commit fb3c01cdd703c72949063ede6a37174b12163fc6 Author: bashynx Date: Sat Oct 24 09:35:12 2026 +0200 dashPi: a self-hosted home dashboard, its sync server and phone app The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end encrypted sync mailbox (PHP + SQLite) and the Android companion app (Flutter), with docs, clean-install checks and screenshots made from demo data. Built mostly with an AI coding assistant; not yet reviewed line by line by a human (see README and SECURITY.md). Co-Authored-By: Claude Opus 5.5 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..444b080 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# each part has its own .gitignore too +.claude/ +.stfolder +.stignore +__pycache__/ +*.pyc diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 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 Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are 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. + + 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. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + 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 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 work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + 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 AGPL, see +. diff --git a/NOTICE.md b/NOTICE.md new file mode 100644 index 0000000..c2ffeb5 --- /dev/null +++ b/NOTICE.md @@ -0,0 +1,20 @@ +# Third-party data + +The code in this repository is under the [AGPL-3.0](LICENSE). The food data it ships (`app/assets/foods.db`) +and the data it can build are not; they keep their own licenses: + +| Data | Where | License | +|---|---|---| +| [USDA FoodData Central](https://fdc.nal.usda.gov/) | The generic foods in `app/assets/foods.db`, built by `dashboard/plugins/food/fdc.py` | Public domain (CC0 1.0) | +| [USDA Food Patterns Equivalents Database (FPED)](https://www.ars.usda.gov/northeast-area/beltsville-md-bhnrc/beltsville-human-nutrition-research-center/food-surveys-research-group/docs/fped-overview/) | Added-sugar figures for those foods | Public domain | +| [Open Food Facts](https://world.openfoodfacts.org/) | The shop products in `app/assets/foods.db` and the server's search archive, built by `dashboard/plugins/food/off.py` | [Open Database License (ODbL) 1.0](https://opendatacommons.org/licenses/odbl/1-0/); the contents under the [Database Contents License](https://opendatacommons.org/licenses/dbcl/1-0/) | + +The Open Food Facts part of `foods.db` is a derivative database under the ODbL. You may use, share and +change it, as long as you credit Open Food Facts and share changed versions of the database under the ODbL. + +The weather icons in `dashboard/plugins/weather/icons/` and `app/assets/weather/` are made from +[Meteocons](https://github.com/basmilius/meteocons) by Bas Milius (MIT License; the license text is next to +them, `LICENSE-meteocons.txt`). `tools/weather-icons.py` makes them. + +At runtime, weather comes from [Open-Meteo](https://open-meteo.com/) (CC BY 4.0) and place names in the app from +OpenStreetMap's Nominatim (© OpenStreetMap contributors, ODbL). diff --git a/README.md b/README.md new file mode 100644 index 0000000..41a5098 --- /dev/null +++ b/README.md @@ -0,0 +1,103 @@ +# dashPi + +A self-hosted home dashboard that runs on a Raspberry Pi with a small 3.5" touch screen and serves the +same information as responsive web pages for a wall TV, a laptop or a phone. A companion Android app works +offline and syncs with it through a small server you host yourself. The sync is end-to-end encrypted, so +the server can't read your data. + +![Home on a TV: clock, weather, room sensors, the day and what's coming up](docs/screenshots/home.png) + +> **Status — please read.** This is a hobby project, built mostly with an AI coding assistant +> (Claude Code), and **the code has not been reviewed line by line by a human**. It runs daily on one +> household's Pi and has the tests and checks in [docs/testing.md](docs/testing.md) (clean installs on +> Debian 12 and 13, an end-to-end sync against a fresh server). Still, treat it as you would any +> unreviewed code: keep the dashboard on your home network, read [SECURITY.md](SECURITY.md), and look at +> what you run. Reviews and issues are very welcome. + +## What it does + +**On the dashboard:** +- Clock, weather (Open-Meteo, no key) and a 14-day forecast. +- Your calendars: ICS feeds (Google, Outlook, holidays), Nextcloud / CalDAV, and the dashboard's own + Local calendar. +- Room sensors: Home Assistant, MQTT, any JSON URL (ESPHome, Tasmota…) or a DS18B20 on the Pi, with + graphs. + +**Optional plugins:** +- Health: body measurements, and sleep, heart rate and workouts from a Gadgetbridge band. +- Food diary, with a bundled food database. +- Cycle tracker. +- Time tracking per customer and project. +- Notes. +- Computer activity from ActivityWatch. + +**In the app:** the same health, food, cycle, work and notes data offline, plus weather and the band +relay. + +| | | +|---|---| +| ![The week view](docs/screenshots/week.png) | ![The weather page](docs/screenshots/weather.png) | +| **Week:** calendar events in a week or month view | **Weather:** 48 hours, 14 days, air quality, more places | +| ![Health overview](docs/screenshots/health.png) | ![Sleep](docs/screenshots/sleep.png) | +| **Health:** steps, BMI, sleep, workouts, cycle, food at a glance | **Sleep:** stages per night, regularity, what stands out | +| ![Food diary](docs/screenshots/food.png) | ![Room sensors](docs/screenshots/stations.png) | +| **Food:** a diary from the food database, targets, nutrients | **Stations:** each sensor's history, 24 hours to a year | +| ![Time tracking](docs/screenshots/work.png) | ![Computer activity](docs/screenshots/activity.png) | +| **Work:** drag to book time, billable or not, a report | **Activity:** your computers' time, sorted into categories | +| ![Notes](docs/screenshots/notes.png) | ![Settings](docs/screenshots/settings.png) | +| **Notes:** Markdown, folders, tags, checklists | **Settings:** everything is set up in the browser | + +The 3.5" screen on the Pi (Home, sensors, weather, calendar): + +![Home](docs/screenshots/screen-home.png) ![Sensors](docs/screenshots/screen-temp.png) +![Weather](docs/screenshots/screen-weather.png) ![Calendar](docs/screenshots/screen-cal.png) + +The phone app (Health, Food, Work, Notes, Weather): + + + + + +The pictures come from a demo with made-up data: [docs/screenshots/make.py](docs/screenshots/make.py) builds +it and takes the dashboard's, [docs/screenshots/app.py](docs/screenshots/app.py) the app's on an emulator. + +## The parts + +| Folder | What | Runs on | +|---|---|---| +| [`dashboard/`](dashboard/) | The dashboard: Python, Pillow straight to the framebuffer, Flask web pages, plugins | Raspberry Pi, or any Linux machine (web pages only) | +| [`server/`](server/) | The sync mailbox: PHP + SQLite, stores only encrypted batches | Any web host with PHP 8.1+ and HTTPS | +| [`app/`](app/) | The phone app: Flutter, Android | Your phone | + +You don't need all three: the dashboard works on its own. The server and app are only for syncing with +a phone, or between dashboards. + +## Set up + +1. **Dashboard** ([dashboard/](dashboard/README.md), [docs/dashboard.md](docs/dashboard.md)): + `sudo ./dashboard/install.sh` on the Pi, then open `http://:8080/settings`. +2. **Sync server** (optional; [server/](server/README.md), [docs/server.md](docs/server.md)): copy + `server/` to your host and run `bin/setup-server.sh `. Paste the token it prints into + the dashboard's Settings ▸ General ▸ Sync. +3. **Phone app** (optional; [app/](app/README.md), [docs/app.md](docs/app.md)): build it, then scan the + QR code from the dashboard's Settings ▸ General ▸ Devices. + +After installing, everything is set from the dashboard's Settings page: users, sync and devices, web +access, the screen, sensors, calendars, backup and restore. + +How it fits together: [docs/architecture.md](docs/architecture.md). The sync protocol: +[server/PROTOCOL.md](server/PROTOCOL.md). + +## Security in one paragraph + +The dashboard is made for a home network. It serves plain HTTP and only answers to its own names and IP +addresses (against DNS rebinding). Until you create the admin account, everyone on the network is admin; +creating it needs a setup code from the service log. Without a login, visitors get a read-only +"household" view whose content you choose. Members are logins that can see only some sections, but they +share the owner's data in those sections; they are not separate accounts. Read [SECURITY.md](SECURITY.md) +before exposing anything beyond your LAN. + +## License + +[AGPL-3.0](LICENSE). The bundled food database includes data from USDA FoodData Central (public domain) +and Open Food Facts (ODbL); see [NOTICE.md](NOTICE.md). diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..8924c9b --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,31 @@ +# Security + +> **Not reviewed by a human.** Most of this code was written with an AI coding assistant and hasn't been +> audited line by line. The design below is deliberate and the checks in [docs/testing.md](docs/testing.md) +> pass, but expect bugs a careful review would catch. Don't expose the dashboard to the internet. A review +> of the crypto (`dashboard/sync.py`, `app/lib/sync/crypto.dart`) and the auth (`dashboard/auth.py`, +> `dashboard/web.py`) is the most useful contribution. + +## What it's built for + +The dashboard runs on your **home network**. The sync server is on the internet, but it only stores +data it can't read. + +| Part | Protects | Doesn't protect | +|---|---|---| +| Dashboard web pages | Logins (PBKDF2, a lockout per address), writes only from its own pages (JSON + `Origin`), only its own host names (against DNS rebinding), a setup code for the first admin | **Plain HTTP:** passwords and session cookies cross your LAN unencrypted. Put it behind a TLS reverse proxy if your network isn't trusted. Don't port-forward it. | +| Users | The household view is read only; members only see the sections they're given | Members **share the owner's data** in those sections. It's one household's dashboard, not a multi-tenant app | +| Sync | End-to-end encrypted (XChaCha20-Poly1305); the key is wrapped with Argon2id; the server sees sizes and times only | Someone with your passphrase or recovery key. The server can delay or withhold batches, but it can't read or forge them | +| Secrets | `dash_config.json` and `dash_data/` are mode 600; Settings never shows a stored password | Anyone with access to the machine as the service user | + +## Before you start + +- Create the admin account right away (Settings ▸ Users). Until then, everyone on the network is admin. +- Choose the household view's calendars on purpose. It's what anyone on your Wi-Fi sees without a login. +- Use a passphrase of 4+ random words for sync, and store the recovery key offline. +- Keep the sync server's folder outside any other site's document root ([docs/server.md](docs/server.md)). + +## Reporting a problem + +Please don't open a public issue for a security bug. Email it to **bashynx@bashynx.com** instead, with +"dashPi security" in the subject. diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..ca13433 --- /dev/null +++ b/app/.gitignore @@ -0,0 +1,52 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins-dependencies +.pub-cache/ +.pub/ +/build/ +/coverage/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release + +# Syncthing, if you sync the source between computers +.stignore +.stfolder + +# your publish settings (tool/publish.env.example) +tool/publish.env diff --git a/app/.metadata b/app/.metadata new file mode 100644 index 0000000..cc161b7 --- /dev/null +++ b/app/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "6b182d2c7585eba26d4edce0f97630effd256c33" + channel: "stable" + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 6b182d2c7585eba26d4edce0f97630effd256c33 + base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33 + - platform: android + create_revision: 6b182d2c7585eba26d4edce0f97630effd256c33 + base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/app/CHANGELOG.md b/app/CHANGELOG.md new file mode 100644 index 0000000..171c1b3 --- /dev/null +++ b/app/CHANGELOG.md @@ -0,0 +1,69 @@ +# Changelog + +What changed in each published build of the app. `tool/publish.sh` shows the entry for the version in +`pubspec.yaml` as the update notes on the phones (Sync page ▸ App) — write it before publishing. + +## Unreleased + +- Connect by scanning the code from the dashboard (Settings ▸ General ▸ Devices ▸ Add a device). +- Weather: the dashboard's home and extra places come with the sync. +- Sync page: the dashboard's address for "sync now" can be set there. +- Food: the targets follow the dashboard's Settings ▸ Food (weight goal, macro split, limits) instead of + fixed values in the app. +- The band's data goes with the phone's time zone, so the dashboard reads its times right without a + setting. + +## 1.1.2 — 2026-10-23 + +- Work: grips at the top and bottom of a block — hold one and drag to start earlier / later or end + earlier / later (15-minute steps, never shorter than 15 minutes; Undo). +- Work: moving a block, drawing a new one and the grips start after a shorter hold (¼ s instead of ½ s). +- Work: dragging near the top or bottom edge scrolls the day, so a block can be drawn or moved past + what's on screen. +- Food: "Search all products" — 2 million+ Open Food Facts products from every country, with country, + brand and Nutri-Score filters (needs a connection); a product you pick is kept and synced, so it works + like any other food afterwards, on the dashboard too. +- Food: barcode scanner (the camera button in the search box) — finds the product here, else in all + products. Reads the code on the phone (ZXing), no Google services. +- Weather: "Current location" asks Android itself (no Google services in the app any more); when it + can't tell — not allowed, switched off, no fix — a red banner on top says why and what to do, and + home (the first place) is shown instead. +- Food: the built-in food database has the shop products of the countries it was built for only (the + rest are in "all products"; ones you've used stay). +- Food: added sugar — USDA's own added-sugar figures for its prepared foods; shop products by their + ingredients (any language) and the label's figure; names matched without accents and in more languages + (RO, SK, CZ, HU, DE, PL, FR, IT, ES, PT); plain oats and grits count as natural. +- Food: My foods have "Sugar counts as" (estimated / all added / milk's own / natural) for when the + estimate is wrong. + +## 1.1.1 — 2026-10-22 + +- Work: hold an empty spot on the timeline and drag up or down to book that span; the times show + while you drag, letting go opens the entry with them filled in. +- "Undo" messages (cycle day, moved work block, note to the trash) disappear on their own + instead of staying on screen until tapped. +- Food: "Free sugar" is now "Added sugar" — the same estimate (added sugar, honey, syrups, fruit juice), + a clearer name. +- Food: whole and dried fruit no longer count as added sugar (every fruit did, through USDA's + "Fruits and Fruit Juices" category). +- Food: snacks, fast food, drinks and baby food are judged by what they are (cola, bars, coleslaw count; + coffee, crisps, burgers, plain baby fruit don't); wine, cider and beer count like juice. +- Sync: the dashboards' raw ActivityWatch data is skipped — the phone never reads it. + +## 1.1.0 — 2026-10-21 + +- Notes: markdown notes with folders, #tags, pinned notes, checklists, search and trash — synced with + the dashboard. + +## 1.0.0 (build 2) — 2026-10-21 + +- Work: the week (a day's timeline on a phone, all seven days in landscape), booking and editing time, + the report (CSV to the clipboard), customers and their editor; the calendar's events behind the week + and Activity's blocks beside it; drag blocks to another time or day. +- After sending the band's data, the Pi on the home network syncs at once. +- The app updates itself from the sync server. + +## 1.0.0 (build 1) — 2026-10-21 + +- First build: Health (overview, cycle, body, sleep, heart, activity), Food, Weather (with the home + stations), sync through the sync server, the Gadgetbridge band relay and the hourly background sync. diff --git a/app/README.md b/app/README.md new file mode 100644 index 0000000..bd3f756 --- /dev/null +++ b/app/README.md @@ -0,0 +1,58 @@ +# The phone app + +The dashboard's companion for Android (Flutter). It keeps its own copy of your data, works offline, and +syncs end-to-end encrypted through your sync server with the dashboard and your other devices. + +- **Health:** + - Body measurements, BMI and body fat by several formulas. + - Sleep, heart rate and workouts as the dashboard works them out. + - The cycle tracker. +- **Food:** a diary with the bundled food database, a barcode scanner, and the server's product archive. +- **Work:** book time in a week view by dragging. +- **Notes:** Markdown, folders, tags, checklists. +- **Weather:** your places, the dashboard's places and where you are. +- **Band relay:** reads Gadgetbridge's database export on the phone and sends the band's new data to the + dashboard. No Syncthing needed. +- **Updates itself** from your server (optional). + +| | | | | +|---|---|---|---| +| ![Health](../docs/screenshots/app-health.png) | ![Sleep](../docs/screenshots/app-sleep.png) | ![Body](../docs/screenshots/app-body.png) | ![Cycle](../docs/screenshots/app-cycle.png) | +| **Health** overview | **Sleep** | **Body** | **Cycle** | +| ![Food](../docs/screenshots/app-food.png) | ![Work](../docs/screenshots/app-work.png) | ![Notes](../docs/screenshots/app-notes.png) | ![Weather](../docs/screenshots/app-weather.png) | +| **Food** diary | **Work** week | **Notes** | **Weather** | + +The pictures come from the demo dashboard's made-up data on an emulator: +[docs/screenshots/app.py](../docs/screenshots/app.py). + +## Build and connect + +```bash +cd app +flutter pub get +flutter test +flutter build apk --release # → build/app/outputs/flutter-apk/app-release.apk +``` + +You need Flutter 3.44 (Dart 3.12+) and the Android SDK. Sign it with your own key, or your next build +can't update it. Then on the dashboard go to **Settings ▸ General ▸ Devices ▸ Add a device**, and in the +app tap **Scan the code from the dashboard** and type the passphrase. + +Signing, optional built-in defaults (`DEV_SERVER`, `PI_URL`, `HOME_PLACES`), the band relay and +publishing updates: [../docs/app.md](../docs/app.md). What changed in each build: +[CHANGELOG.md](CHANGELOG.md). + +## Layout + +``` +lib/main.dart start, the connect screen +lib/app/ the shell (tabs), background sync, the updater, location, the code scanner +lib/sync/ the sync: store.dart (the local copy + merge), client.dart, crypto.dart, the kick, the band relay +lib/health/ work/ notes/ weather/ the sections +packages/gb_export/ a small Android plugin: Gadgetbridge's export, the phone's time zone (works in the background too) +assets/foods.db the food database (also the dashboard's starting one) +tool/publish.sh build + upload an update (tool/publish.env) +``` + +The sync format is the dashboard's ([../server/PROTOCOL.md](../server/PROTOCOL.md)); both sides merge the +same way, last writer wins per row. diff --git a/app/analysis_options.yaml b/app/analysis_options.yaml new file mode 100644 index 0000000..0d29021 --- /dev/null +++ b/app/analysis_options.yaml @@ -0,0 +1,28 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/lints. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/app/android/.gitignore b/app/android/.gitignore new file mode 100644 index 0000000..be3943c --- /dev/null +++ b/app/android/.gitignore @@ -0,0 +1,14 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java +.cxx/ + +# Remember to never publicly share your keystore. +# See https://flutter.dev/to/reference-keystore +key.properties +**/*.keystore +**/*.jks diff --git a/app/android/app/build.gradle.kts b/app/android/app/build.gradle.kts new file mode 100644 index 0000000..1670f34 --- /dev/null +++ b/app/android/app/build.gradle.kts @@ -0,0 +1,68 @@ +import java.util.Properties + +plugins { + id("com.android.application") + // The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins. + id("dev.flutter.flutter-gradle-plugin") +} + +// Release signing: android/key.properties (not in git) → the keystore in ~/keys (storeFile, storePassword, +// keyAlias, keyPassword). Without it, release builds fall back to the debug key (and can't update a release install). +val keyProps = Properties().apply { + val f = rootProject.file("key.properties") + if (f.exists()) f.inputStream().use { load(it) } +} + +android { + namespace = "dev.bashynx.dash_app" + compileSdk = flutter.compileSdkVersion + ndkVersion = flutter.ndkVersion + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId = "dev.bashynx.dash_app" + // You can update the following values to match your application needs. + // For more information, see: https://flutter.dev/to/review-gradle-config. + minSdk = flutter.minSdkVersion + targetSdk = flutter.targetSdkVersion + versionCode = flutter.versionCode + versionName = flutter.versionName + } + + signingConfigs { + if (keyProps.getProperty("storeFile") != null) { + create("release") { + storeFile = file(keyProps.getProperty("storeFile")) + storePassword = keyProps.getProperty("storePassword") + keyAlias = keyProps.getProperty("keyAlias") + keyPassword = keyProps.getProperty("keyPassword") + } + } + } + + if (keyProps.getProperty("storeFile") == null) { + logger.warn("android/key.properties is missing: this release build is signed with the debug key " + + "(it can't update an installed release). See docs/app.md.") + } + + buildTypes { + release { + signingConfig = signingConfigs.findByName("release") ?: signingConfigs.getByName("debug") + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +flutter { + source = "../.." +} diff --git a/app/android/app/src/debug/AndroidManifest.xml b/app/android/app/src/debug/AndroidManifest.xml new file mode 100644 index 0000000..9af1674 --- /dev/null +++ b/app/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,9 @@ + + + + + + diff --git a/app/android/app/src/main/AndroidManifest.xml b/app/android/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..4adedf6 --- /dev/null +++ b/app/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,61 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/app/android/app/src/main/kotlin/dev/bashynx/dash_app/MainActivity.kt b/app/android/app/src/main/kotlin/dev/bashynx/dash_app/MainActivity.kt new file mode 100644 index 0000000..5bff79a --- /dev/null +++ b/app/android/app/src/main/kotlin/dev/bashynx/dash_app/MainActivity.kt @@ -0,0 +1,141 @@ +package dev.bashynx.dash_app + +import android.Manifest +import android.content.Intent +import android.content.pm.PackageManager +import android.location.Location +import android.location.LocationListener +import android.location.LocationManager +import android.net.ConnectivityManager +import android.net.Uri +import android.os.Build +import android.os.CancellationSignal +import android.os.Handler +import android.os.Looper +import android.provider.Settings +import androidx.core.content.FileProvider +import io.flutter.embedding.android.FlutterActivity +import io.flutter.embedding.engine.FlutterEngine +import io.flutter.plugin.common.MethodChannel +import java.io.File +import java.security.MessageDigest + +// The Gadgetbridge export bridge lives in packages/gb_export (a plugin, so background tasks have it too). +// "dash/update" (lib/app/updater.dart), only while the app is on screen: +// info() → {code, name, metered, canInstall} +// install(path, sha256) → "started" | "allow" (opened the "install unknown apps" setting first) | "bad" (checksum) +// "dash/location" (lib/app/location.dart) — Android's own LocationManager, never Google's Play services: +// status() → {allowed, enabled} ask() → allowed (the permission dialog; refused for good: false at once) +// last() → the newest last-known fix {lat, lon, time, accuracy} | null current(timeoutMs) → a new fix | null +class MainActivity : FlutterActivity() { + private var asking: MethodChannel.Result? = null + + private fun allowed() = checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED + + private fun fix(l: Location) = mapOf("lat" to l.latitude, "lon" to l.longitude, "time" to l.time, "accuracy" to l.accuracy.toDouble()) + + override fun onRequestPermissionsResult(code: Int, permissions: Array, grants: IntArray) { + super.onRequestPermissionsResult(code, permissions, grants) + if (code == ASK_LOCATION) { + asking?.success(allowed()) + asking = null + } + } + + override fun configureFlutterEngine(engine: FlutterEngine) { + super.configureFlutterEngine(engine) + MethodChannel(engine.dartExecutor.binaryMessenger, "dash/location").setMethodCallHandler { call, result -> + val lm = getSystemService(LOCATION_SERVICE) as LocationManager + try { + when (call.method) { + "status" -> result.success(mapOf( + "allowed" to allowed(), + "enabled" to if (Build.VERSION.SDK_INT >= 28) lm.isLocationEnabled else lm.getProviders(true).isNotEmpty())) + "ask" -> if (allowed()) result.success(true) else { + asking?.success(false) + asking = result + requestPermissions(arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION), ASK_LOCATION) + } + "last" -> result.success(if (!allowed()) null else + lm.getProviders(true).mapNotNull { lm.getLastKnownLocation(it) }.maxByOrNull { it.time }?.let(::fix)) + "current" -> { + val provider = listOf(LocationManager.NETWORK_PROVIDER, LocationManager.GPS_PROVIDER) + .firstOrNull { lm.isProviderEnabled(it) } + if (!allowed() || provider == null) return@setMethodCallHandler result.success(null) + var done = false + val main = Handler(Looper.getMainLooper()) + fun reply(l: Location?) { + if (!done) { + done = true + result.success(l?.let(::fix)) + } + } + val wait = (call.argument("timeoutMs") ?: 20000).toLong() + if (Build.VERSION.SDK_INT >= 30) { + val cancel = CancellationSignal() + lm.getCurrentLocation(provider, cancel, mainExecutor) { reply(it) } + main.postDelayed({ cancel.cancel(); reply(null) }, wait) + } else { + val once = object : LocationListener { + override fun onLocationChanged(l: Location) { + lm.removeUpdates(this) + reply(l) + } + } + @Suppress("DEPRECATION") + lm.requestSingleUpdate(provider, once, Looper.getMainLooper()) + main.postDelayed({ lm.removeUpdates(once); reply(null) }, wait) + } + } + else -> result.notImplemented() + } + } catch (e: SecurityException) { + result.success(null) // the permission went away meanwhile + } + } + MethodChannel(engine.dartExecutor.binaryMessenger, "dash/update").setMethodCallHandler { call, result -> + when (call.method) { + "info" -> { + val p = packageManager.getPackageInfo(packageName, 0) + val code = if (Build.VERSION.SDK_INT >= 28) p.longVersionCode else @Suppress("DEPRECATION") p.versionCode.toLong() + val cm = getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager + result.success(mapOf("code" to code, "name" to (p.versionName ?: ""), "metered" to cm.isActiveNetworkMetered, + "canInstall" to packageManager.canRequestPackageInstalls())) + } + "install" -> { + val f = File(call.argument("path")!!) + val want = call.argument("sha256") ?: "" + if (!f.exists() || (want.isNotEmpty() && sha256(f) != want.lowercase())) { + result.success("bad") + } else if (!packageManager.canRequestPackageInstalls()) { + startActivity(Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, Uri.parse("package:$packageName"))) + result.success("allow") + } else { + val uri = FileProvider.getUriForFile(this, "$packageName.updates", f) + startActivity(Intent(Intent.ACTION_VIEW).setDataAndType(uri, "application/vnd.android.package-archive") + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_ACTIVITY_NEW_TASK)) + result.success("started") + } + } + else -> result.notImplemented() + } + } + } + + companion object { + private const val ASK_LOCATION = 41 + } + + private fun sha256(f: File): String { + val md = MessageDigest.getInstance("SHA-256") + f.inputStream().use { s -> + val buf = ByteArray(1 shl 16) + while (true) { + val n = s.read(buf) + if (n < 0) break + md.update(buf, 0, n) + } + } + return md.digest().joinToString("") { "%02x".format(it) } + } +} diff --git a/app/android/app/src/main/res/drawable-v21/launch_background.xml b/app/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100644 index 0000000..f74085f --- /dev/null +++ b/app/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/app/android/app/src/main/res/drawable/launch_background.xml b/app/android/app/src/main/res/drawable/launch_background.xml new file mode 100644 index 0000000..304732f --- /dev/null +++ b/app/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/app/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/app/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 0000000..80b730f --- /dev/null +++ b/app/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 0000000..be6220e Binary files /dev/null and b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..1dc4b3f Binary files /dev/null and b/app/android/app/src/main/res/mipmap-hdpi/ic_launcher_foreground.png differ diff --git a/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 0000000..51c048e Binary files /dev/null and b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..e5300b7 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-mdpi/ic_launcher_foreground.png differ diff --git a/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 0000000..d961c7f Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..0b393cf Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xhdpi/ic_launcher_foreground.png differ diff --git a/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 0000000..5fcb39e Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..4178100 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_foreground.png differ diff --git a/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 0000000..52399d2 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png new file mode 100644 index 0000000..b804ef7 Binary files /dev/null and b/app/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foreground.png differ diff --git a/app/android/app/src/main/res/values-night/styles.xml b/app/android/app/src/main/res/values-night/styles.xml new file mode 100644 index 0000000..06952be --- /dev/null +++ b/app/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/app/android/app/src/main/res/values/ic_launcher_background.xml b/app/android/app/src/main/res/values/ic_launcher_background.xml new file mode 100644 index 0000000..9bd8811 --- /dev/null +++ b/app/android/app/src/main/res/values/ic_launcher_background.xml @@ -0,0 +1,4 @@ + + + #0D1017 + diff --git a/app/android/app/src/main/res/values/styles.xml b/app/android/app/src/main/res/values/styles.xml new file mode 100644 index 0000000..cb1ef88 --- /dev/null +++ b/app/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/app/android/app/src/main/res/xml/network_security_config.xml b/app/android/app/src/main/res/xml/network_security_config.xml new file mode 100644 index 0000000..d5d70e6 --- /dev/null +++ b/app/android/app/src/main/res/xml/network_security_config.xml @@ -0,0 +1,7 @@ + + + + + diff --git a/app/android/app/src/main/res/xml/update_paths.xml b/app/android/app/src/main/res/xml/update_paths.xml new file mode 100644 index 0000000..cb5b6d1 --- /dev/null +++ b/app/android/app/src/main/res/xml/update_paths.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/app/android/app/src/profile/AndroidManifest.xml b/app/android/app/src/profile/AndroidManifest.xml new file mode 100644 index 0000000..399f698 --- /dev/null +++ b/app/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,7 @@ + + + + diff --git a/app/android/build.gradle.kts b/app/android/build.gradle.kts new file mode 100644 index 0000000..dbee657 --- /dev/null +++ b/app/android/build.gradle.kts @@ -0,0 +1,24 @@ +allprojects { + repositories { + google() + mavenCentral() + } +} + +val newBuildDir: Directory = + rootProject.layout.buildDirectory + .dir("../../build") + .get() +rootProject.layout.buildDirectory.value(newBuildDir) + +subprojects { + val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name) + project.layout.buildDirectory.value(newSubprojectBuildDir) +} +subprojects { + project.evaluationDependsOn(":app") +} + +tasks.register("clean") { + delete(rootProject.layout.buildDirectory) +} diff --git a/app/android/gradle.properties b/app/android/gradle.properties new file mode 100644 index 0000000..e96108c --- /dev/null +++ b/app/android/gradle.properties @@ -0,0 +1,6 @@ +org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError +android.useAndroidX=true +# This newDsl flag was added by the Flutter template +android.newDsl=false +# This builtInKotlin flag was added by the Flutter template +android.builtInKotlin=false diff --git a/app/android/gradle/wrapper/gradle-wrapper.properties b/app/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..2d428bf --- /dev/null +++ b/app/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.1.0-all.zip diff --git a/app/android/settings.gradle.kts b/app/android/settings.gradle.kts new file mode 100644 index 0000000..c21f0c5 --- /dev/null +++ b/app/android/settings.gradle.kts @@ -0,0 +1,26 @@ +pluginManagement { + val flutterSdkPath = + run { + val properties = java.util.Properties() + file("local.properties").inputStream().use { properties.load(it) } + val flutterSdkPath = properties.getProperty("flutter.sdk") + require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" } + flutterSdkPath + } + + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } +} + +plugins { + id("dev.flutter.flutter-plugin-loader") version "1.0.0" + id("com.android.application") version "9.0.1" apply false + id("org.jetbrains.kotlin.android") version "2.3.20" apply false +} + +include(":app") diff --git a/app/assets/foods.db b/app/assets/foods.db new file mode 100644 index 0000000..91c643f Binary files /dev/null and b/app/assets/foods.db differ diff --git a/app/assets/weather/01d.png b/app/assets/weather/01d.png new file mode 100644 index 0000000..8753306 Binary files /dev/null and b/app/assets/weather/01d.png differ diff --git a/app/assets/weather/01n.png b/app/assets/weather/01n.png new file mode 100644 index 0000000..cd5df5f Binary files /dev/null and b/app/assets/weather/01n.png differ diff --git a/app/assets/weather/02d.png b/app/assets/weather/02d.png new file mode 100644 index 0000000..90fb73a Binary files /dev/null and b/app/assets/weather/02d.png differ diff --git a/app/assets/weather/02n.png b/app/assets/weather/02n.png new file mode 100644 index 0000000..5f9f762 Binary files /dev/null and b/app/assets/weather/02n.png differ diff --git a/app/assets/weather/03d.png b/app/assets/weather/03d.png new file mode 100644 index 0000000..108f8c6 Binary files /dev/null and b/app/assets/weather/03d.png differ diff --git a/app/assets/weather/03n.png b/app/assets/weather/03n.png new file mode 100644 index 0000000..824ec7e Binary files /dev/null and b/app/assets/weather/03n.png differ diff --git a/app/assets/weather/04d.png b/app/assets/weather/04d.png new file mode 100644 index 0000000..9190826 Binary files /dev/null and b/app/assets/weather/04d.png differ diff --git a/app/assets/weather/04n.png b/app/assets/weather/04n.png new file mode 100644 index 0000000..9190826 Binary files /dev/null and b/app/assets/weather/04n.png differ diff --git a/app/assets/weather/09d.png b/app/assets/weather/09d.png new file mode 100644 index 0000000..0b34fd5 Binary files /dev/null and b/app/assets/weather/09d.png differ diff --git a/app/assets/weather/09n.png b/app/assets/weather/09n.png new file mode 100644 index 0000000..0b34fd5 Binary files /dev/null and b/app/assets/weather/09n.png differ diff --git a/app/assets/weather/10d.png b/app/assets/weather/10d.png new file mode 100644 index 0000000..7c72e41 Binary files /dev/null and b/app/assets/weather/10d.png differ diff --git a/app/assets/weather/10n.png b/app/assets/weather/10n.png new file mode 100644 index 0000000..7c72e41 Binary files /dev/null and b/app/assets/weather/10n.png differ diff --git a/app/assets/weather/11d.png b/app/assets/weather/11d.png new file mode 100644 index 0000000..da34a4d Binary files /dev/null and b/app/assets/weather/11d.png differ diff --git a/app/assets/weather/11n.png b/app/assets/weather/11n.png new file mode 100644 index 0000000..da34a4d Binary files /dev/null and b/app/assets/weather/11n.png differ diff --git a/app/assets/weather/13d.png b/app/assets/weather/13d.png new file mode 100644 index 0000000..463c769 Binary files /dev/null and b/app/assets/weather/13d.png differ diff --git a/app/assets/weather/13n.png b/app/assets/weather/13n.png new file mode 100644 index 0000000..463c769 Binary files /dev/null and b/app/assets/weather/13n.png differ diff --git a/app/assets/weather/50d.png b/app/assets/weather/50d.png new file mode 100644 index 0000000..7d83580 Binary files /dev/null and b/app/assets/weather/50d.png differ diff --git a/app/assets/weather/50n.png b/app/assets/weather/50n.png new file mode 100644 index 0000000..7d83580 Binary files /dev/null and b/app/assets/weather/50n.png differ diff --git a/app/assets/weather/LICENSE-meteocons.txt b/app/assets/weather/LICENSE-meteocons.txt new file mode 100644 index 0000000..1588fe9 --- /dev/null +++ b/app/assets/weather/LICENSE-meteocons.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-present Bas Milius + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/app/lib/app/background.dart b/app/lib/app/background.dart new file mode 100644 index 0000000..05c2340 --- /dev/null +++ b/app/lib/app/background.dart @@ -0,0 +1,64 @@ +// The sync in the background (Android WorkManager), also while the app is closed: about once an hour +// with a network — relay the band's new rows from Gadgetbridge's export (gb_relay.dart), then sync. +// Runs in its own engine and isolate; shares the data file with the app (SQLite waits for the other). +import 'package:flutter/widgets.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:workmanager/workmanager.dart'; + +import '../sync/client.dart'; +import '../sync/crypto.dart'; +import '../sync/gb_relay.dart'; +import '../sync/kick.dart'; +import '../sync/store.dart'; +import '../weather/stations.dart' show stationDays; + +const _task = 'band-sync'; +const every = Duration(hours: 1); + +Future dataPath() async => '${(await getApplicationSupportDirectory()).path}/data.db'; + +@pragma('vm:entry-point') +void backgroundDispatcher() { + Workmanager().executeTask((task, input) async { + WidgetsFlutterBinding.ensureInitialized(); + final s = await SyncSettings.load(); + if (s == null) return true; // disconnected meanwhile + final store = SyncStore(await dataPath(), s.device); + try { + var band = 0; + try { + band = await GbRelay(store).run() ?? 0; + } catch (e) { + debugPrint('background: gb relay: $e'); + } + final crypto = await SyncCrypto.create(); + var res = await runSync(s, store, crypto); + if (band > 0 && res.pushed > 0 && await kickPi(s, store, crypto)) res = await runSync(s, store, crypto); // kick.dart + store.dropOld('stations.hourly', 't', DateTime.now().millisecondsSinceEpoch ~/ 1000 - stationDays * 86400); + store.setMeta('bg_ok', DateTime.now().millisecondsSinceEpoch); + debugPrint('background: $res'); + return true; + } catch (e) { + debugPrint('background: $e'); + return false; // WorkManager tries again later + } finally { + store.db.close(); + } + }); +} + +/// Start (or keep) the hourly background sync — after connecting and at every app start. +Future scheduleBackground() async { + await Workmanager().initialize(backgroundDispatcher); + await Workmanager().registerPeriodicTask(_task, _task, + frequency: every, + constraints: Constraints(networkType: NetworkType.connected), + existingWorkPolicy: ExistingPeriodicWorkPolicy.update); + // test builds only (--dart-define=BG_TEST=true): the same work once, 30 s after start — kill the app to see it run + if (const bool.fromEnvironment('BG_TEST')) { + await Workmanager().registerOneOffTask('$_task-test', _task, + initialDelay: const Duration(seconds: 30), existingWorkPolicy: ExistingWorkPolicy.replace); + } +} + +Future stopBackground() => Workmanager().cancelByUniqueName(_task); diff --git a/app/lib/app/location.dart b/app/lib/app/location.dart new file mode 100644 index 0000000..3611073 --- /dev/null +++ b/app/lib/app/location.dart @@ -0,0 +1,33 @@ +// Where the phone is, from Android itself (MainActivity's "dash/location": LocationManager — never Google's Play +// services): the permission asked once, the newest last-known fix, else a new one. The town is enough (coarse). +import 'package:flutter/services.dart'; + +const _ch = MethodChannel('dash/location'); + +/// A fix (lat, lon), or why there's none: "location not allowed" / "location off" / "no location found". +Future<({double lat, double lon})?> whereAmI({void Function(String why)? none}) async { + try { + final st = (await _ch.invokeMapMethod('status'))!; + if (st['allowed'] != true && await _ch.invokeMethod('ask') != true) { + none?.call('location not allowed'); + return null; + } + if (st['enabled'] != true) { + none?.call('location off'); + return null; + } + final fix = await _ch.invokeMapMethod('last') ?? + await _ch.invokeMapMethod('current', {'timeoutMs': 20000}); + if (fix == null) { + none?.call('no location found'); + return null; + } + return (lat: (fix['lat'] as num).toDouble(), lon: (fix['lon'] as num).toDouble()); + } on PlatformException { + none?.call('no location found'); + return null; + } on MissingPluginException { + none?.call('no location found'); // not on Android (tests) + return null; + } +} diff --git a/app/lib/app/scanner.dart b/app/lib/app/scanner.dart new file mode 100644 index 0000000..77e13f2 --- /dev/null +++ b/app/lib/app/scanner.dart @@ -0,0 +1,43 @@ +// The camera, until a code is read: ZXing (flutter_zxing: open source, on the phone — no Google services) +// over Flutter's camera plugin. The food barcodes (health/food_archive.dart) and the connect screen's QR +// code from the dashboard's Settings ▸ General ▸ Sync (main.dart). +import 'package:flutter/material.dart'; +import 'package:flutter_zxing/flutter_zxing.dart'; + +/// → the code's text once `accept` takes it, or null (closed). +Future scanCode(BuildContext context, + {required String title, required int format, required bool Function(String) accept}) => + Navigator.of(context).push(MaterialPageRoute( + builder: (_) => _Scanner(title: title, format: format, accept: accept), fullscreenDialog: true)); + +class _Scanner extends StatefulWidget { + const _Scanner({required this.title, required this.format, required this.accept}); + final String title; + final int format; + final bool Function(String) accept; + @override + State<_Scanner> createState() => _ScannerState(); +} + +class _ScannerState extends State<_Scanner> { + bool done = false; + + @override + Widget build(BuildContext context) => Scaffold( + backgroundColor: Colors.black, + appBar: AppBar(title: Text(widget.title)), + body: ReaderWidget( + codeFormat: widget.format, + tryHarder: true, + showGallery: false, + showToggleCamera: false, + scanDelay: const Duration(milliseconds: 300), + onScan: (code) { + final v = code.text; + if (done || !code.isValid || v == null || !widget.accept(v)) return; + done = true; + Navigator.of(context).pop(v); + }, + ), + ); +} diff --git a/app/lib/app/shell.dart b/app/lib/app/shell.dart new file mode 100644 index 0000000..7a3c826 --- /dev/null +++ b/app/lib/app/shell.dart @@ -0,0 +1,346 @@ +// The app's frame: Health | Food | Work | Notes | Weather at the bottom (Work's ⋮: Report, Customers); Health's sections as tabs at the +// top (Overview, Cycle, Body, Sleep, Heart, Activity — the band's parts from the Pi's summaries). +// The sync icon (top right) shows the state and opens the Sync page. +import 'package:flutter/material.dart'; + +import '../health/activity_page.dart'; +import '../notes/notes_page.dart'; +import '../sync/gb_relay.dart'; +import '../weather/weather_page.dart'; +import '../work/customers_page.dart'; +import '../work/report_page.dart'; +import '../work/work_page.dart'; +import '../health/body_page.dart'; +import '../health/cycle_doctor.dart'; +import '../health/cycle_model.dart' show CycleSettings; +import '../health/cycle_page.dart'; +import '../health/food_history.dart'; +import '../health/food_page.dart'; +import '../health/my_foods.dart'; +import '../health/heart_page.dart'; +import '../health/overview_page.dart'; +import '../health/range.dart'; +import '../health/sleep_page.dart'; +import '../sync/client.dart'; +import '../sync/kick.dart' show piUrl; +import 'sync_service.dart'; +import 'updater.dart'; +import 'theme.dart'; + +class Shell extends StatefulWidget { + const Shell({super.key, required this.sync, required this.onForget}); + final SyncService sync; + final Future Function() onForget; + @override + State createState() => _ShellState(); +} + +class _ShellState extends State { + int section = 0; + late final range = HealthRange(widget.sync.store); // the period every Health chart shows + + /// Food's ⋮: History, My foods. + Widget _foodMenu() => PopupMenuButton( + icon: const Icon(Icons.more_vert), + color: card2, + onSelected: (k) => Navigator.push(context, MaterialPageRoute(builder: (_) => k == 'history' + ? FoodHistoryPage(sync: widget.sync, range: range) + : MyFoodsPage(sync: widget.sync))), + itemBuilder: (_) => const [ + PopupMenuItem(value: 'history', child: Text('History')), + PopupMenuItem(value: 'foods', child: Text('My foods')), + ], + ); + + /// Work's ⋮: Report, Customers. + Widget _workMenu() => PopupMenuButton( + icon: const Icon(Icons.more_vert), + color: card2, + onSelected: (k) => Navigator.push(context, MaterialPageRoute(builder: (_) => k == 'report' + ? ReportPage(sync: widget.sync) + : CustomersPage(sync: widget.sync))), + itemBuilder: (_) => const [ + PopupMenuItem(value: 'report', child: Text('Report')), + PopupMenuItem(value: 'customers', child: Text('Customers')), + ], + ); + + /// Health's ⋮ (next to the sync icon): what isn't a tab — the doctor summary. + Widget _healthMenu() => PopupMenuButton( + icon: const Icon(Icons.more_vert), + color: card2, + onSelected: (k) { + if (k == 'doctor') { + Navigator.push(context, MaterialPageRoute(builder: (_) => DoctorPage(sync: widget.sync, settings: const CycleSettings()))); + } + }, + itemBuilder: (_) => const [PopupMenuItem(value: 'doctor', child: Text('For your doctor'))], + ); + + static const healthTabs = ['Overview', 'Cycle', 'Body', 'Sleep', 'Heart', 'Activity']; + + Widget _syncIcon() => ListenableBuilder( + listenable: Listenable.merge([widget.sync, widget.sync.updater]), + builder: (context, _) => Badge( + isLabelVisible: const {UpdateState.available, UpdateState.ready}.contains(widget.sync.updater.state), + smallSize: 8, + backgroundColor: accent, + offset: const Offset(-6, 6), + child: IconButton( // the dot: an app update (Sync page ▸ App) + tooltip: widget.sync.error ?? (widget.sync.lastOk == null ? 'Not synced yet' : 'Synced'), + onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => SyncPage(sync: widget.sync, onForget: widget.onForget))), + icon: widget.sync.busy + ? const SizedBox(width: 18, height: 18, child: CircularProgressIndicator(strokeWidth: 2)) + : Icon(widget.sync.error != null ? Icons.cloud_off : Icons.cloud_done, color: widget.sync.error != null ? muted : accent), + ), + ), + ); + + static const sections = [ + (Icons.favorite_border, Icons.favorite, 'Health'), + (Icons.restaurant_outlined, Icons.restaurant, 'Food'), + (Icons.work_outline, Icons.work, 'Work'), + (Icons.sticky_note_2_outlined, Icons.sticky_note_2, 'Notes'), + (Icons.cloud_outlined, Icons.cloud, 'Weather'), + ]; + + @override + Widget build(BuildContext context) { + // landscape: the sections as a rail on the left, Health's tabs inside the top bar — the height is for the page + final wide = MediaQuery.of(context).orientation == Orientation.landscape; + final tabs = TabBar(isScrollable: true, tabAlignment: TabAlignment.start, dividerColor: Colors.transparent, + tabs: [for (final t in healthTabs) Tab(text: t)]); + final body = switch (section) { + 0 => DefaultTabController( + length: healthTabs.length, + child: Scaffold( + appBar: wide + ? AppBar(titleSpacing: 0, title: tabs, actions: [_syncIcon(), _healthMenu()]) + : AppBar(title: const Text('Health'), actions: [_syncIcon(), _healthMenu()], bottom: tabs), + body: TabBarView(children: [ + OverviewPage(sync: widget.sync, onFood: () => setState(() => section = 1)), + CyclePage(sync: widget.sync), + BodyPage(sync: widget.sync, range: range), + SleepPage(sync: widget.sync, range: range), + HeartPage(sync: widget.sync, range: range), + ActivityPage(sync: widget.sync, range: range), + ]), + ), + ), + 1 => Scaffold(appBar: AppBar(title: const Text('Food'), actions: [_syncIcon(), _foodMenu()]), body: FoodPage(sync: widget.sync)), + 2 => WorkPage(sync: widget.sync, actions: [_syncIcon(), _workMenu()]), // its own bar: in landscape the week's ‹ CW › is in it + 3 => NotesPage(sync: widget.sync, actions: [_syncIcon()]), // its own bar: the title picks folder / tag + _ => WeatherPage(sync: widget.sync, actions: [_syncIcon()]), // its own bar: the place is the title's dropdown + }; + void go(int i) => setState(() => section = i); + if (wide) { + return Scaffold( + body: SafeArea( + right: false, + child: Row(children: [ + NavigationRail( + backgroundColor: card, + selectedIndex: section, + onDestinationSelected: go, + labelType: NavigationRailLabelType.none, // icons only (the name shows on long-press) + indicatorColor: card2, + destinations: [for (final (o, s, l) in sections) NavigationRailDestination(icon: Icon(o), selectedIcon: Icon(s), label: Text(l))], + ), + Expanded(child: body), + ]), + ), + ); + } + return Scaffold( + body: body, + bottomNavigationBar: NavigationBar( + height: 56, // icons only (the name shows on long-press) + labelBehavior: NavigationDestinationLabelBehavior.alwaysHide, + selectedIndex: section, + onDestinationSelected: go, + destinations: [for (final (o, s, l) in sections) NavigationDestination(icon: Icon(o), selectedIcon: Icon(s), label: l)], + ), + ); + } +} + +/// Sync state: the server, last sync, what's here per table, Sync now, disconnect. +class SyncPage extends StatelessWidget { + const SyncPage({super.key, required this.sync, required this.onForget}); + final SyncService sync; + final Future Function() onForget; + + /// This app: its version and a newer build on the sync server (updater.dart). + Widget _app(BuildContext context) => ListenableBuilder( + listenable: sync.updater, + builder: (context, _) { + final u = sync.updater; + final mb = (u.size / 1e6).round(); + final (text, Widget? action) = switch (u.state) { + UpdateState.unknown => ('Looking for updates after the next sync', null), + UpdateState.current => ('Up to date', null), + UpdateState.available => ( + 'Update ${u.label} available · $mb MB${u.metered ? ' (mobile data)' : ''}', + FilledButton(onPressed: u.download, child: const Text('Download')), + ), + UpdateState.downloading => ('Downloading ${u.label} · ${(u.progress * 100).round()} %', null), + UpdateState.ready => ( + 'Update ${u.label} downloaded', + FilledButton( + onPressed: () async { + final m = await u.install(); + if (m != null && context.mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(m))); + }, + child: const Text('Install'), + ), + ), + UpdateState.failed => ('The download failed', OutlinedButton(onPressed: u.download, child: const Text('Try again'))), + }; + return Card(child: Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 10, 10), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + const Expanded(child: Text('App', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))), + if (u.name.isNotEmpty) Text('${u.name} (${u.code})', style: const TextStyle(color: muted)), + ]), + const SizedBox(height: 4), + Row(children: [ + Expanded(child: Text(text)), + ?action, + ]), + if (u.state == UpdateState.downloading) Padding( + padding: const EdgeInsets.only(top: 6), + child: LinearProgressIndicator(value: u.progress), + ), + if ((u.latest?['notes'] as String?)?.isNotEmpty == true && u.state != UpdateState.current) + Text(u.latest!['notes'] as String, style: const TextStyle(color: muted)), + if (u.error != null && u.state != UpdateState.current) Text(u.error!, style: const TextStyle(color: muted, fontSize: 12)), + ]), + )); + }, + ); + + /// The band: Gadgetbridge's export file on this phone, relayed to the dashboard at every sync. + Widget _band(BuildContext context) { + final r = GbRelay(sync.store); + return Card(child: Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 8, 10), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + const Expanded(child: Text('Band (Gadgetbridge)', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))), + Tooltip( + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 10), + message: 'In Gadgetbridge: Settings ▸ Automations ▸ Auto export — a database export, e.g. every hour. ' + 'Choose that file here once; every sync then sends the band\'s new data to the dashboard.', + child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)), + ), + ]), + Text(r.uri == null ? 'No export chosen — the band\'s data reaches the dashboard only through Syncthing.' + : Uri.decodeComponent(r.uri!.split('/').last).split(':').last, style: const TextStyle(color: muted)), + if (r.lastResult != null) + Text('${TimeOfDay.fromDateTime(DateTime.fromMillisecondsSinceEpoch(r.lastRun)).format(context)} · ${r.lastResult}'), + Row(children: [ + TextButton.icon( + icon: const Icon(Icons.folder_open), + label: Text(r.uri == null ? 'Choose the export' : 'Choose again'), + onPressed: () async { + if (await r.pick()) sync.syncNow(); + }, + ), + if (r.uri != null) + TextButton(onPressed: () { + r.forget(); + sync.changed(); + }, child: const Text('Stop', style: TextStyle(color: muted))), + ]), + ]), + )); + } + + /// The dashboard on the home network: after the band's rows go out it's asked to work on them at once. + Widget _pi(BuildContext context) { + final url = piUrl(sync.store); + return ListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Dashboard on the home network'), + subtitle: Text(url.isEmpty ? 'Not set — the band\'s data reaches the app in the usual rhythm' : url, + style: const TextStyle(color: muted)), + trailing: const Icon(Icons.edit), + onTap: () async { + final c = TextEditingController(text: url); + final v = await showDialog( + context: context, + builder: (d) => AlertDialog( + title: const Text('Dashboard address'), + content: TextField( + controller: c, + keyboardType: TextInputType.url, + decoration: const InputDecoration(hintText: 'http://192.168.1.50:8080')), + actions: [ + TextButton(onPressed: () => Navigator.pop(d), child: const Text('Cancel')), + TextButton(onPressed: () => Navigator.pop(d, c.text), child: const Text('Save')), + ], + ), + ); + if (v != null) sync.setPiUrl(v); + }, + ); + } + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('Sync'), actions: [ + IconButton(onPressed: () { + sync.syncNow(); + sync.updater.check(force: true); + }, icon: const Icon(Icons.sync), tooltip: 'Sync now'), + ]), + body: ListenableBuilder( + listenable: sync, + builder: (context, _) { + final s = sync.settings; + return ListView(padding: const EdgeInsets.all(16), children: [ + Text('${s.account} · ${s.name} · ${s.server}', style: const TextStyle(color: muted)), + const SizedBox(height: 6), + if (sync.busy) const LinearProgressIndicator(), + Text(sync.lastOk == null ? 'Not synced yet' : 'Last sync ${TimeOfDay.fromDateTime(sync.lastOk!).format(context)}' + '${sync.last == null ? '' : ' · ${sync.last}'}'), + if (sync.error != null) Text(sync.error!, style: const TextStyle(color: bad)), + Text(sync.store.meta('bg_ok') == 0 ? 'In the background: about every hour (none yet)' + : 'In the background: about every hour · last ${TimeOfDay.fromDateTime(DateTime.fromMillisecondsSinceEpoch(sync.store.meta('bg_ok'))).format(context)}', + style: const TextStyle(color: muted)), + const SizedBox(height: 12), + _band(context), + const SizedBox(height: 12), + _app(context), + const SizedBox(height: 12), + _pi(context), + const SizedBox(height: 12), + for (final e in sync.store.counts().entries) + ListTile(dense: true, title: Text(e.key), trailing: Text('${e.value}')), + const SizedBox(height: 24), + OutlinedButton( + onPressed: () => showDialog( + context: context, + builder: (d) => AlertDialog( + title: const Text('Disconnect this phone?'), + content: const Text('The data on this phone is deleted; the dashboard keeps everything. ' + 'Connecting again needs the device token and the passphrase.'), + actions: [ + TextButton(onPressed: () => Navigator.pop(d), child: const Text('Cancel')), + TextButton(onPressed: () async { + await SyncSettings.forget(); + if (d.mounted) Navigator.of(d).popUntil((r) => r.isFirst); + await onForget(); + }, child: const Text('Disconnect', style: TextStyle(color: bad))), + ], + ), + ), + child: const Text('Disconnect'), + ), + ]); + }, + ), + ); +} diff --git a/app/lib/app/sync_service.dart b/app/lib/app/sync_service.dart new file mode 100644 index 0000000..f7e60f5 --- /dev/null +++ b/app/lib/app/sync_service.dart @@ -0,0 +1,89 @@ +// One place that owns the connection: syncs on start, when the app comes back to the screen, +// every 5 minutes while it's open, and a few seconds after a local change (pages call changed()). +// Each sync first relays the band's new rows from Gadgetbridge's export (gb_relay.dart); when some went +// out, the Pi is told to sync now (kick.dart) and the app pulls its results right after. +// Pages listen to it and rebuild when data arrived or a sync finished. +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import '../sync/client.dart'; +import '../sync/crypto.dart'; +import '../sync/gb_relay.dart'; +import '../sync/kick.dart'; +import 'updater.dart'; +import '../weather/stations.dart' show stationDays; +import '../sync/store.dart'; + +class SyncService extends ChangeNotifier with WidgetsBindingObserver { + SyncService(this.settings, this.store) { + WidgetsBinding.instance.addObserver(this); + _timer = Timer.periodic(const Duration(minutes: 5), (_) => syncNow()); + syncNow(); + } + + final SyncSettings settings; + final SyncStore store; + late final updater = Updater(settings); // a newer app build on the server (updater.dart), looked for after syncs + SyncCrypto? _crypto; + Timer? _timer, _soon; + bool busy = false; + DateTime? lastOk; + String? error; + SyncResult? last; + + /// The dashboard's address on the home network for "sync now" (kick.dart); empty = none. + void setPiUrl(String v) { + store.setMetaText('pi_url', v.trim()); + notifyListeners(); + } + + /// A local change was saved: refresh the pages now, send it in a few seconds (edits in a row → one batch). + void changed() { + notifyListeners(); + _soon?.cancel(); + _soon = Timer(const Duration(seconds: 3), syncNow); + } + + Future syncNow() async { + if (busy) return; + busy = true; + notifyListeners(); + try { + _crypto ??= await SyncCrypto.create(); + var band = 0; + try { + band = await GbRelay(store).run() ?? 0; // the band's new rows go out with this sync + } catch (e) { + debugPrint('gb relay: $e'); + } + last = await runSync(settings, store, _crypto!); + if (band > 0 && last!.pushed > 0 && await kickPi(settings, store, _crypto!)) { + last = await runSync(settings, store, _crypto!); // the Pi's summaries of them, already there + } + store.dropOld('stations.hourly', 't', DateTime.now().millisecondsSinceEpoch ~/ 1000 - stationDays * 86400); + lastOk = DateTime.now(); + error = null; + unawaited(updater.check()); + } catch (e) { + error = '$e'; // offline is normal: the data stays here, sent next time + } finally { + busy = false; + notifyListeners(); + } + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) syncNow(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + _timer?.cancel(); + _soon?.cancel(); + updater.dispose(); + super.dispose(); + } +} diff --git a/app/lib/app/theme.dart b/app/lib/app/theme.dart new file mode 100644 index 0000000..2aa0136 --- /dev/null +++ b/app/lib/app/theme.dart @@ -0,0 +1,34 @@ +// The dashboard's look (config.THEME / dash.css): one dark background, amber for highlights. +import 'package:flutter/material.dart'; + +const bg = Color(0xFF0D1017), card = Color(0xFF161A23), card2 = Color(0xFF262D3B); +const accent = Color(0xFFFFB33A), muted = Color(0xFF8B929E), bad = Color(0xFFFF9A9A), good = Color(0xFF7FD6A3); + +ThemeData appTheme() => ThemeData( + brightness: Brightness.dark, + scaffoldBackgroundColor: bg, + colorScheme: const ColorScheme.dark(primary: accent, secondary: accent, surface: card), + appBarTheme: const AppBarTheme(backgroundColor: bg, foregroundColor: accent, surfaceTintColor: Colors.transparent), + cardTheme: const CardThemeData(color: card, margin: EdgeInsets.zero, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(12)))), + // the selected section's icon in amber (Material's default is dark on the indicator) + navigationBarTheme: NavigationBarThemeData( + backgroundColor: card, + indicatorColor: card2, + iconTheme: WidgetStateProperty.resolveWith( + (st) => IconThemeData(color: st.contains(WidgetState.selected) ? accent : Colors.white)), + labelTextStyle: WidgetStateProperty.resolveWith((st) => TextStyle( + fontSize: 12.5, fontWeight: FontWeight.w600, color: st.contains(WidgetState.selected) ? accent : Colors.white)), + ), + snackBarTheme: const SnackBarThemeData(backgroundColor: card2, contentTextStyle: TextStyle(color: Colors.white), + actionTextColor: accent, behavior: SnackBarBehavior.floating), + navigationRailTheme: const NavigationRailThemeData( + backgroundColor: card, + indicatorColor: card2, + selectedIconTheme: IconThemeData(color: accent), + unselectedIconTheme: IconThemeData(color: Colors.white), + selectedLabelTextStyle: TextStyle(color: accent, fontWeight: FontWeight.w600), + unselectedLabelTextStyle: TextStyle(color: Colors.white), + ), + chipTheme: const ChipThemeData(backgroundColor: card2, selectedColor: Color(0xFF4A3B1E)), + ); diff --git a/app/lib/app/updater.dart b/app/lib/app/updater.dart new file mode 100644 index 0000000..b36906f --- /dev/null +++ b/app/lib/app/updater.dart @@ -0,0 +1,138 @@ +// The app updates itself from the sync server (dash-sync-server: GET /v1/app, /v1/app/apk — uploaded by +// tool/publish.sh): after a sync (at most every 3 hours, or when asked) it looks for a newer build; on +// Wi-Fi it downloads it by itself, on mobile data only when asked (~70 MB); then Install hands it to +// Android's installer (MainActivity "dash/update": checks the SHA-256 first; Android asks, and refuses an +// update not signed with this app's key). Works anywhere the sync works — not only at home. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:http/http.dart' as http; +import 'package:path_provider/path_provider.dart'; + +import '../sync/client.dart'; + +enum UpdateState { unknown, current, available, downloading, ready, failed } + +class Updater extends ChangeNotifier { + Updater(this.settings); + final SyncSettings settings; + static const _ch = MethodChannel('dash/update'); + static const every = Duration(hours: 3); + + UpdateState state = UpdateState.unknown; + Map? latest; // {version, build, size, sha256, published, notes} + int code = 0; // this install's build number + String name = ''; + bool metered = true; + double progress = 0; + String? error; + DateTime? checked; + bool _busy = false; + + int get size => (latest?['size'] as num?)?.toInt() ?? 0; + String get label => latest == null ? '' : '${latest!['version']} (${latest!['build']})'; + + Future _file() async { + final d = Directory('${(await getTemporaryDirectory()).path}/updates'); // = the FileProvider's cache-path + if (!d.existsSync()) d.createSync(recursive: true); + return File('${d.path}/dash-app.apk'); + } + + Uri _uri(String path) => Uri.parse(settings.server.replaceAll(RegExp(r'/+$'), '') + path); + + /// Look for a newer build (quietly; [force] = now, not every 3 hours). + Future check({bool force = false}) async { + if (_busy || (!force && checked != null && DateTime.now().difference(checked!) < every)) return; + _busy = true; + try { + final me = await _ch.invokeMapMethod('info'); + code = (me?['code'] as num?)?.toInt() ?? 0; + name = me?['name'] as String? ?? ''; + metered = me?['metered'] as bool? ?? true; + final r = await http.get(_uri('/v1/app'), headers: {'Authorization': 'Bearer ${settings.token}'}).timeout(const Duration(seconds: 20)); + checked = DateTime.now(); + if (r.statusCode == 404) { + latest = null; + state = UpdateState.current; + } else if (r.statusCode == 200) { + latest = jsonDecode(r.body) as Map; + final build = (latest!['build'] as num?)?.toInt() ?? 0; + if (build <= code) { + state = UpdateState.current; + final f = await _file(); + if (f.existsSync()) f.deleteSync(); // installed: the download isn't needed any more + } else { + final f = await _file(); + state = f.existsSync() && f.lengthSync() == size ? UpdateState.ready : UpdateState.available; + } + error = null; + } else { + error = 'Server: ${r.statusCode}'; + } + } catch (e) { + error = e is SocketException || e is http.ClientException || e is TimeoutException + ? "Can't reach the sync server — trying again later" // offline is normal + : '$e'; + } finally { + _busy = false; + notifyListeners(); + } + if (state == UpdateState.available && !metered) unawaited(download()); + } + + /// Fetch the APK (to the cache; .part until it's complete). + Future download() async { + if (_busy || latest == null) return; + _busy = true; + state = UpdateState.downloading; + progress = 0; + notifyListeners(); + final f = await _file(), part = File('${f.path}.part'); + final client = http.Client(); + try { + final req = http.Request('GET', _uri('/v1/app/apk'))..headers['Authorization'] = 'Bearer ${settings.token}'; + final res = await client.send(req); + if (res.statusCode != 200) throw HttpException('Server: ${res.statusCode}'); + final sink = part.openWrite(); + var got = 0; + await for (final chunk in res.stream) { + sink.add(chunk); + got += chunk.length; + if (size > 0) progress = got / size; + notifyListeners(); + } + await sink.close(); + if (size > 0 && got != size) throw const HttpException('the download was cut off'); + part.renameSync(f.path); + state = UpdateState.ready; + error = null; + } catch (e) { + if (part.existsSync()) part.deleteSync(); + state = UpdateState.failed; + error = '$e'; + } finally { + client.close(); + _busy = false; + notifyListeners(); + } + } + + /// Hand it to Android's installer → a message for the user, or null when the installer opened. + Future install() async { + final f = await _file(); + final r = await _ch.invokeMethod('install', {'path': f.path, 'sha256': latest?['sha256'] ?? ''}); + switch (r) { + case 'allow': + return 'Allow "Install unknown apps" for dashPi, then tap Install again.'; + case 'bad': + if (f.existsSync()) f.deleteSync(); + state = UpdateState.available; + notifyListeners(); + return "The download didn't check out — download it again."; + } + return null; + } +} diff --git a/app/lib/health/activity_page.dart b/app/lib/health/activity_page.dart new file mode 100644 index 0000000..17b1edd --- /dev/null +++ b/app/lib/health/activity_page.dart @@ -0,0 +1,401 @@ +// Health ▸ Activity (as on the web page's Activity tab), from the Pi's summaries: tiles (steps, workouts, +// fitness · form, vitality), steps and energy per day, training (fitness / fatigue / form) and the +// workouts — tap one for its heart rate on the zone bands and time in zones (WorkoutPage). +import 'dart:math'; + +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import '../widgets/bar_chart.dart'; +import '../widgets/line_chart.dart'; +import 'body_page.dart' show dm, dmy; +import 'cycle_model.dart' show iso, parseDay, today; +import 'range.dart'; +import 'summaries.dart'; + +const vitalityGoal = 150; // intensity minutes a week (calc.VITALITY_GOAL, WHO) +const zoneNames = ['Resting', 'Warm-up', 'Fat burn', 'Aerobic', 'Anaerobic', 'Maximum']; +const zoneColors = [Color(0xFF4A5266), Color(0xFF8FA3BF), Color(0xFF5CC8FF), Color(0xFF7FD6A3), Color(0xFFFFB33A), Color(0xFFFF6B7A)]; +const _fitC = Color(0xFF5CC8FF), _fatC = Color(0xFFFF8FC8); + +/// watch.FORM +(String, String) formLabel(double v) => v < -30 + ? ('Overload', 'fatigue far above fitness — rest soon') + : v < -10 + ? ('Building', 'training hard, fitness rising') + : v < 10 + ? ('Neutral', 'steady') + : ('Fresh', 'rested, ready for a hard session'); + +/// watch.hm: minutes → "1h 05m" +String hm(num? minutes) { + if (minutes == null) return '—'; + final m = minutes.round(); + return '${m ~/ 60}h ${(m % 60).toString().padLeft(2, '0')}m'; +} + +String thousands(num v) => v.round().toString().replaceAllMapped(RegExp(r'\B(?=(\d{3})+$)'), (_) => ','); + +class ActivityPage extends StatelessWidget { + const ActivityPage({super.key, required this.sync, required this.range}); + final SyncService sync; + final HealthRange range; + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: Listenable.merge([sync, range]), + builder: (context, _) { + final sm = Summaries(sync.store); + final days = sm.all('day'); + final wks = sm.all('workout'); + if (days.isEmpty && wks.isEmpty) { + return const Center(child: Padding( + padding: EdgeInsets.all(24), + child: Text('Nothing from the band yet — it comes from the dashboard once it has synced.', + textAlign: TextAlign.center, style: TextStyle(color: muted)), + )); + } + final now = today(); + final first = parseDay([...days, ...wks].map((x) => x['_day'] as String).reduce((a, b) => a.compareTo(b) < 0 ? a : b)); + final a = range.from(first, now); + bool inRange(Map x) => !parseDay(x['_day'] as String).isBefore(a); + final rd = days.where(inRange).toList(), rw = wks.where(inRange).toList(); + DateTime at(Map x) => parseDay(x['_day'] as String); + + final steps = [for (final x in rd) if (x['steps'] != null) (at(x), (x['steps'] as num).toDouble())]; + final energy = [ + for (final x in rd) + if (x['energy'] != null && (x['steps'] != null || rw.any((w) => w['_day'] == x['_day']))) + (at(x), ((x['energy'] as Map)['total'] as num).toDouble()) + ]; + final todays = days.isNotEmpty && days.last['_day'] == iso(now) ? days.last : null; + final train = [for (final x in days) if (x['fitness'] != null) x]; + final cur = train.isEmpty ? null : train.last; + final vit = days.where((x) => now.difference(at(x)).inDays < 7).fold(0, (s, x) => s + ((x['vitality'] as num?) ?? 0)); + double avg(List<(DateTime, double)> xs) => xs.isEmpty ? 0 : xs.map((p) => p.$2).reduce((p, q) => p + q) / xs.length; + final mins = rw.fold(0, (s, w) => s + (w['minutes'] as num)), kcal = rw.fold(0, (s, w) => s + ((w['kcal'] as num?) ?? 0)); + final wide = MediaQuery.of(context).size.width >= 700; + + return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [ + GridView.count( + crossAxisCount: wide ? 4 : 2, + shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), + mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.75, + children: [ + _tile('Steps', steps.isEmpty ? '—' : thousands(avg(steps)), 'a day · today ${todays?['steps'] == null ? '—' : thousands(todays!['steps'] as num)}', + 'The band\'s steps, the average day of the ${steps.length} days with steps in this period'), + _tile('Workouts', '${rw.length}', '${hm(mins)} · ${thousands(kcal)} kcal', + 'Workouts in this period: their time and the energy above resting (from heart rate)'), + _tile('Fitness · form', cur == null ? '—' : '${(cur['fitness'] as num).round()} · ${(cur['form'] as num).round()}', + cur == null ? 'no workouts yet' : formLabel((cur['form'] as num).toDouble()).$1, + 'Fitness = your training load over 42 days, fatigue over 7, form = fitness − fatigue.' + '${cur == null ? '' : ' Now: ${formLabel((cur['form'] as num).toDouble()).$2}.'}'), + _tile('Vitality', '${vit.round()} / $vitalityGoal', 'intensity minutes, 7 days', + 'Moderate minutes + 2 × vigorous ones, from the whole day\'s heart rate — WHO: at least 150 a week', + color: vit >= vitalityGoal ? good : null), + ], + ), + const SizedBox(height: 12), + _card('Steps', 'The band\'s steps per day (per week from 4 months: the average day)', + BarChart(points: steps, from: a, to: now, color: good, range: range, + fmt: (v) => '${thousands(v)} steps')), + const SizedBox(height: 12), + if (energy.isNotEmpty) ...[ + _card('Energy', 'Estimated energy a day: resting (Mifflin–St Jeor) + walking (steps outside workouts) ' + '+ workouts (heart rate). Average ${thousands(avg(energy))} kcal a day.', + BarChart(points: energy, from: a, to: now, color: accent, fmt: (v) => '${thousands(v)} kcal')), + const SizedBox(height: 12), + ], + if (train.isNotEmpty) ...[ + _card('Training', 'Fitness (42-day load), fatigue (7-day load) and form = fitness − fatigue. ' + 'Below −10: building, below −30: overload; above 10: fresh.', + Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Wrap(spacing: 14, children: [ + for (final (n, col) in [('Fitness', _fitC), ('Fatigue', _fatC), ('Form', accent)]) + Row(mainAxisSize: MainAxisSize.min, children: [ + Container(width: 10, height: 10, decoration: BoxDecoration(color: col, shape: BoxShape.circle)), + const SizedBox(width: 5), Text(n, style: const TextStyle(color: muted, fontSize: 12.5)), + ]), + ]), + const SizedBox(height: 6), + LineChart(from: a, to: now, decimals: 0, series: [ + Series('Fitness', [for (final x in train) (at(x), (x['fitness'] as num).toDouble())], _fitC), + Series('Fatigue', [for (final x in train) (at(x), (x['fatigue'] as num).toDouble())], _fatC), + Series('Form', [for (final x in train) (at(x), (x['form'] as num).toDouble())], accent), + ]), + ])), + const SizedBox(height: 12), + ], + _workouts(context, rw), + ]); + }, + ); + + Widget _tile(String label, String value, String sub, String tip, {Color? color}) => Tooltip( + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 6), + message: tip, + child: Card(child: Padding( + padding: const EdgeInsets.all(12), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ + Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)), + FittedBox(fit: BoxFit.scaleDown, child: Text(value, style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: color))), + Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 12)), + ]), + )), + ); + + Widget _card(String title, String tip, Widget child) => Card(child: Padding( + padding: const EdgeInsets.fromLTRB(14, 8, 10, 10), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))), + _info(tip), + ]), + child, + ]), + )); + + Widget _workouts(BuildContext context, List> rw) { + final rows = rw.reversed.take(60).toList(); + return Card(child: Padding( + padding: const EdgeInsets.fromLTRB(14, 8, 10, 6), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + const Expanded(child: Text('Workouts', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))), + _info('Calories = above resting, from heart rate. Effect = this workout\'s load vs your usual one (6 weeks before). ' + 'The strip = time in each heart-rate zone.'), + ]), + if (rows.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 12), child: Text('None in this period', style: TextStyle(color: muted))), + for (final w in rows) + InkWell( + onTap: () => Navigator.push(context, MaterialPageRoute(builder: (_) => WorkoutPage(w: w))), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 8), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + Expanded(child: Text(w['name'] as String, style: const TextStyle(fontWeight: FontWeight.bold))), + Text('${(w['kcal'] as num?)?.round() ?? '—'} kcal', style: const TextStyle(color: accent)), + ]), + Text([dmy(parseDay(w['_day'] as String)), hm(w['minutes'] as num), if (w['avg_hr'] != null) '${(w['avg_hr'] as num).round()} bpm', if (w['effect'] != null) w['effect']].join(' · '), + style: const TextStyle(color: muted, fontSize: 12.5)), + const SizedBox(height: 5), + ZoneStrip(pct: ((w['zone_pct'] as List?) ?? const []).cast()), + ]), + ), + ), + if (rw.length > rows.length) + Padding(padding: const EdgeInsets.only(bottom: 6), child: Text('… and ${rw.length - rows.length} more', style: const TextStyle(color: muted))), + ]), + )); + } +} + +Widget _info(String tip) => Tooltip( + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 8), + message: tip, + child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)), + ); + +class ZoneStrip extends StatelessWidget { + const ZoneStrip({super.key, required this.pct, this.height = 6}); + final List pct; + final double height; + @override + Widget build(BuildContext context) => ClipRRect( + borderRadius: BorderRadius.circular(3), + child: SizedBox(height: height, child: Row(children: [ + for (var i = 0; i < pct.length && i < zoneColors.length; i++) + if (pct[i] > 0) Expanded(flex: max(1, pct[i].round()), child: Container(color: zoneColors[i])), + if (pct.every((p) => p <= 0)) Expanded(child: Container(color: card2)), + ])), + ); +} + +/// One workout (the web's workout page): stats, heart rate on the zone bands, time in zones. +class WorkoutPage extends StatelessWidget { + const WorkoutPage({super.key, required this.w}); + final Map w; + + @override + Widget build(BuildContext context) { + final start = DateTime.parse(w['start'] as String); + final zones = ((w['zones'] as List?) ?? const []).cast(), pct = ((w['zone_pct'] as List?) ?? const []).cast(); + final bounds = ((w['bounds'] as List?) ?? const []).cast(); + final hr = [for (final p in (w['hr'] as List? ?? const [])) ((p as List)[0] as num, p[1] as num)]; + String t(DateTime d) => d.toIso8601String().substring(11, 16); + final end = DateTime.parse(w['end'] as String); + final stats = [ + ('Time', hm(w['minutes'] as num)), + ('Calories', '${(w['kcal'] as num?)?.round() ?? '—'} kcal'), + ('Average', w['avg_hr'] == null ? '—' : '${(w['avg_hr'] as num).round()} bpm'), + ('Highest', w['max_hr'] == null ? '—' : '${w['max_hr']} bpm'), + if (w['distance'] != null) ('Distance', '${((w['distance'] as num) / 1000).toStringAsFixed(2)} km'), + if (w['steps'] != null && (w['steps'] as num) > 0) ('Steps', thousands(w['steps'] as num)), + if (w['load'] != null) ('Load', '${(w['load'] as num).round()}'), + if (w['effect'] != null) ('Effect', w['effect'] as String), + ]; + return Scaffold( + appBar: AppBar(title: Text(w['name'] as String)), + body: ListView(padding: const EdgeInsets.all(12), children: [ + Text('${dm(start)} ${start.year} · ${t(start)} – ${t(end)}', style: const TextStyle(color: muted)), + const SizedBox(height: 10), + Card(child: Padding( + padding: const EdgeInsets.all(12), + child: Wrap(spacing: 18, runSpacing: 10, children: [ + for (final (l, v) in stats) + Tooltip( + triggerMode: TooltipTriggerMode.tap, + message: switch (l) { + 'Calories' => 'Above resting, from your heart rate (with resting: ${(w['kcal_total'] as num?)?.round() ?? '—'} kcal)', + 'Load' => 'Training load (TRIMP): minutes × how hard, from heart rate', + 'Effect' => 'This load vs your usual one (the workouts of the 6 weeks before${w['usual'] == null ? '' : ': ${(w['usual'] as num).round()}'})', + _ => l, + }, + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(l.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11)), + Text(v, style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold)), + ]), + ), + ]), + )), + const SizedBox(height: 12), + if (hr.length > 1) + Card(child: Padding( + padding: const EdgeInsets.fromLTRB(8, 12, 12, 8), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + const Padding(padding: EdgeInsets.only(left: 6, bottom: 8), child: Text('Heart rate', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))), + _HrGraph(hr: hr, bounds: bounds, start: start, seconds: end.difference(start).inSeconds.toDouble()), + ]), + )), + const SizedBox(height: 12), + if (zones.isNotEmpty) + Card(child: Padding( + padding: const EdgeInsets.all(12), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + const Text('Time in zones', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + const SizedBox(height: 8), + for (var i = zones.length - 1; i >= 0; i--) + Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row(children: [ + SizedBox(width: 118, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(zoneNames[i]), + Text(_range(i, bounds), style: const TextStyle(color: muted, fontSize: 11.5)), + ])), + Expanded(child: ClipRRect( + borderRadius: BorderRadius.circular(3), + child: LinearProgressIndicator(value: (i < pct.length ? pct[i] : 0) / 100, minHeight: 8, + color: zoneColors[i], backgroundColor: card2), + )), + SizedBox(width: 90, child: Text('${(zones[i] / 60).round()} min · ${i < pct.length ? pct[i] : 0} %', + textAlign: TextAlign.right, style: const TextStyle(fontSize: 12.5))), + ]), + ), + ]), + )), + ]), + ); + } + + static String _range(int i, List b) { + if (b.isEmpty) return ''; + if (i == 0) return 'under ${b[0]}'; + return i < b.length ? '${b[i - 1]}–${b[i] - 1} bpm' : '${b[i - 1]}+ bpm'; + } +} + +class _HrGraph extends StatefulWidget { + const _HrGraph({required this.hr, required this.bounds, required this.start, required this.seconds}); + final List<(num, num)> hr; // (seconds from start, bpm) + final List bounds; + final DateTime start; + final double seconds; + @override + State<_HrGraph> createState() => _HrGraphState(); +} + +class _HrGraphState extends State<_HrGraph> { + int? hit; + + @override + Widget build(BuildContext context) { + final h = hit == null ? null : widget.hr[hit!]; + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + LayoutBuilder(builder: (context, box) { + void pick(Offset o) { + final s = (o.dx - 34) / (box.maxWidth - 34) * widget.seconds; + var best = 0; + for (var i = 1; i < widget.hr.length; i++) { + if ((widget.hr[i].$1 - s).abs() < (widget.hr[best].$1 - s).abs()) best = i; + } + setState(() => hit = best); + } + + return GestureDetector( + onTapDown: (d) => pick(d.localPosition), + onHorizontalDragUpdate: (d) => pick(d.localPosition), + child: CustomPaint(size: Size(box.maxWidth, 200), painter: _HrPainter(widget, hit)), + ); + }), + SizedBox( + height: 20, + child: h == null + ? const Text('Tap the graph for a minute\'s heart rate', textAlign: TextAlign.center, style: TextStyle(color: muted, fontSize: 12.5)) + : Text('${(h.$1 / 60).floor()} min: ${h.$2} bpm', textAlign: TextAlign.center, style: const TextStyle(fontSize: 13)), + ), + ]); + } +} + +class _HrPainter extends CustomPainter { + _HrPainter(this.g, this.hit); + final _HrGraph g; + final int? hit; + + @override + void paint(Canvas c, Size size) { + const ml = 34.0, mb = 16.0, mt = 4.0; + final vs = g.hr.map((p) => p.$2.toDouble()); + final lo = (min(vs.reduce(min), g.bounds.isEmpty ? 999 : g.bounds.first.toDouble()) / 10).floor() * 10.0 - 5; + final hi = (vs.reduce(max) / 10).ceil() * 10.0 + 5; + final h = size.height - mb - mt, w = size.width - ml; + double y(double v) => mt + h - h * (v - lo) / (hi - lo); + double x(num s) => ml + w * s / max(1, g.seconds); + // zone bands (z1…z5), faint + for (var i = 0; i < g.bounds.length; i++) { + final top = i + 1 < g.bounds.length ? g.bounds[i + 1].toDouble() : hi; + final a = y(min(top, hi)), b = y(max(g.bounds[i].toDouble(), lo)); + if (b > a) c.drawRect(Rect.fromLTRB(ml, a, size.width, b), Paint()..color = zoneColors[i + 1].withValues(alpha: .13)); + } + final txt = const TextStyle(color: muted, fontSize: 10.5); + void label(String s, Offset o, {bool right = false}) { + final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout(); + tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0)); + } + + for (var v = (lo / 20).ceil() * 20.0; v <= hi; v += 20) { + label('${v.round()}', Offset(ml - 4, y(v)), right: true); + } + final mins = g.seconds / 60, every = mins <= 30 ? 5 : mins <= 75 ? 15 : mins <= 150 ? 30 : 60; + for (var m = 0; m <= mins; m += every) { + label('$m′', Offset(x(m * 60), size.height - mb + 3)); + } + final path = Path(); + for (var i = 0; i < g.hr.length; i++) { + final p = Offset(x(g.hr[i].$1), y(g.hr[i].$2.toDouble())); + i == 0 ? path.moveTo(p.dx, p.dy) : path.lineTo(p.dx, p.dy); + } + c.drawPath(path, Paint()..color = const Color(0xFFFF6B7A)..strokeWidth = 2..style = PaintingStyle.stroke..strokeJoin = StrokeJoin.round); + if (hit != null) { + final p = Offset(x(g.hr[hit!].$1), y(g.hr[hit!].$2.toDouble())); + c.drawLine(Offset(p.dx, mt), Offset(p.dx, size.height - mb), Paint()..color = muted.withValues(alpha: .5)); + c.drawCircle(p, 4, Paint()..color = Colors.white); + } + } + + @override + bool shouldRepaint(covariant _HrPainter old) => true; +} diff --git a/app/lib/health/body_model.dart b/app/lib/health/body_model.dart new file mode 100644 index 0000000..10128a2 --- /dev/null +++ b/app/lib/health/body_model.dart @@ -0,0 +1,344 @@ +// Body measurements + vitals — a port of the dashboard's plugins/health calc.py (formulas, +// categories), views.py (latest per field, changes, series) and db.py (what a save does). +// Keep them in step with the web pages. +// +// Synced rows: "health.measure" id "measure:" {day, weight, waist, hip, neck, chest, arm, +// thigh, fat_scale, note, updated}; "health.vital" {t "YYYY-MM-DD HH:MM", sys, dia, spo2, pulse, +// note, source} — imported ones have id "vital:", ones typed here a random id. +import 'dart:math'; + +import '../sync/store.dart'; +import 'cycle_model.dart' show iso, parseDay, daysBetween, today; +import 'summaries.dart'; + +const female = 'female'; +const stale = 90; // days a measurement is still used for "now" / carried forward + +/// key: (label, unit, min, max) +const fields = { + 'weight': ('Weight', 'kg', 20.0, 400.0), + 'waist': ('Waist', 'cm', 30.0, 250.0), + 'hip': ('Hips', 'cm', 30.0, 250.0), + 'neck': ('Neck', 'cm', 15.0, 80.0), + 'chest': ('Chest', 'cm', 40.0, 250.0), + 'arm': ('Upper arm', 'cm', 10.0, 80.0), + 'thigh': ('Thigh', 'cm', 20.0, 120.0), + 'fat_scale': ('Body fat from a scale', '%', 2.0, 75.0), +}; +const fatDayFields = {'weight', 'waist', 'hip', 'neck', 'fat_scale'}; + +/// The values set on the dashboard (Settings ▸ Health), from its person summary (profileOf). +class Profile { + const Profile({this.sex = female, this.birth, this.height}); + final String sex; + final DateTime? birth; + final double? height; + int? ageOn(DateTime d) { + final b = birth; + if (b == null) return null; + return d.year - b.year - ((d.month < b.month || (d.month == b.month && d.day < b.day)) ? 1 : 0); + } +} + +/// The dashboard's Settings ▸ Health (sex, birth date, height) as its summary brings them; none yet = no age / height. +Profile profileOf(SyncStore store) { + final p = Summaries(store).meta('person') ?? {}; + final b = DateTime.tryParse('${p['birth'] ?? ''}'); + final h = (p['height'] as num?)?.toDouble(); + return Profile(sex: p['sex'] == 'male' ? 'male' : female, + birth: b == null ? null : DateTime.utc(b.year, b.month, b.day), height: h == null || h <= 0 ? null : h); +} + +// ---- formulas (calc.py) --------------------------------------------------------------------- + +double _log10(double x) => log(x) / ln10; + +double? bmi(double? w, double? h) => (w == null || h == null || w == 0 || h == 0) ? null : w / pow(h / 100, 2); + +const bmiClasses = [(18.5, 'underweight'), (25.0, 'normal'), (30.0, 'overweight'), (35.0, 'obese (class I)'), + (40.0, 'obese (class II)'), (999.0, 'obese (class III)')]; +String? bmiClass(double? b) => b == null ? null : bmiClasses.firstWhere((c) => b < c.$1).$2; + +(double, double)? healthyWeight(double? h) => h == null ? null : (18.5 * pow(h / 100, 2), 24.9 * pow(h / 100, 2)); + +double? whtr(double? waist, double? h) => waist != null && h != null ? waist / h : null; +String? whtrClass(double? r) => r == null ? null : r < 0.4 ? 'low' : r < 0.5 ? 'healthy' : r < 0.6 ? 'raised' : 'high'; +double? whr(double? waist, double? hip) => waist != null && hip != null ? waist / hip : null; +String? whrClass(double? r, String sex) => r == null ? null : r >= (sex == female ? 0.85 : 0.90) ? 'raised (WHO)' : 'healthy'; +String? waistClass(double? w, String sex) { + if (w == null) return null; + final (a, b) = sex == female ? (80, 88) : (94, 102); + return w < a ? 'healthy' : w < b ? 'raised' : 'high'; +} + +double? navy(Map m, double? h, String sex) { + final w = m['waist'], n = m['neck'], hip = m['hip']; + if (w == null || n == null || h == null) return null; + if (sex == female) { + if (hip == null || w + hip - n <= 0) return null; + return 495 / (1.29579 - 0.35004 * _log10(w + hip - n) + 0.22100 * _log10(h)) - 450; + } + if (w - n <= 0) return null; + return 495 / (1.0324 - 0.19077 * _log10(w - n) + 0.15456 * _log10(h)) - 450; +} + +double? rfm(Map m, double? h, String sex) { + final w = m['waist']; + return w == null || h == null ? null : (sex == female ? 76 : 64) - 20 * h / w; +} + +double? ymca(Map m, double? h, String sex) { + final w = m['waist'], kg = m['weight']; + if (w == null || kg == null) return null; + final lb = kg * 2.20462, inch = w / 2.54; + return (4.15 * inch - 0.082 * lb - (sex == female ? 76.76 : 98.42)) / lb * 100; +} + +class FatResult { + FatResult(this.key, this.name, this.value, this.missing, this.note); + final String key, name, note; + final double? value; + final List missing; +} + +/// (key, name, needs, note) — BMI-based formulas and skinfolds left out on purpose (calc.FAT). +const fatFormulas = [ + ('navy', 'U.S. Navy', ['waist', 'neck', 'hip?', 'height'], 'tape: waist, neck, hips · about ±3–4 % in studies'), + ('rfm', 'Relative fat mass', ['waist', 'height'], 'waist and height · checked against DEXA scans'), + ('ymca', 'YMCA', ['waist', 'weight'], 'waist and weight · simple, less tested in women'), + ('scale', 'Your scale', ['fat_scale'], 'bioimpedance · shifts with water, time of day'), +]; + +List fatAll(Map m, double? h, String sex) => [ + for (final (key, name, needs, note) in fatFormulas) + () { + var v = switch (key) { + 'navy' => navy(m, h, sex), + 'rfm' => rfm(m, h, sex), + 'ymca' => ymca(m, h, sex), + _ => m['fat_scale'], + }; + if (v != null && (v < 2 || v > 75)) v = null; // implausible: bad inputs + final missing = []; + if (v == null) { + for (final n in needs) { + if (n == 'hip?') { + if (sex == female && m['hip'] == null) missing.add('hip'); + } else if (n == 'height') { + if (h == null) missing.add('height'); + } else if (m[n] == null) { + missing.add(n); + } + } + } + return FatResult(key, name, v, missing, note); + }() + ]; + +/// Healthy body-fat ranges (Gallagher et al. 2000): (age from, to, healthy from, high from, very high from). +const fatRanges = { + female: [(20, 39, 21.0, 33.0, 39.0), (40, 59, 23.0, 34.0, 40.0), (60, 79, 24.0, 36.0, 42.0)], + 'male': [(20, 39, 8.0, 20.0, 25.0), (40, 59, 11.0, 22.0, 28.0), (60, 79, 13.0, 25.0, 30.0)], +}; +const fatNames = ['low', 'healthy', 'high', 'very high']; + +(int, int, double, double, double)? fatBand(String sex, int? age) { + if (age == null || age < 20) return null; + final rows = fatRanges[sex == female ? female : 'male']!; + return rows.firstWhere((r) => r.$1 <= age && age <= r.$2, orElse: () => rows.last); +} + +String? fatClass(double? v, String sex, int? age) { + final b = fatBand(sex, age); + if (v == null || b == null) return null; + return fatNames[[b.$3, b.$4, b.$5].where((x) => v >= x).length]; +} + +/// Desirable BMI by age (NRC 1989): (age from, to, lo, hi). +const bmiAge = [(19, 24, 19, 24), (25, 34, 20, 25), (35, 44, 21, 26), (45, 54, 22, 27), (55, 64, 23, 28), (65, 200, 24, 29)]; +(int, int, int, int)? bmiAgeBand(int? age) => + age == null || age < 19 ? null : bmiAge.firstWhere((r) => r.$1 <= age && age <= r.$2); + +double? bmrMifflin(double? w, double? h, String sex, int? age) => + w == null || h == null || age == null ? null : 10 * w + 6.25 * h - 5 * age + (sex == female ? -161 : 5); +double? bmrKatch(double? w, double? fat) => w == null || fat == null ? null : 370 + 21.6 * w * (1 - fat / 100); + +double? median(List xs) { + if (xs.isEmpty) return null; + final s = [...xs]..sort(); + final n = s.length; + return n.isOdd ? s[n ~/ 2] : (s[n ~/ 2 - 1] + s[n ~/ 2]) / 2; +} + +// ---- the page's numbers (views.py) ---------------------------------------------------------- + +class Measure { + Measure(this.row) : day = parseDay(row['day'] as String); + final Map row; + final DateTime day; + double? operator [](String k) => (row[k] as num?)?.toDouble(); + String get note => (row['note'] as String?) ?? ''; +} + +class Latest { + Latest(this.v, this.day, this.stale); + final double v; + final DateTime day; + final bool stale; +} + +class BodyView { + BodyView(SyncStore store, this.p, {DateTime? now}) : now = now ?? today() { + rows = [for (final r in store.rows('health.measure')) Measure(r)]..sort((a, b) => a.day.compareTo(b.day)); + for (final r in rows) { + for (final k in fields.keys) { + if (r[k] != null) cur[k] = Latest(r[k]!, r.day, daysBetween(r.day, this.now) > stale); + } + } + final m = {for (final e in cur.entries) if (!e.value.stale) e.key: e.value.v}; + fresh = m; + age = p.ageOn(this.now); + fat = fatAll(m, p.height, p.sex); + final est = [for (final f in fat) if (f.value != null) f.value!]; + fatMid = median(est); + fatRange = est.length > 1 ? (est.reduce(min), est.reduce(max)) : null; + } + + final Profile p; + final DateTime now; + late final List rows; + final cur = {}; + late final Map fresh; + late final int? age; + late final List fat; + late final double? fatMid; + late final (double, double)? fatRange; + + double? get weight => fresh['weight']; + double? get waist => fresh['waist']; + double? get hip => fresh['hip']; + double? get bmiNow => bmi(weight, p.height); + + /// Change of [key] from the value nearest [days] ago (at least 7 days back) to the latest. + (double, DateTime, int)? change(String key, {int days = 30}) { + final pts = [for (final r in rows) if (r[key] != null) (r.day, r[key]!)]; + if (pts.length < 2) return null; + final (lastD, lastV) = pts.last; + final old = pts.where((p) => daysBetween(p.$1, lastD) >= 7).toList(); + if (old.isEmpty) return null; + old.sort((a, b) => (daysBetween(a.$1, lastD) - days).abs().compareTo((daysBetween(b.$1, lastD) - days).abs())); + final (d, v) = old.first; + return (lastV - v, d, daysBetween(d, lastD)); + } + + /// Per measured day: weight, waist, BMI and each fat formula (other inputs carried forward ≤ stale days). + Map> series() { + final out = >{ + 'weight': [], 'waist': [], 'bmi': [], for (final f in fatFormulas) f.$1: []}; + final last = {}; + for (final r in rows) { + for (final k in fields.keys) { + if (r[k] != null) last[k] = (r[k]!, r.day); + } + final m = {for (final e in last.entries) if (daysBetween(e.value.$2, r.day) <= stale) e.key: e.value.$1}; + for (final k in ['weight', 'waist']) { + if (r[k] != null) out[k]!.add((r.day, r[k]!)); + } + if (r['weight'] != null && p.height != null) out['bmi']!.add((r.day, bmi(r['weight'], p.height)!)); + if (fatDayFields.any((k) => r[k] != null)) { + for (final f in fatAll(m, p.height, p.sex)) { + if (f.value != null) out[f.key]!.add((r.day, f.value!)); + } + } + } + return out; + } +} + +/// db.save: replace the day's row; `was` (another day) moves it; nothing in it → deleted. +String? saveMeasure(SyncStore store, DateTime d, Map vals, String note, {DateTime? was}) { + if (d.isAfter(today())) return "That day hasn't happened yet."; + for (final e in vals.entries) { + final f = fields[e.key]!; + if (e.value != null && (e.value! < f.$3 || e.value! > f.$4)) return '${f.$1}: between ${f.$3.round()} and ${f.$4.round()} ${f.$2}.'; + } + final u = 'measure:${iso(d)}'; + if (was != null && was != d) { + if (store.row('health.measure', u) != null) return 'That day already has measurements — edit it instead.'; + store.delete('health.measure', 'measure:${iso(was)}'); + } + if (vals.values.every((v) => v == null) && note.trim().isEmpty) { + if (store.row('health.measure', u) != null) store.delete('health.measure', u); + return null; + } + final old = store.row('health.measure', u) ?? {}; + final now = DateTime.now(); + store.put('health.measure', u, { + ...old, // columns this app doesn't show (old skinfolds) stay + 'day': iso(d), 'note': note.trim(), 'updated': '${iso(now)} ${now.toIso8601String().substring(11, 19)}', + for (final k in fields.keys) k: vals[k], + }); + return null; +} + +// ---- vitals ------------------------------------------------------------------------------ + +const vitalSources = {'mi_fitness': 'Mi Fitness', 'health_connect': 'Health Connect', 'gadgetbridge': 'Gadgetbridge'}; + +class Vital { + Vital(this.row) : t = DateTime.parse('${(row['t'] as String).replaceFirst(' ', 'T')}:00Z'); + final Map row; + final DateTime t; // local wall time (stored as UTC so nothing shifts) + String get u => row['_u'] as String; + int? get sys => (row['sys'] as num?)?.toInt(); + int? get dia => (row['dia'] as num?)?.toInt(); + double? get spo2 => (row['spo2'] as num?)?.toDouble(); + String get note => (row['note'] as String?) ?? ''; + String? get source => row['source'] as String?; + bool get isBp => sys != null && dia != null; +} + +List vitals(SyncStore store) => + [for (final r in store.rows('health.vital')) Vital(r)]..sort((a, b) => b.t.compareTo(a.t)); // newest first + +/// (name, colour key) — ESC 2024 office categories; the higher of the two numbers decides. +(String, String)? bpClass(int? sys, int? dia) { + if (sys == null || dia == null) return null; + const classes = [('non-elevated', 0, 0, 'ok'), ('elevated', 120, 70, 'mid'), ('hypertension', 140, 90, 'high'), + ('severe hypertension', 180, 110, 'vhigh')]; + var pick = classes.first; + for (final c in classes) { + if (sys >= c.$2 || dia >= c.$3) pick = c; + } + return (pick.$1, pick.$4); +} + +(String, String)? spo2Class(double? p) => p == null ? null : p >= 95 ? ('normal', 'ok') : p > 90 ? ('low', 'mid') : ('very low', 'vhigh'); + +/// db.save_vital: one kind per reading (bp: sys + dia, ox: spo2). Returns an error or null. +String? saveVital(SyncStore store, {String? u, required String kind, required DateTime t, int? sys, int? dia, double? spo2, + String note = ''}) { + if (t.isAfter(DateTime.now().toUtc().add(const Duration(hours: 14)))) return "That time hasn't come yet."; + if (kind == 'bp') { + if (sys == null || dia == null) return 'Blood pressure needs both numbers (e.g. 120 / 80).'; + if (sys < 60 || sys > 260) return 'Systolic: between 60 and 260 mmHg.'; + if (dia < 30 || dia > 160) return 'Diastolic: between 30 and 160 mmHg.'; + if (sys <= dia) return 'The upper number (systolic) is the bigger one.'; + } else { + if (spo2 == null) return 'Enter the oxygen %.'; + if (spo2 < 50 || spo2 > 100) return 'Blood oxygen: between 50 and 100 %.'; + } + final old = u == null ? null : store.row('health.vital', u); + final ts = '${iso(t)} ${t.toIso8601String().substring(11, 16)}'; + store.put('health.vital', u ?? SyncStore.randomId(), { + ...?old, + 't': ts, 'sys': kind == 'bp' ? sys : null, 'dia': kind == 'bp' ? dia : null, + 'spo2': kind == 'ox' ? (spo2! * 10).round() / 10 : null, 'pulse': null, 'note': note.trim(), + 'source': old?['source'], + }); + return null; +} + +/// Readings of one kind as chart points (oldest first). +List<(DateTime, double)> vitalSeries(List vs, double? Function(Vital) pick) => + [for (final v in vs.reversed) if (pick(v) != null) (v.t, pick(v)!)]; diff --git a/app/lib/health/body_page.dart b/app/lib/health/body_page.dart new file mode 100644 index 0000000..2eb6ade --- /dev/null +++ b/app/lib/health/body_page.dart @@ -0,0 +1,419 @@ +// Health ▸ Body: tiles (weight + change, BMI, waist, body fat), the chart (weight / waist / BMI / +// body fat over 3 months · 1 year · all), body fat by every formula, ratios + resting energy, the +// measurements (tap = edit, + = add). The numbers are the web page's (body_model.dart). +// Categories: tap a tile (the web page shows them on hover). +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import '../widgets/line_chart.dart'; +import 'body_model.dart'; +import 'cycle_model.dart' show plus, today; +import 'range.dart'; + +const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; +String dm(DateTime d) => '${d.day} ${_mon[d.month - 1]}'; +String dmy(DateTime d) => '${d.day} ${_mon[d.month - 1]} ${d.year}'; +String n1(double? v) => v == null ? '—' : v.toStringAsFixed(1); +/// 115 not 115.0; 124.6 stays. +String trim1(double? v) => v == null ? '—' : n1(v).replaceFirst(RegExp(r'\.0$'), ''); +const _short = {'weight': 'weight', 'waist': 'waist', 'hip': 'hips', 'neck': 'neck', 'chest': 'chest', 'arm': 'arm', + 'thigh': 'thigh', 'fat_scale': 'scale fat'}; + +/// A category word → its colour (healthy green, raised amber, high red, low blue). +Color classColor(String? c) { + if (c == null) return muted; + if (RegExp(r'very high|obese|severe|vhigh|very low').hasMatch(c)) return bad; + if (RegExp(r'^(healthy|normal|non-elevated|ok)').hasMatch(c)) return good; + if (RegExp(r'^(low|underweight)').hasMatch(c)) return const Color(0xFF5CC8FF); + return accent; +} + +class BodyPage extends StatefulWidget { + const BodyPage({super.key, required this.sync, required this.range}); + final SyncService sync; + final HealthRange range; + @override + State createState() => _BodyPageState(); +} + +class _BodyPageState extends State { + String chart = 'weight'; + int shown = 5; + + @override + Widget build(BuildContext context) => Scaffold( + floatingActionButton: FloatingActionButton( + backgroundColor: accent, + foregroundColor: bg, + tooltip: 'Add measurements', + onPressed: () => _edit(BodyView(widget.sync.store, profileOf(widget.sync.store)), null), + child: const Icon(Icons.add), + ), + body: ListenableBuilder( + listenable: Listenable.merge([widget.sync, widget.range]), + builder: (context, _) { + final v = BodyView(widget.sync.store, profileOf(widget.sync.store)); + if (v.rows.isEmpty) { + return const Center(child: Text('No measurements yet — + to add the first.', style: TextStyle(color: muted))); + } + return LayoutBuilder(builder: (context, box) { + final wide = box.maxWidth >= 700; + final left = [_tiles(v, wide), const SizedBox(height: 12), _chart(v)]; + final right = [_fat(v), const SizedBox(height: 12), _ratios(v), const SizedBox(height: 12), _list(v)]; + return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 88), children: [ + if (wide) + Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Expanded(child: Column(children: left)), + const SizedBox(width: 12), + Expanded(child: Column(children: right)), + ]) + else ...[...left, const SizedBox(height: 12), ...right], + ]); + }); + }, + ), + ); + + // ---- tiles + Widget _tiles(BodyView v, bool wide) { + final wc = v.change('weight'); + final b = v.bmiNow; + String from(String k) { + final c = v.cur[k]; + if (c == null) return ''; + return c.day == v.now ? 'today' : c.stale ? 'old: ${dmy(c.day)}' : dm(c.day); + } + final tiles = [ + _Tile('Weight', v.weight == null ? '—' : '${trim1(v.weight)} kg', + wc == null ? from('weight') : '${wc.$1 >= 0 ? '+' : '−'}${wc.$1.abs().toStringAsFixed(1)} kg in ${wc.$3} days', + null, () => _info('Weight', _weightInfo(v))), + _Tile('BMI', b == null ? '—' : n1(b), bmiClass(b) ?? 'needs height + weight', bmiClass(b), () => _info('BMI', _bmiInfo(v))), + _Tile('Waist', v.waist == null ? '—' : '${trim1(v.waist)} cm', waistClass(v.waist, v.p.sex) ?? from('waist'), + waistClass(v.waist, v.p.sex), () => _info('Waist', _waistInfo(v))), + _Tile('Body fat', v.fatMid == null ? '—' : '${n1(v.fatMid)} %', + fatClass(v.fatMid, v.p.sex, v.age) ?? 'needs measurements', fatClass(v.fatMid, v.p.sex, v.age), + () => _info('Body fat', _fatInfo(v))), + ]; + return GridView.count( + crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), + mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.9, + children: tiles, + ); + } + + Widget _weightInfo(BodyView v) { + final hw = healthyWeight(v.p.height); + return Text(hw == null ? 'Set your height on the dashboard.' : + 'Healthy weight for ${v.p.height} cm (BMI 18.5–24.9): ${hw.$1.toStringAsFixed(1)}–${hw.$2.toStringAsFixed(1)} kg.'); + } + + Widget _bmiInfo(BodyView v) { + final band = bmiAgeBand(v.age); + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + const Text('WHO classes (all adults): under 18.5 underweight · 18.5–25 normal · 25–30 overweight · 30+ obese (I 30–35, II 35–40, III 40+).'), + const SizedBox(height: 10), + const Text('Desirable BMI by age (NRC 1989):', style: TextStyle(color: muted)), + for (final r in bmiAge) + Text('${r.$1}–${r.$2 > 100 ? '+' : r.$2}: ${r.$3}–${r.$4}', + style: TextStyle(color: band == r ? accent : null, fontWeight: band == r ? FontWeight.bold : null)), + const SizedBox(height: 8), + const Text('BMI reads muscle as fat; the waist and body fat say more.', style: TextStyle(color: muted)), + ]); + } + + Widget _waistInfo(BodyView v) => Text(v.p.sex == female + ? 'WHO (European women): under 80 cm healthy · 80–88 raised · 88+ high.' + : 'WHO (European men): under 94 cm healthy · 94–102 raised · 102+ high.'); + + Widget _fatInfo(BodyView v) { + final rows = fatRanges[v.p.sex == female ? female : 'male']!; + final band = fatBand(v.p.sex, v.age); + return Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text('Healthy body fat by age (${v.p.sex}, Gallagher et al. 2000):', style: const TextStyle(color: muted)), + for (final r in rows) + Text('${r.$1}–${r.$2}: healthy ${r.$3.round()}–${r.$4.round()} % · high from ${r.$4.round()} · very high from ${r.$5.round()}', + style: TextStyle(color: band == r ? accent : null, fontWeight: band == r ? FontWeight.bold : null)), + const SizedBox(height: 8), + const Text('The middle (median) of every formula that has its measurements; they disagree by a few points.', + style: TextStyle(color: muted)), + ]); + } + + void _info(String title, Widget body) => showModalBottomSheet( + context: context, + backgroundColor: card, + builder: (_) => Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 28), + child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(title, style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)), + const SizedBox(height: 10), + body, + ]), + ), + ); + + // ---- chart + Widget _chart(BodyView v) { + final sr = v.series(); + final from = widget.range.from(v.rows.first.day, v.now); + final hw = healthyWeight(v.p.height); + const fatColors = [Color(0xFFFFB33A), Color(0xFF5CC8FF), Color(0xFFC792EA), Color(0xFF7FD6A3)]; + final (List s, String unit, (double, double)? band) = switch (chart) { + 'waist' => ([Series('Waist', sr['waist']!, accent)], 'cm', null), + 'bmi' => ([Series('BMI', sr['bmi']!, accent)], '', (18.5, 25.0)), + 'fat' => ([for (var i = 0; i < fatFormulas.length; i++) Series(fatFormulas[i].$2, sr[fatFormulas[i].$1]!, fatColors[i])], '%', null), + _ => ([Series('Weight', sr['weight']!, accent)], 'kg', hw), + }; + return Card( + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 6), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row(children: [ + for (final (k, l) in [('weight', 'Weight'), ('waist', 'Waist'), ('bmi', 'BMI'), ('fat', 'Body fat')]) + Padding(padding: const EdgeInsets.only(right: 6), + child: ChoiceChip(label: Text(l), selected: chart == k, onSelected: (_) => setState(() => chart = k))), + ]), + ), + const SizedBox(height: 8), + LineChart(series: s, from: from, to: plus(v.now, 1), unit: unit, band: band, range: widget.range), + if (chart == 'fat') + Wrap(spacing: 10, children: [ + for (var i = 0; i < fatFormulas.length; i++) + Text('● ${fatFormulas[i].$2}', style: TextStyle(color: fatColors[i], fontSize: 12)), + ]), + ]), + ), + ); + } + + // ---- body fat by formula + Widget _fat(BodyView v) => _Card('Body fat', [ + for (final f in v.fat) + Tooltip( + triggerMode: TooltipTriggerMode.tap, + message: f.note, + child: _Row(f.name, f.value != null ? '${n1(f.value)} %' : 'needs ${f.missing.map(_need).join(', ')}', + f.value == null ? muted : classColor(fatClass(f.value, v.p.sex, v.age))), + ), + const Divider(color: card2), + _Row('Middle of ${v.fat.where((f) => f.value != null).length}', v.fatMid == null ? '—' : + '${n1(v.fatMid)} %${v.fatRange == null ? '' : ' (${n1(v.fatRange!.$1)}–${n1(v.fatRange!.$2)})'}', + classColor(fatClass(v.fatMid, v.p.sex, v.age))), + if (v.weight != null && v.fatMid != null) + _Row('Fat · lean', '${(v.weight! * v.fatMid! / 100).toStringAsFixed(1)} kg · ${(v.weight! * (1 - v.fatMid! / 100)).toStringAsFixed(1)} kg', null), + ]); + + static String _need(String k) => k == 'height' ? 'height' : k == 'fat_scale' ? 'a scale reading' : fields[k]!.$1.toLowerCase(); + + // ---- ratios + energy + Widget _ratios(BodyView v) { + final r1 = whtr(v.waist, v.p.height), r2 = whr(v.waist, v.hip); + final m = bmrMifflin(v.weight, v.p.height, v.p.sex, v.age), k = bmrKatch(v.weight, v.fatMid); + return _Card('Ratios & energy', [ + _Row('Waist ÷ height', r1 == null ? '—' : '${r1.toStringAsFixed(2)} · ${whtrClass(r1)}', classColor(whtrClass(r1))), + _Row('Waist ÷ hips', r2 == null ? '—' : '${r2.toStringAsFixed(2)} · ${whrClass(r2, v.p.sex)}', classColor(whrClass(r2, v.p.sex))), + _Row('Resting energy', m == null ? '—' : '${m.round()} kcal/day${k == null ? '' : ' · ${k.round()} from lean mass'}', null), + ]); + } + + // ---- the measurements + Widget _list(BodyView v) { + final from = widget.range.from(v.rows.first.day, v.now); // the charts' period + final rows = v.rows.reversed.where((r) => !r.day.isBefore(from)).toList(); + return _Card('Measurements', [ + if (rows.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6), + child: Text('Nothing measured in this period', style: TextStyle(color: muted))), + for (final r in rows.take(shown)) + InkWell( + onTap: () => _edit(v, r), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 7), + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + SizedBox(width: 92, child: Text(r.day.year == v.now.year ? dm(r.day) : dmy(r.day), style: const TextStyle(color: muted))), + Expanded(child: Text([ + for (final k in fields.keys) if (r[k] != null) '${_short[k]} ${trim1(r[k])}', + if (r.note.isNotEmpty) '“${r.note}”', + ].join(' · '))), + ]), + ), + ), + if (rows.length > shown) + TextButton(onPressed: () => setState(() => shown += 5), child: Text('Show more (${rows.length - shown})')), + ]); + } + + Future _edit(BodyView v, Measure? m) => showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => MeasureSheet(v: v, m: m, onSave: (d, vals, note, was) { + final err = saveMeasure(widget.sync.store, d, vals, note, was: was); + if (err == null) widget.sync.changed(); + return err; + }, onDelete: m == null ? null : () { + saveMeasure(widget.sync.store, m.day, {}, ''); + widget.sync.changed(); + }), + ); +} + +class _Tile extends StatelessWidget { + const _Tile(this.label, this.value, this.sub, this.cls, this.onTap); + final String label, value, sub; + final String? cls; + final VoidCallback onTap; + @override + Widget build(BuildContext context) => Card( + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: onTap, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ + Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)), + Text(value, style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold)), + Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: TextStyle(color: cls == null ? muted : classColor(cls), fontSize: 12.5)), + ]), + ), + ), + ); +} + +class _Card extends StatelessWidget { + const _Card(this.title, this.children); + final String title; + final List children; + @override + Widget build(BuildContext context) => Card( + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 12, 14, 10), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + const SizedBox(height: 6), + ...children, + ]), + ), + ); +} + +class _Row extends StatelessWidget { + const _Row(this.k, this.v, this.color); + final String k, v; + final Color? color; + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row(children: [ + Expanded(child: Text(k, style: const TextStyle(color: muted))), + Flexible(child: Text(v, textAlign: TextAlign.right, style: TextStyle(color: color))), + ]), + ); +} + +/// Add / edit a day's measurements: date, every field (placeholders = your last values), note. +class MeasureSheet extends StatefulWidget { + const MeasureSheet({super.key, required this.v, required this.m, required this.onSave, this.onDelete}); + final BodyView v; + final Measure? m; + final String? Function(DateTime d, Map vals, String note, DateTime? was) onSave; + final VoidCallback? onDelete; + @override + State createState() => _MeasureSheetState(); +} + +class _MeasureSheetState extends State { + late DateTime d = widget.m?.day ?? today(); + late final ctl = { + for (final k in fields.keys) k: TextEditingController(text: widget.m?[k] == null ? '' : trim1(widget.m![k])) + }; + late final note = TextEditingController(text: widget.m?.note ?? ''); + String? error; + bool armed = false; + + void _loadDay(DateTime nd) { + // picking a day that already has measurements (when adding) loads them, like the web dialog + final other = widget.v.rows.where((r) => r.day == nd).firstOrNull; + setState(() { + d = nd; + if (widget.m == null && other != null) { + for (final k in fields.keys) { + ctl[k]!.text = other[k] == null ? '' : trim1(other[k]); + } + note.text = other.note; + } + }); + } + + @override + Widget build(BuildContext context) => Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + MediaQuery.of(context).viewInsets.bottom), + child: SingleChildScrollView( + child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + Expanded(child: Text(widget.m == null ? 'Add measurements' : 'Edit measurements', + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent))), + TextButton.icon( + icon: const Icon(Icons.event, size: 18), + label: Text(dmy(d)), + onPressed: () async { + final p = await showDatePicker(context: context, initialDate: d, firstDate: DateTime.utc(2000), lastDate: today()); + if (p != null) _loadDay(DateTime.utc(p.year, p.month, p.day)); + }, + ), + ]), + const SizedBox(height: 4), + GridView.count( + crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), + crossAxisSpacing: 12, childAspectRatio: 3.2, + children: [ + for (final e in fields.entries) + TextField( + controller: ctl[e.key], + keyboardType: const TextInputType.numberWithOptions(decimal: true), + textInputAction: TextInputAction.next, + decoration: InputDecoration( + labelText: e.key == 'fat_scale' ? 'Scale body fat' : e.value.$1, suffixText: e.value.$2, + hintText: widget.v.cur[e.key] == null ? null : n1(widget.v.cur[e.key]!.v), + ), + ), + ]), + TextField(controller: note, maxLength: 2000, decoration: const InputDecoration(labelText: 'Note')), + if (error != null) Padding(padding: const EdgeInsets.only(bottom: 8), child: Text(error!, style: const TextStyle(color: bad))), + Row(children: [ + if (widget.onDelete != null) + TextButton( + onPressed: () { + if (!armed) return setState(() => armed = true); + widget.onDelete!(); + Navigator.pop(context); + }, + child: Text(armed ? 'Tap again to delete' : 'Delete', style: const TextStyle(color: bad)), + ), + const Spacer(), + FilledButton( + onPressed: () { + final vals = {}; + for (final k in fields.keys) { + final t = ctl[k]!.text.trim().replaceAll(',', '.'); + if (t.isEmpty) { + vals[k] = null; + } else if (double.tryParse(t) == null) { + return setState(() => error = '${fields[k]!.$1}: not a number.'); + } else { + vals[k] = double.parse(t); + } + } + final err = widget.onSave(d, vals, note.text, widget.m?.day); + if (err != null) return setState(() => error = err); + Navigator.pop(context); + }, + child: const Text('Save'), + ), + ]), + ]), + ), + ); +} diff --git a/app/lib/health/cycle_doctor.dart b/app/lib/health/cycle_doctor.dart new file mode 100644 index 0000000..c72c94d --- /dev/null +++ b/app/lib/health/cycle_doctor.dart @@ -0,0 +1,74 @@ +// Cycle ▸ For your doctor: the last 12 months as on the web page's History (cycle.views.history's +// doctor part): last period, cycle / period length (average + range), periods logged, pain, +// most common symptoms + moods, and what's worth mentioning by the common guidelines. +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'cycle_model.dart'; + +const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; +String dmy(DateTime d) => '${d.day} ${_mon[d.month - 1]} ${d.year}'; +String _range((int, int)? r) => r == null ? '—' : r.$1 == r.$2 ? '${r.$1} days' : '${r.$1}–${r.$2} days'; + +class DoctorPage extends StatelessWidget { + const DoctorPage({super.key, required this.sync, required this.settings}); + final SyncService sync; + final CycleSettings settings; + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('For your doctor')), + body: ListenableBuilder( + listenable: sync, + builder: (context, _) { + final v = CycleView(sync.store, settings); + if (v.periods.isEmpty) { + return const Center(child: Text('Nothing logged yet.', style: TextStyle(color: muted))); + } + final d = doctor(v); + final rows = <(String, String)>[ + ('First day of last period', d.last == null ? '—' : dmy(d.last!)), + ('Cycle length', d.cycle == null ? 'not enough data yet' : '${d.cycle} days on average · ${_range(d.cycleRange)}'), + ('Period length', d.period == null ? 'not enough data yet' : '${d.period} days on average · ${_range(d.periodRange)}'), + ('Periods logged', '${d.periods}'), + ('Pain', d.painDays == 0 ? 'none logged' : 'on ${d.painDays} day${d.painDays != 1 ? 's' : ''}, ${d.painAvg} / 5 on average'), + ('Most common', d.symptoms.isEmpty ? 'no symptoms logged' : d.symptoms.map((s) => '${s.$1} (${s.$2}×)').join(', ')), + ]; + return ListView(padding: const EdgeInsets.all(12), children: [ + Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Row(children: [ + Expanded(child: Text('${dmy(d.since)} – ${dmy(d.now)}', style: const TextStyle(color: muted))), + const Tooltip( + triggerMode: TooltipTriggerMode.tap, + message: 'From self-logged data; general guidance, not a diagnosis.', + child: Icon(Icons.info_outline, size: 18, color: muted), + ), + ]), + const SizedBox(height: 12), + for (final (k, val) in rows) ...[ + Text(k, style: const TextStyle(color: muted, fontSize: 13)), + Padding(padding: const EdgeInsets.only(top: 2, bottom: 12), child: Text(val, style: const TextStyle(fontSize: 16))), + ], + const Divider(color: card2), + const SizedBox(height: 6), + if (d.flags.isEmpty) + const Text('Nothing unusual by the common guidelines (cycles 21–35 days, periods up to 7 days, ' + 'no spotting between periods, …).', style: TextStyle(color: good)) + else ...[ + const Text('Worth mentioning', style: TextStyle(fontWeight: FontWeight.bold, color: accent)), + const SizedBox(height: 6), + for (final f in d.flags) + Padding(padding: const EdgeInsets.only(bottom: 4), child: Text('• $f')), + ], + ]), + ), + ), + ]); + }, + ), + ); +} diff --git a/app/lib/health/cycle_model.dart b/app/lib/health/cycle_model.dart new file mode 100644 index 0000000..3fc8ce3 --- /dev/null +++ b/app/lib/health/cycle_model.dart @@ -0,0 +1,334 @@ +// The cycle tracker's numbers — a port of the dashboard's plugins/cycle/views.py (keep them in +// step: same rules, same results as the web page) + db.save_day's rules for writing a day. +// +// Data: synced rows "cycle.day", id "day:YYYY-MM-DD": {day, period 0/1, flow 1–5, pain 1–5, +// pain_len, tags "a,b", note, source, updated}. Days are UTC dates here (no DST surprises). +import 'dart:math'; + +import '../sync/store.dart'; + +const history = 12; // cycles averaged (at most) +const halfLife = 180; // days: a cycle this much older counts half as much +const maxCycle = 60; // longer "cycles" are gaps in logging +const luteal = 14; // ovulation -> next period, days +const gap = 2; // unmarked days that don't split a period + +const painLen = {'0-1': 'under 1 h', '1-3': '1–3 h', '3-6': '3–6 h', '6-24': '6–24 h'}; +const tagGroups = { + 'Symptoms': { + 'spotting': 'Spotting', 'headache': 'Headache', 'backache': 'Backache', 'tiredness': 'Tiredness', + 'bloating': 'Bloating', 'breasts': 'Tender breasts', 'acne': 'Acne', 'nausea': 'Nausea', + 'cravings': 'Cravings', 'stomach': 'Upset stomach', 'sleep': 'Poor sleep', 'dizzy': 'Dizziness'}, + 'Mood': { + 'happy': 'Happy', 'calm': 'Calm', 'energetic': 'Energetic', 'sensitive': 'Sensitive', + 'irritable': 'Irritable', 'anxious': 'Anxious', 'sad': 'Sad', 'swings': 'Mood swings', + 'stressed': 'Stressed', 'unmotivated': 'Unmotivated'}, + 'Sex': { + 'sex_prot': 'Sex, protected', 'sex_unprot': 'Sex, unprotected', 'drive': 'Sex drive', + 'drive_low': 'Low sex drive', 'solo': 'Masturbation', 'sex_pain': 'Pain during sex'}, +}; +const flowNames = ['very light', 'light', 'medium', 'heavy', 'very heavy']; +const sources = { + 'xiaomi': ('⌚', 'Imported from Xiaomi (Mi Fitness)'), + 'mymonthlycycles': ('📱', 'Imported from My Monthly Cycles'), + 'calculated': ('≈', 'Calculated: not logged, placed between the periods around it'), +}; +/// Calendar symbols for some tags: (tags, glyph, label); "spot" = a small droplet. +const symbols = [ + ({'sex_prot', 'sex_unprot'}, '♥', 'had sex'), + ({'happy', 'calm', 'energetic'}, '☺', 'good mood'), + ({'sensitive', 'irritable', 'anxious', 'sad', 'swings', 'stressed', 'unmotivated'}, '☹', 'low mood'), + ({'spotting'}, 'spot', 'spotting'), + ({'tiredness'}, '💤', 'tired'), + ({'headache'}, '⚡', 'headache'), +]; + +DateTime day(DateTime d) => DateTime.utc(d.year, d.month, d.day); + +/// Python's round(): halves go to the even number (round(28.5) == 28), so averages match the web page. +int pyRound(double x) { + final f = x.floorToDouble(), diff = x - f; + if (diff > 0.5) return f.toInt() + 1; + if (diff < 0.5) return f.toInt(); + return f.toInt().isEven ? f.toInt() : f.toInt() + 1; +} +DateTime today() => day(DateTime.now()); +DateTime parseDay(String s) => DateTime.parse('${s}T00:00:00Z'); +String iso(DateTime d) => d.toIso8601String().substring(0, 10); +int daysBetween(DateTime a, DateTime b) => b.difference(a).inDays; // b - a +DateTime plus(DateTime d, int n) => d.add(Duration(days: n)); + +class CycleSettings { + const CycleSettings({this.cycleLength = 28, this.periodLength = 5, this.showFertile = true}); + final int cycleLength, periodLength; + final bool showFertile; +} + +class DayLog { + DayLog(this.row); + final Map row; + bool get period => (row['period'] ?? 0) == 1; + int? get flow => row['flow'] as int?; + int? get pain => row['pain'] as int?; + String? get painLength => row['pain_len'] as String?; + List get tags => ((row['tags'] as String?) ?? '').split(',').where((t) => t.isNotEmpty).toList(); + String get note => (row['note'] as String?) ?? ''; + String? get source => row['source'] as String?; + bool get hasLog => pain != null || tags.isNotEmpty || note.isNotEmpty; + + String summary() { + final names = {for (final g in tagGroups.values) ...g}; + return [ + if (pain != null) 'pain $pain/5${painLen[painLength] != null ? ' (${painLen[painLength]})' : ''}', + ...tags.where(names.containsKey).map((t) => names[t]!), + if (note.isNotEmpty) note, + if (sources[source] != null) sources[source]!.$2, + ].join(' · '); + } + + List<(String, String)> get symbolList => + [for (final (ts, g, label) in symbols) if (ts.intersection(tags.toSet()).isNotEmpty) (g, label)]; +} + +class Period { + Period(this.start, this.end, this.calc); + DateTime start, end; + bool calc; + int get length => daysBetween(start, end) + 1; +} + +class CycleStats { + CycleStats(this.cycle, this.period, this.cycles, this.fromData); + final int cycle, period; + final List cycles; + final bool fromData; +} + +int _avg(List<(int, DateTime)> xs, int fallback, DateTime now) { + final last = xs.length > history ? xs.sublist(xs.length - history) : xs; + if (last.isEmpty) return fallback; + final w = [for (final (_, d) in last) pow(0.5, max(0, daysBetween(d, now)) / halfLife).toDouble()]; + var s = 0.0; + for (var i = 0; i < last.length; i++) { + s += last[i].$1 * w[i]; + } + return pyRound(s / w.reduce((a, b) => a + b)); +} + +/// Sorted period days -> runs; up to [gap] unmarked days inside one don't split it. +List periodsOf(List days, Set calc) { + final out = []; + for (final d in days) { + if (out.isNotEmpty && daysBetween(out.last.end, d) <= gap + 1) { + out.last.end = d; + out.last.calc = out.last.calc && calc.contains(d); + } else { + out.add(Period(d, d, calc.contains(d))); + } + } + return out; +} + +bool going(Period p, DateTime now) => !p.end.isBefore(plus(now, -1)); + +/// (length, start of the next period) between consecutive logged periods. +List<(int, DateTime)> realCycles(List ps) => [ + for (var i = 0; i + 1 < ps.length; i++) + if (!ps[i].calc && !ps[i + 1].calc) (daysBetween(ps[i].start, ps[i + 1].start), ps[i + 1].start) + ]; + +CycleStats stats(List ps, CycleSettings s, DateTime now) { + final cyc = realCycles(ps); + final ok = [for (final c in cyc) if (c.$1 >= 15 && c.$1 <= maxCycle) c]; + final lens = [for (final p in ps) if (!going(p, now) && !p.calc) (p.length, p.start)]; + return CycleStats(_avg(ok, s.cycleLength, now), _avg(lens, s.periodLength, now), [for (final c in cyc) c.$1], + ok.isNotEmpty); +} + +/// The next n predicted periods (start, end) + days late (0 = not late). +(List<(DateTime, DateTime)>, int) predict(List ps, CycleStats st, DateTime now, {int n = 4}) { + if (ps.isEmpty) return (const [], 0); + var next = plus(ps.last.start, st.cycle); + final late = next.isBefore(now) ? daysBetween(next, now) : 0; + if (late > 0) next = plus(now, st.cycle); // overdue: "any day now"; the one after counts from today + return ([for (var k = 0; k < n; k++) (plus(next, k * st.cycle), plus(next, k * st.cycle + st.period - 1))], late); +} + +/// {day: "ovul" | "fertile"} before each given period start. +Map fertile(List starts) { + final out = {}; + for (final a in starts) { + final ov = plus(a, -luteal); + for (var k = -5; k <= 1; k++) { + out[plus(ov, k)] = 'fertile'; + } + out[ov] = 'ovul'; + } + return out; +} + +enum Status { empty, period, late, wait } + +/// Everything the Cycle page shows, from the synced rows. +class CycleView { + CycleView(SyncStore store, this.s, {DateTime? now}) : now = now ?? today() { + for (final r in store.rows('cycle.day')) { + final d = parseDay(r['day'] as String); + logs[d] = DayLog(r); + } + final days = [for (final e in logs.entries) if (e.value.period) e.key]..sort(); + marked = days.toSet(); + final calc = {for (final e in logs.entries) if (e.value.source == 'calculated') e.key}; + periods = periodsOf(days, calc); + st = stats(periods, s, this.now); + final (p, l) = predict(periods, st, this.now); + preds = p; + late = l; + final last = periods.isEmpty ? null : periods.last; + if (last != null) { + cycleDay = daysBetween(last.start, this.now) + 1; + status = going(last, this.now) ? Status.period : late > 0 ? Status.late : Status.wait; + } + predDays = {for (final (a, z) in preds) for (var k = 0; k <= daysBetween(a, z); k++) plus(a, k)}; + if (status == Status.period) { + for (var k = 0; k < st.period; k++) { + if (plus(last!.start, k).isAfter(last.end)) predDays.add(plus(last.start, k)); + } + } + final starts = [for (final (a, _) in preds) a]; + if (last != null) starts.add(plus(last.start, st.cycle)); + fert = s.showFertile ? fertile(starts) : {}; + } + + final CycleSettings s; + final DateTime now; + final logs = {}; + late final Set marked; + late final List periods; + late final CycleStats st; + late final List<(DateTime, DateTime)> preds; + late final int late; + late final Set predDays; + late final Map fert; + Status status = Status.empty; + int? cycleDay; + + Period? get last => periods.isEmpty ? null : periods.last; + bool get todayOn => marked.contains(now); + DateTime? get expected => last == null ? null : plus(last!.start, st.cycle); + int? get daysToNext => preds.isEmpty ? null : daysBetween(now, preds.first.$1); + + /// The fertile window that matters now (this cycle's if not over, else the next one's). + (DateTime, DateTime, DateTime)? fertileWindow() { + if (last == null || !s.showFertile) return null; + for (final a in [plus(last!.start, st.cycle), ...preds.map((p) => p.$1)]) { + final ov = plus(a, -luteal); + if (!plus(ov, 1).isBefore(now)) return (plus(ov, -5), plus(ov, 1), ov); + } + return null; + } +} + +// ---- for a doctor (views.history's doctor part + views.flags) -------------------------------- + +const doctorMonths = 12; + +class Doctor { + Doctor({required this.since, required this.now, required this.last, required this.periods, required this.cycle, + required this.cycleRange, required this.period, required this.periodRange, required this.symptoms, + required this.painDays, required this.painAvg, required this.flags}); + final DateTime since, now; + final DateTime? last; + final int periods, painDays; + final int? cycle, period; + final (int, int)? cycleRange, periodRange; + final List<(String, int)> symptoms; + final double? painAvg; + final List flags; +} + +(int, int)? _spread(List xs) => xs.isEmpty ? null : (xs.reduce(min), xs.reduce(max)); + +/// Things worth mentioning to a doctor (common guidance, not a diagnosis). +List flags(List ps, List cycles, Map logs, DateTime now) { + final out = []; + final within = cycles.where((c) => c <= maxCycle).toList(); // longer = a gap in logging + final recent = within.length > 6 ? within.sublist(within.length - 6) : within; + final short = recent.where((c) => c < 21).length, long = recent.where((c) => c > 35).length; + if (short >= 2) out.add('$short of the last ${recent.length} cycles were shorter than 21 days.'); + if (long >= 2) out.add('$long of the last ${recent.length} cycles were longer than 35 days.'); + if (recent.length >= 3 && recent.reduce(max) - recent.reduce(min) > 7) { + out.add('Cycle length varies a lot: ${recent.reduce(min)}–${recent.reduce(max)} days.'); + } + final finished = ps.where((p) => !going(p, now)).toList(); + final done = finished.length > 6 ? finished.sublist(finished.length - 6) : finished; + final longp = done.where((p) => p.length > 7).length; + if (longp > 0) out.add('$longp of the last ${done.length} periods lasted more than 7 days.'); + bool inside(Period p, DateTime d) => !d.isBefore(p.start) && !d.isAfter(p.end); + final heavy = done.where((p) => logs.entries.where((e) => inside(p, e.key) && (e.value.flow ?? 0) >= 4).length >= 3).length; + if (heavy > 0) out.add('$heavy of the last ${done.length} periods had 3 or more heavy days.'); + final since = plus(now, -90); + final spot = logs.entries.where((e) => !e.key.isBefore(since) && e.value.tags.contains('spotting') && !e.value.period).length; + if (spot > 0) out.add('Spotting between periods on $spot day${spot != 1 ? 's' : ''} in the last 3 months.'); + final strong = logs.entries.where((e) => !e.key.isBefore(since) && (e.value.pain ?? 0) >= 4).length; + if (strong >= 3) out.add('Strong pain (4–5 of 5) on $strong days in the last 3 months.'); + if (ps.isNotEmpty && daysBetween(ps.last.start, now) > 90) out.add('No period for ${daysBetween(ps.last.start, now)} days.'); + return out; +} + +Doctor doctor(CycleView v) { + final now = v.now, since = plus(now, -doctorMonths * 30); + final real = v.periods.where((p) => !p.calc).toList(); + final dp = real.where((p) => !p.start.isBefore(since)).toList(); + final dcycles = [ + for (final (c, d) in realCycles(v.periods)) + if (!d.isBefore(since) && c <= maxCycle && !plus(d, -c).isBefore(since)) c + ]; + final dlens = [for (final p in dp) if (!going(p, now)) p.length]; + final names = {for (final g in tagGroups.values) ...g}; + final counts = {}; + final pains = []; + for (final e in v.logs.entries.where((e) => !e.key.isBefore(since))) { + for (final t in e.value.tags) { + if (tagGroups['Symptoms']!.containsKey(t) || tagGroups['Mood']!.containsKey(t)) counts[t] = (counts[t] ?? 0) + 1; + } + if (e.value.pain != null) pains.add(e.value.pain!); + } + final sym = [for (final e in counts.entries) (names[e.key]!, e.value)]..sort((a, b) => b.$2.compareTo(a.$2)); + return Doctor( + since: dp.isNotEmpty && dp.first.start.isAfter(since) ? dp.first.start : since, + now: now, + last: real.isEmpty ? null : real.last.start, + periods: dp.length, + cycle: dcycles.isEmpty ? null : pyRound(dcycles.reduce((a, b) => a + b) / dcycles.length), + cycleRange: _spread(dcycles), + period: dlens.isEmpty ? null : pyRound(dlens.reduce((a, b) => a + b) / dlens.length), + periodRange: _spread(dlens), + symptoms: sym.take(10).toList(), + painDays: pains.length, + painAvg: pains.isEmpty ? null : pyRound(pains.reduce((a, b) => a + b) / pains.length * 10) / 10, + flags: flags(real, v.st.cycles, v.logs, now), + ); +} + +/// db.save_day: set the given fields of a day (the rest stay); a day with nothing left is deleted. +void saveDay(SyncStore store, DateTime d, Map fields) { + if (d.isAfter(today())) throw ArgumentError("That day hasn't happened yet."); + final u = 'day:${iso(d)}'; + final row = store.row('cycle.day', u) ?? + {'day': iso(d), 'period': 0, 'note': '', 'flow': null, 'pain': null, 'pain_len': null, 'tags': '', 'source': null}; + row.addAll(fields); + if (fields.containsKey('tags')) { + final picked = (fields['tags'] as List).cast().toSet(); + row['tags'] = [for (final g in tagGroups.values) ...g.keys.where(picked.contains)].join(','); // stable order + } + final now = DateTime.now(); + row['updated'] = '${iso(now)} ${now.toIso8601String().substring(11, 19)}'; + final empty = row['period'] != 1 && (row['note'] ?? '') == '' && row['flow'] == null && row['pain'] == null && + row['pain_len'] == null && (row['tags'] ?? '') == ''; + if (empty) { + if (store.row('cycle.day', u) != null) store.delete('cycle.day', u); + } else { + store.put('cycle.day', u, row); + } +} diff --git a/app/lib/health/cycle_page.dart b/app/lib/health/cycle_page.dart new file mode 100644 index 0000000..42fdbbc --- /dev/null +++ b/app/lib/health/cycle_page.dart @@ -0,0 +1,351 @@ +// The Cycle page (Health ▸ Cycle): the status ring + one button for today (as on the web page), +// the month calendar, and a day's log as a sheet. Phone difference: tapping a day opens its log; holding +// it marks / unmarks it as a period day (the web's click — not on a tap, so no marks by a stray tap; Undo). +import 'dart:math'; + +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'cycle_model.dart'; + +const periodRed = Color(0xFFE5576B), fertileTeal = Color(0xFF3FB5A0); +const _months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', + 'November', 'December']; +const _dows = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; +String niceDay(DateTime d) => '${_dows[d.weekday - 1]} ${d.day} ${_months[d.month - 1].substring(0, 3)}'; + +class CyclePage extends StatefulWidget { + const CyclePage({super.key, required this.sync}); + final SyncService sync; + @override + State createState() => _CyclePageState(); +} + +class _CyclePageState extends State { + int offset = 0; // months from this one + final settings = const CycleSettings(); // TODO: from synced settings once those sync (Pi: 28 / 5 / fertile on) + + void _save(DateTime d, Map fields) { + saveDay(widget.sync.store, d, fields); + widget.sync.changed(); + } + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: widget.sync, + builder: (context, _) { + final v = CycleView(widget.sync.store, settings); + final status = _StatusCard(v: v, onToday: (on) => _save(v.now, {'period': on ? 1 : 0})); + final month = _Month(v: v, offset: offset, onMove: (d) => setState(() => offset += d), onDay: (d) => _openDay(v, d), + onHold: (d) => _toggle(v, d)); + return LayoutBuilder(builder: (context, box) { + if (box.maxWidth >= 700) { // landscape / tablet: side by side + return SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Expanded(flex: 2, child: status), + const SizedBox(width: 12), + Expanded(flex: 3, child: month), + ]), + ); + } + return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [ + status, + const SizedBox(height: 12), + month, + ]); + }); + }, + ); + + + /// Hold a day: period on that day on / off at once (the web calendar's click); Undo in the snackbar. + void _toggle(CycleView v, DateTime d) { + if (d.isAfter(v.now)) return; + final was = v.marked.contains(d); + HapticFeedback.mediumImpact(); + _save(d, {'period': was ? 0 : 1}); + final m = ScaffoldMessenger.of(context); + m.hideCurrentSnackBar(); + m.showSnackBar(SnackBar( + content: Text('${was ? 'Not a period day' : 'Period'}: ${niceDay(d)}'), + duration: const Duration(seconds: 4), + persist: false, // with an action Flutter keeps it up until tapped + action: SnackBarAction(label: 'Undo', textColor: accent, onPressed: () => _save(d, {'period': was ? 1 : 0})), + )); + } + + Future _openDay(CycleView v, DateTime d) async { + if (d.isAfter(v.now)) return; + await showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => DaySheet(day: d, log: v.logs[d], onSave: (f) => _save(d, f)), + ); + } +} + +/// The status card's two lines (also Health ▸ Overview's period tile). +(String, String) cycleStatus(CycleView v) => switch (v.status) { + Status.empty => ('No periods logged yet', 'Mark the first day of your period.'), + Status.period => ('Period · day ${v.cycleDay}', 'since ${niceDay(v.last!.start)}'), + Status.late => ('${v.late} ${v.late == 1 ? 'day' : 'days'} late', 'expected ${niceDay(v.expected!)}'), + Status.wait => ( + v.daysToNext == 0 ? 'Period expected today' : 'Next period in ${v.daysToNext} ${v.daysToNext == 1 ? 'day' : 'days'}', + '${niceDay(v.preds.first.$1)} · cycle day ${v.cycleDay}'), + }; + +class _StatusCard extends StatelessWidget { + const _StatusCard({required this.v, required this.onToday}); + final CycleView v; + final void Function(bool on) onToday; + + @override + Widget build(BuildContext context) { + final t = Theme.of(context).textTheme; + final (head, sub) = cycleStatus(v); + final button = v.todayOn ? 'Not today — undo' : v.status == Status.period ? 'Period today too' : 'Period started today'; + final fw = v.fertileWindow(); + return Card( + child: Padding( + padding: const EdgeInsets.all(16), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + SizedBox(width: 96, height: 96, child: CustomPaint(painter: _Ring(v), child: Center( + child: Text(v.cycleDay == null || v.status == Status.late ? '' : '${v.cycleDay}', + style: t.headlineMedium?.copyWith(fontWeight: FontWeight.bold))))), + const SizedBox(width: 16), + Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(head, style: t.titleLarge?.copyWith(fontWeight: FontWeight.bold)), + const SizedBox(height: 2), + Text(sub, style: const TextStyle(color: muted)), + if (fw != null) ...[ + const SizedBox(height: 6), + Text(fw.$1.isAfter(v.now) ? 'Fertile ${niceDay(fw.$1)} – ${niceDay(fw.$2)}' : 'Fertile window now, until ${niceDay(fw.$2)}', + style: const TextStyle(color: fertileTeal)), + ], + ])), + ]), + const SizedBox(height: 14), + FilledButton( + style: FilledButton.styleFrom(backgroundColor: v.todayOn ? card2 : periodRed, foregroundColor: Colors.white), + onPressed: () => onToday(!v.todayOn), + child: Text(button), + ), + const SizedBox(height: 10), + Tooltip( + message: v.st.fromData ? 'Recent cycles count more (half as much every 180 days of age)' : 'From the settings until there are logged cycles', + child: Text('Usual cycle ${v.st.cycle} days · period ${v.st.period} days', + textAlign: TextAlign.center, style: const TextStyle(color: muted, fontSize: 13)), + ), + ]), + ), + ); + } +} + +/// The cycle as a circle: the period arc, the fertile arc, today's dot (cycle.views.ring). +class _Ring extends CustomPainter { + _Ring(this.v); + final CycleView v; + + @override + void paint(Canvas c, Size size) { + final r = size.width / 2 - 6, o = Offset(size.width / 2, size.height / 2); + final n = max(v.st.cycle, max(v.cycleDay ?? 0, 1)); + Paint p(Color col, double w) => Paint()..color = col..style = PaintingStyle.stroke..strokeWidth = w..strokeCap = StrokeCap.round; + c.drawCircle(o, r, p(card2, 8)); + if (v.last == null) return; + void arc(int d0, int d1, Color col) { + final a0 = (d0 - 1) / n * 2 * pi - pi / 2, sweep = (d1 - d0 + 1) / n * 2 * pi; + c.drawArc(Rect.fromCircle(center: o, radius: r), a0, sweep, false, p(col, 8)); + } + arc(1, min(v.st.period, n), periodRed); + final ov = v.st.cycle - luteal; + if (v.s.showFertile && ov - 5 > v.st.period) arc(ov - 5, ov + 1, fertileTeal); + if (v.cycleDay != null && v.status != Status.late) { + final a = (v.cycleDay! - .5) / n * 2 * pi - pi / 2; + final at = o + Offset(cos(a), sin(a)) * r; + c.drawCircle(at, 8.5, Paint()..color = card); // the web's dot outline (stroke: var(--card)) + c.drawCircle(at, 7, Paint()..color = Colors.white); + } + } + + @override + bool shouldRepaint(covariant _Ring old) => true; +} + +class _Month extends StatelessWidget { + const _Month({required this.v, required this.offset, required this.onMove, required this.onDay, required this.onHold}); + final CycleView v; + final int offset; + final void Function(int) onMove; + final void Function(DateTime) onDay, onHold; + + @override + Widget build(BuildContext context) { + final m0 = DateTime.utc(v.now.year, v.now.month + offset, 1); + final g0 = plus(m0, -(m0.weekday - 1)); + final mEnd = DateTime.utc(m0.year, m0.month + 1, 0); + final g1 = plus(mEnd, 7 - mEnd.weekday); + final weeks = >[]; + for (var d = g0; !d.isAfter(g1); d = plus(d, 7)) { + weeks.add([for (var k = 0; k < 7; k++) plus(d, k)]); + } + return Card( + child: Padding( + padding: const EdgeInsets.fromLTRB(8, 4, 8, 12), + child: Column(children: [ + Row(children: [ + IconButton(onPressed: () => onMove(-1), icon: const Icon(Icons.chevron_left)), + Expanded(child: Text('${_months[m0.month - 1]} ${m0.year}', textAlign: TextAlign.center, + style: const TextStyle(fontSize: 17, fontWeight: FontWeight.bold))), + IconButton(onPressed: offset < 12 ? () => onMove(1) : null, icon: const Icon(Icons.chevron_right)), + ]), + Row(children: [for (final d in _dows) Expanded(child: Text(d, textAlign: TextAlign.center, style: const TextStyle(color: muted, fontSize: 12)))]), + const SizedBox(height: 4), + for (final w in weeks) + Row(children: [for (final d in w) Expanded(child: _Cell(v: v, d: d, out: d.month != m0.month, onTap: () => onDay(d), onHold: () => onHold(d)))]), + ]), + ), + ); + } +} + +class _Cell extends StatelessWidget { + const _Cell({required this.v, required this.d, required this.out, required this.onTap, required this.onHold}); + final CycleView v; + final DateTime d; + final bool out; + final VoidCallback onTap, onHold; // tap = the day's log, hold = period on / off + + @override + Widget build(BuildContext context) { + final on = v.marked.contains(d), pred = !on && v.predDays.contains(d), fert = on ? null : v.fert[d]; + final log = v.logs[d]; + final isToday = d == v.now, future = d.isAfter(v.now); + final syms = log?.symbolList ?? const []; + return GestureDetector( + onTap: future ? null : onTap, + onLongPress: future ? null : onHold, + child: Opacity( + opacity: out ? 0.35 : 1, + child: Container( + height: MediaQuery.of(context).orientation == Orientation.landscape ? 44 : 52, + margin: const EdgeInsets.all(1.5), + decoration: BoxDecoration( + color: fert != null ? fertileTeal.withValues(alpha: 0.14) : null, + borderRadius: BorderRadius.circular(8), + border: isToday ? Border.all(color: accent, width: 1.5) : null, + ), + child: Stack(children: [ + Center( + child: Container( + width: 32, height: 32, + alignment: Alignment.center, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: on ? periodRed.withValues(alpha: 0.35 + 0.13 * ((log?.flow ?? 3) - 1)) : null, + border: pred ? Border.all(color: periodRed, width: 1.5) : fert == 'ovul' ? Border.all(color: fertileTeal, width: 2) : null, + ), + child: Text('${d.day}', style: TextStyle(color: future ? muted : Colors.white, fontWeight: isToday ? FontWeight.bold : null)), + ), + ), + if (syms.isNotEmpty) + Positioned(left: 3, top: 1, child: Text(syms.map((s) => s.$1 == 'spot' ? '•' : s.$1).join(), style: const TextStyle(fontSize: 9))), + if (log?.hasLog ?? false) const Positioned(right: 4, top: 3, child: Icon(Icons.edit, size: 9, color: accent)), + if (sources[log?.source] != null) + Positioned(left: 3, bottom: 1, child: Text(sources[log!.source]!.$1, style: const TextStyle(fontSize: 8, color: muted))), + ]), + ), + ), + ); + } +} + +/// A day's log: period on / off + flow, pain + how long, tags, note — saved together. +class DaySheet extends StatefulWidget { + const DaySheet({super.key, required this.day, required this.log, required this.onSave}); + final DateTime day; + final DayLog? log; + final void Function(Map) onSave; + @override + State createState() => _DaySheetState(); +} + +class _DaySheetState extends State { + late bool period = widget.log?.period ?? false; + late int? flow = widget.log?.flow, pain = widget.log?.pain; + late String? len = widget.log?.painLength; + late final Set tags = {...?widget.log?.tags}; + late final note = TextEditingController(text: widget.log?.note ?? ''); + + @override + Widget build(BuildContext context) => Padding( + padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), + child: DraggableScrollableSheet( + expand: false, + initialChildSize: 0.75, + maxChildSize: 0.95, + builder: (context, scroll) => ListView(controller: scroll, padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), children: [ + Center(child: Container(width: 36, height: 4, decoration: BoxDecoration(color: muted, borderRadius: BorderRadius.circular(2)))), + const SizedBox(height: 12), + Text(niceDay(widget.day), style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: accent)), + SwitchListTile(contentPadding: EdgeInsets.zero, title: const Text('Period day'), value: period, + activeThumbColor: periodRed, onChanged: (x) => setState(() => period = x)), + if (period) ...[ + const Text('Flow', style: TextStyle(color: muted)), + Row(children: [ + for (var i = 1; i <= 5; i++) + IconButton( + tooltip: flowNames[i - 1], + onPressed: () => setState(() => flow = flow == i ? null : i), + icon: Icon(Icons.water_drop, size: 16.0 + i * 3, color: (flow ?? 0) >= i ? periodRed : card2), + ), + ]), + ], + const SizedBox(height: 8), + const Text('Pain', style: TextStyle(color: muted)), + Wrap(spacing: 6, children: [ + for (var i = 1; i <= 5; i++) + ChoiceChip(label: Text('$i'), selected: pain == i, onSelected: (x) => setState(() => pain = x ? i : null)), + ]), + if (pain != null) + Wrap(spacing: 6, children: [ + for (final e in painLen.entries) + ChoiceChip(label: Text(e.value), selected: len == e.key, onSelected: (x) => setState(() => len = x ? e.key : null)), + ]), + for (final g in tagGroups.entries) ...[ + const SizedBox(height: 10), + Text(g.key, style: const TextStyle(color: muted)), + Wrap(spacing: 6, runSpacing: 2, children: [ + for (final t in g.value.entries) + FilterChip( + label: Text(t.value), + selected: tags.contains(t.key), + onSelected: (x) => setState(() { + x ? tags.add(t.key) : tags.remove(t.key); + if (x && t.key == 'drive') tags.remove('drive_low'); // exclusive, like the web page + if (x && t.key == 'drive_low') tags.remove('drive'); + }), + ), + ]), + ], + const SizedBox(height: 10), + TextField(controller: note, maxLines: 3, maxLength: 2000, decoration: const InputDecoration(labelText: 'Note')), + const SizedBox(height: 8), + FilledButton( + onPressed: () { + widget.onSave({'period': period ? 1 : 0, 'flow': flow, 'pain': pain, 'pain_len': pain == null ? null : len, + 'tags': tags.toList(), 'note': note.text.trim()}); + Navigator.pop(context); + }, + child: const Text('Save'), + ), + ]), + ), + ); +} diff --git a/app/lib/health/food_archive.dart b/app/lib/health/food_archive.dart new file mode 100644 index 0000000..5bf8702 --- /dev/null +++ b/app/lib/health/food_archive.dart @@ -0,0 +1,226 @@ +// Every Open Food Facts product (2 million+, every country), searched on the sync server's archive +// (GET /v1/food/search — sync-server/src/food.php), with filters: country, brand, Nutri-Score; a +// barcode finds that product. A pick is kept ("food.product", food_model.dart keepProduct) and synced, +// so entries made from it work on every device. Also the camera barcode scanner (ZXing, no Google services). +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; +import 'package:flutter_zxing/flutter_zxing.dart' show Format; + +import '../app/scanner.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'food_model.dart'; + +const _countries = [('', 'Any country'), ('ro', 'Romania'), ('sk', 'Slovakia'), ('cz', 'Czechia'), ('hu', 'Hungary'), ('at', 'Austria'), + ('de', 'Germany'), ('pl', 'Poland'), ('it', 'Italy'), ('fr', 'France'), ('es', 'Spain'), ('uk', 'UK'), ('us', 'USA')]; +const _scores = [('', 'Any Nutri-Score'), ('a', 'A'), ('ab', 'A–B'), ('abc', 'A–C')]; + +/// The archive's search: [q] (or a barcode), filters → its products (as it sends them), or throws a message. +Future>> archiveSearch(SyncService sync, Map p) async { + final s = sync.settings; + final query = {for (final e in p.entries) if (e.value.isNotEmpty) e.key: e.value, 'limit': '25'}; + final uri = Uri.parse('${s.server.replaceAll(RegExp(r'/+$'), '')}/v1/food/search').replace(queryParameters: query); + final http.Response r; + try { + r = await http.get(uri, headers: {'Authorization': 'Bearer ${s.token}', 'Accept': 'application/json'}) + .timeout(const Duration(seconds: 20)); + } catch (_) { + throw 'The sync server can\'t be reached — no connection?'; + } + final j = jsonDecode(r.body); + if (r.statusCode != 200) throw (j is Map ? j['error'] : null) ?? 'Error ${r.statusCode}'; + return ((j as Map)['items'] as List).cast>(); +} + +/// The archive's search sheet → the product picked (kept already), or null. +Future openArchive(BuildContext context, SyncService sync, FoodDb? fdb, String q) => showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => ArchiveSheet(sync: sync, fdb: fdb, q: q), +); + +class ArchiveSheet extends StatefulWidget { + const ArchiveSheet({super.key, required this.sync, required this.fdb, required this.q}); + final SyncService sync; + final FoodDb? fdb; + final String q; + @override + State createState() => _ArchiveSheetState(); +} + +class _ArchiveSheetState extends State { + late final q = TextEditingController(text: widget.q); + final brand = TextEditingController(); + String country = '', score = ''; + List> items = []; + String? status; + Timer? timer; + int seq = 0; + + @override + void initState() { + super.initState(); + _run(); + } + + @override + void dispose() { + timer?.cancel(); + super.dispose(); + } + + void _soon() { + timer?.cancel(); + timer = Timer(const Duration(milliseconds: 350), _run); + } + + Future _run() async { + final text = q.text.trim(), n = ++seq; + final code = RegExp(r'^\d{8,14}$').hasMatch(text); + if (!code && text.length < 3 && brand.text.trim().isEmpty && country.isEmpty) { + setState(() { + items = []; + status = 'Type at least 3 letters, or pick a filter.'; + }); + return; + } + setState(() => status = 'Searching…'); + try { + final got = await archiveSearch(widget.sync, { + if (code) 'barcode': text else 'q': text, + 'country': country, 'brand': brand.text.trim(), 'nutriscore': score, + }); + if (!mounted || n != seq) return; + setState(() { + items = got; + status = got.isEmpty ? 'Nothing found.' : null; + }); + } catch (e) { + if (mounted && n == seq) { + setState(() { + items = []; + status = '$e'; + }); + } + } + } + + String _home(String c) { + final cs = c.split(' ').where((x) => x.isNotEmpty).toList(); + return cs.take(3).map((x) => x[0].toUpperCase() + x.substring(1).replaceAll('-', ' ')).join(', ') + (cs.length > 3 ? ' …' : ''); + } + + void _pick(Map it) { + final id = (it['id'] as num).toInt(); + final f = widget.fdb?.food(id) ?? keepProduct(widget.sync.store, it); // one you have already: that one + if (f == null) { + setState(() => status = 'That product came back garbled.'); + return; + } + widget.sync.changed(); + Navigator.of(context).pop(f); + } + + Widget _drop(List<(String, String)> opts, String value, void Function(String) set) => DropdownButton( + value: value, + isDense: true, + underline: const SizedBox(), + dropdownColor: card2, + items: [for (final (k, l) in opts) DropdownMenuItem(value: k, child: Text(l, style: const TextStyle(fontSize: 13.5)))], + onChanged: (v) { + set(v ?? ''); + _run(); + }, + ); + + @override + Widget build(BuildContext context) { + final h = MediaQuery.of(context).size.height; + return Padding( + padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), + child: ConstrainedBox( + constraints: BoxConstraints(maxHeight: h * 0.85), + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 12), + child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + const Text('All products', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)), + const Text('Open Food Facts — every country, through the sync server', style: TextStyle(color: muted, fontSize: 12.5)), + const SizedBox(height: 6), + TextField( + controller: q, + autofocus: widget.q.isEmpty, + decoration: InputDecoration( + prefixIcon: const Icon(Icons.search), + hintText: 'Name, brand or barcode…', + suffixIcon: IconButton( + tooltip: 'Scan a barcode', + icon: const Icon(Icons.qr_code_scanner), + onPressed: () async { + final code = await scanBarcode(context); + if (code != null) { + q.text = code; + _run(); + } + }, + ), + ), + onChanged: (_) => _soon(), + onSubmitted: (_) => _run(), + ), + Wrap(spacing: 12, crossAxisAlignment: WrapCrossAlignment.center, children: [ + _drop(_countries, country, (v) => country = v), + _drop(_scores, score, (v) => score = v), + SizedBox( + width: 120, + child: TextField( + controller: brand, + style: const TextStyle(fontSize: 13.5), + decoration: const InputDecoration(isDense: true, hintText: 'Brand'), + onChanged: (_) => _soon(), + ), + ), + ]), + if (status != null) Padding(padding: const EdgeInsets.only(top: 10), child: Text(status!, style: const TextStyle(color: muted))), + Flexible( + child: ListView(shrinkWrap: true, children: [ + for (final it in items) + ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + title: Text('${it['name']}', maxLines: 1, overflow: TextOverflow.ellipsis), + subtitle: Text( + [ + if ('${it['brand'] ?? ''}'.isNotEmpty) '${it['brand']}', + _home('${it['countries'] ?? ''}'), + if (widget.fdb?.food((it['id'] as num).toInt()) != null) '✓ you have it', + ].where((x) => x.isNotEmpty).join(' · '), + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(color: muted), + ), + trailing: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.end, children: [ + Text('${((it['per100'] as Map?)?['kcal'] as num? ?? 0).round()} kcal', style: const TextStyle(fontSize: 13.5)), + if (it['nutriscore'] != null) + Text('Nutri-Score ${'${it['nutriscore']}'.toUpperCase()}', style: const TextStyle(color: muted, fontSize: 11.5)), + ]), + onTap: () => _pick(it), + ), + ]), + ), + ]), + ), + ), + ); + } +} + +/// The camera, until a product barcode (EAN / UPC) is read → its digits, or null (closed) — app/scanner.dart. +Future scanBarcode(BuildContext context) => scanCode(context, + title: 'Scan a barcode', + format: Format.ean13 | Format.ean8 | Format.upca | Format.upce, + accept: (v) => RegExp(r'^\d{8,14}$').hasMatch(v)); diff --git a/app/lib/health/food_history.dart b/app/lib/health/food_history.dart new file mode 100644 index 0000000..3bc7cd6 --- /dev/null +++ b/app/lib/health/food_history.dart @@ -0,0 +1,208 @@ +// Food ▸ History (views.history): over the shared Health period — tiles (the average *logged* day: +// empty days don't count as zero; days logged + within 10 % of the target; protein, fibre; where the +// energy came from), energy per day (per week from 120 days: the average logged day) stacked by macro +// with the target as a dashed line (tap a bar = its numbers), and the foods eaten most. +import 'dart:math'; + +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'cycle_model.dart' show daysBetween, parseDay, plus, today; +import 'food_model.dart'; +import 'food_page.dart' show macroColors; +import '../widgets/line_chart.dart' show RangeChip; +import 'range.dart'; + +const weeklyFrom = 120; +const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +class FoodHistoryPage extends StatefulWidget { + const FoodHistoryPage({super.key, required this.sync, required this.range}); + final SyncService sync; + final HealthRange range; + @override + State createState() => _FoodHistoryPageState(); +} + +class _FoodHistoryPageState extends State { + String? tip; + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('Food history')), + body: ListenableBuilder( + listenable: Listenable.merge([widget.sync, widget.range]), + builder: (context, _) { + final store = widget.sync.store; + final now = today(); + final first = store.db.select("SELECT min(json_extract(data, '\$.day')) AS d FROM rec WHERE t = 'food.entry'").first['d'] as String?; + final a = widget.range.from(first == null ? now : parseDay(first), now); + final days = dayTotals(store, dayIso(a), dayIso(now)); + final logged = days.values.where((v) => (v['kcal'] ?? 0) > 0).toList(); + double? avg(String k) => logged.isEmpty ? null : logged.map((v) => v[k] ?? 0).reduce((x, y) => x + y) / logged.length; + final target = targets(store, FoodSettings.of(store))['kcal']!.$1; + final onTarget = logged.where((v) => ((v['kcal'] ?? 0) - target).abs() <= target * 0.1).length; + final e = {for (final m in macros) m: (avg(m) ?? 0) * kcalPerG[m]!}; + final tot = e.values.fold(0, (x, y) => x + y); + final top = topFoods(store, dayIso(a), dayIso(now)); + String r(double? v) => v == null ? '—' : v.round().toString(); + return ListView(padding: const EdgeInsets.all(12), children: [ + GridView.count( + crossAxisCount: MediaQuery.of(context).size.width >= 700 ? 4 : 2, + shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), + mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.9, + children: [ + _tile('Average day', '${r(avg('kcal'))} kcal', 'target ${target.round()}'), + _tile('Days logged', '${logged.length} of ${daysBetween(a, now) + 1}', '$onTarget within 10 % of target'), + _tile('Protein', '${r(avg('protein'))} g', 'a logged day on average'), + _tile('Fibre', '${r(avg('fiber'))} g', 'at least 25 g'), + ], + ), + const SizedBox(height: 10), + if (tot > 0) + Card(child: Padding( + padding: const EdgeInsets.all(12), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + const Text('Where the energy came from', style: TextStyle(color: muted, fontSize: 13)), + const SizedBox(height: 6), + ClipRRect(borderRadius: BorderRadius.circular(5), child: Row(children: [ + for (final m in macros) Expanded(flex: max(1, (100 * e[m]! / tot).round()), + child: Container(height: 12, color: macroColors[m])), + ])), + const SizedBox(height: 4), + Text(macros.map((m) => '${m[0].toUpperCase()}${m.substring(1)} ${(100 * e[m]! / tot).round()} %').join(' · '), + style: const TextStyle(fontSize: 13)), + ]), + )), + const SizedBox(height: 10), + Card(child: Padding( + padding: const EdgeInsets.fromLTRB(10, 10, 10, 6), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + const Expanded(child: Text('Energy per day', style: TextStyle(fontWeight: FontWeight.bold))), + RangeChip(widget.range), + ]), + const SizedBox(height: 8), + _Bars(days: days, a: a, z: now, target: target, onTip: (t) => setState(() => tip = t)), + SizedBox(height: 20, child: Text(tip ?? 'Tap a bar for its numbers', textAlign: TextAlign.center, + style: const TextStyle(color: muted, fontSize: 12.5))), + ]), + )), + const SizedBox(height: 10), + if (top.isNotEmpty) + Card(child: Padding( + padding: const EdgeInsets.all(12), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + const Text('Eaten most', style: TextStyle(fontWeight: FontWeight.bold)), + for (final (name, n, kcal) in top) + Padding(padding: const EdgeInsets.symmetric(vertical: 4), child: Row(children: [ + Expanded(child: Text(name)), + Text('$n× · ${kcal.round()} kcal', style: const TextStyle(color: muted)), + ])), + ]), + )), + ]); + }, + ), + ); + + Widget _tile(String label, String value, String sub) => Card(child: Padding( + padding: const EdgeInsets.all(12), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ + Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)), + Text(value, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold)), + Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 12)), + ]), + )); +} + +/// Bars per day (or per week, the average logged day), stacked protein / carbs / fat by energy, the rest grey. +class _Bars extends StatelessWidget { + const _Bars({required this.days, required this.a, required this.z, required this.target, required this.onTip}); + final Map> days; + final DateTime a, z; + final double target; + final void Function(String) onTip; + + List<(DateTime, List>, String)> _buckets() { + final n = daysBetween(a, z) + 1; + final out = <(DateTime, List>, String)>[]; + if (n >= weeklyFrom) { + for (var s = plus(a, -(a.weekday - 1)); !s.isAfter(z); s = plus(s, 7)) { + final vs = [for (var i = 0; i < 7; i++) days[dayIso(plus(s, i))]].whereType>() + .where((v) => (v['kcal'] ?? 0) > 0).toList(); + out.add((s, vs, 'Week of ${s.day} ${_mon[s.month - 1]} ${s.year}')); + } + } else { + for (var i = 0; i < n; i++) { + final x = plus(a, i), v = days[dayIso(x)]; + out.add((x, v != null && (v['kcal'] ?? 0) > 0 ? [v] : [], '${x.day} ${_mon[x.month - 1]} ${x.year}')); + } + } + return out; + } + + @override + Widget build(BuildContext context) { + final b = _buckets(); + return LayoutBuilder(builder: (context, box) => GestureDetector( + onTapDown: (d) { + final i = (d.localPosition.dx / box.maxWidth * b.length).floor().clamp(0, b.length - 1); + final (_, vs, label) = b[i]; + if (vs.isEmpty) return onTip('$label · nothing logged'); + double av(String k) => vs.map((v) => v[k] ?? 0).reduce((x, y) => x + y) / vs.length; + onTip('$label · ${av('kcal').round()} kcal${vs.length > 1 ? ' (${vs.length} days)' : ''} · ' + 'P ${av('protein').round()} g, C ${av('carbs').round()} g, F ${av('fat').round()} g'); + }, + child: CustomPaint(size: Size(box.maxWidth, 170), painter: _BarsPainter(b, target)), + )); + } +} + +class _BarsPainter extends CustomPainter { + _BarsPainter(this.b, this.target); + final List<(DateTime, List>, String)> b; + final double target; + + @override + void paint(Canvas c, Size size) { + const mb = 16.0; + final h = size.height - mb; + double avg(List> vs, String k) => vs.map((v) => v[k] ?? 0).reduce((x, y) => x + y) / vs.length; + final peak = [target * 1.25, for (final (_, vs, _) in b) if (vs.isNotEmpty) avg(vs, 'kcal')].reduce(max); + double y(double k) => h - h * k / peak; + final bw = size.width / max(1, b.length), pad = bw > 4 ? bw * 0.18 : 0.0; + for (var i = 0; i < b.length; i++) { + final (x, vs, _) = b[i]; + if (vs.isNotEmpty) { + final k = avg(vs, 'kcal'); + final e = {for (final m in macros) m: avg(vs, m) * kcalPerG[m]!}; + final sum = e.values.reduce((p, q) => p + q); + final scale = sum > k ? k / sum : 1.0; // labels' macros can add up past the kcal + var base = 0.0; + for (final m in macros) { + final hh = e[m]! * scale; + if (hh > 0) c.drawRect(Rect.fromLTRB(i * bw + pad, y(base + hh), (i + 1) * bw - pad, y(base)), Paint()..color = macroColors[m]!); + base += hh; + } + if (k - base > 1) c.drawRect(Rect.fromLTRB(i * bw + pad, y(k), (i + 1) * bw - pad, y(base)), Paint()..color = muted); + } + final weekly = b.length > 1 && b[1].$1.difference(b[0].$1).inDays == 7; + final label = weekly ? (x.day <= 7 && (b.length <= 30 || x.month % 3 == 1) ? _mon[x.month - 1] : null) + : b.length > 35 ? (x.day == 1 ? _mon[x.month - 1] : null) : (x.weekday == 1 || b.length <= 8 ? '${x.day} ${_mon[x.month - 1]}' : null); + if (label != null) { + final tp = TextPainter(text: TextSpan(text: label, style: const TextStyle(color: muted, fontSize: 10.5)), + textDirection: TextDirection.ltr)..layout(); + tp.paint(c, Offset(i * bw + bw / 2 - tp.width / 2, h + 3)); + } + } + final ty = y(target); + for (var x = 0.0; x < size.width; x += 8) { + c.drawLine(Offset(x, ty), Offset(min(x + 4, size.width), ty), Paint()..color = accent..strokeWidth = 1.2); + } + } + + @override + bool shouldRepaint(covariant _BarsPainter old) => true; +} diff --git a/app/lib/health/food_model.dart b/app/lib/health/food_model.dart new file mode 100644 index 0000000..ac85965 --- /dev/null +++ b/app/lib/health/food_model.dart @@ -0,0 +1,720 @@ +// The food diary — a port of the dashboard's plugins/food: db.py (what an entry is, recent foods), +// fooddb.py (the food database: search, portions → grams → nutrients), views.py (totals, targets, +// the ring, the bars). Keep them in step with the web pages. +// +// Synced rows: "food.entry" {day, time, meal, name, kcal, protein, carbs, sugar, fiber, fat, sat_fat, +// mono_fat, poly_fat, trans_fat, sodium_mg, cholesterol_mg, potassium_mg, micros, source, src_id, +// amount, unit, note, food_id (foods.db id), grams, my_food_id (a "food.food" id)}; "food.food" = +// My foods + meals (per 100 g, portions JSON, recipe JSON, gone). +// foods.db (USDA + Open Food Facts, read-only) ships with the app — the same file as on the Pi, so +// food_id means the same food on both. "food.product" = shop products picked from the archive on the +// sync server (every Open Food Facts product; uid "p:", {food_id, name, brand, barcode, data +// JSON = the product, added}) — FoodDb.food finds them too, so entries made from them work everywhere. +import 'dart:convert'; +import 'dart:io'; +import 'dart:math'; + +import 'package:flutter/services.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:sqlite3/sqlite3.dart'; + +import '../sync/store.dart'; +import 'body_model.dart' show BodyView, bmrMifflin, female, profileOf; +import 'cycle_model.dart' show iso; +import 'summaries.dart'; + +const mealKeys = ['breakfast', 'lunch', 'dinner', 'snack']; +const mealLabels = {'breakfast': 'Breakfast', 'lunch': 'Lunch', 'dinner': 'Dinner', 'snack': 'Snacks', '': 'Other'}; +const kcalPerG = {'protein': 4, 'carbs': 4, 'fat': 9}; +const macros = ['protein', 'carbs', 'fat']; +const foodCols = ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'mono_fat', 'poly_fat', 'trans_fat', + 'sodium_mg', 'cholesterol_mg', 'potassium_mg']; +const reuseSources = {'manual', 'parsed'}; // entries worth offering again (imports are too rough) +const generic = {'tbsp (15 ml)': 15.0, 'tsp (5 ml)': 5.0}; // spoons every food can be measured in (ml as g) + +/// The dashboard's Settings ▸ Food, as its Health summary brings it (meta:food); its defaults until then. +class FoodSettings { + const FoodSettings({this.goalRate = 0, this.split = (20, 50, 30), this.kcalTarget = 0, this.fiberMin = 25, + this.sugarMax = 50, this.sodiumMax = 2000}); + final double goalRate; // % of the weight a week (0 = keep it) + final (int, int, int) split; // protein / carbs / fat % of the energy + final int kcalTarget, fiberMin, sugarMax, sodiumMax; + + static FoodSettings of(SyncStore store) { + final m = Summaries(store).meta('food'); + if (m == null) return const FoodSettings(); + final sp = (m['split'] as List?)?.map((v) => (v as num).toInt()).toList(); + int n(String k, int d) => (m[k] as num?)?.toInt() ?? d; + return FoodSettings( + goalRate: (m['goal_rate'] as num?)?.toDouble() ?? 0, + split: sp != null && sp.length == 3 ? (sp[0], sp[1], sp[2]) : (20, 50, 30), + kcalTarget: n('kcal_target', 0), fiberMin: n('fiber_min', 25), sugarMax: n('sugar_max', 50), + sodiumMax: n('sodium_max', 2000)); + } +} + +// ---- a food (the database's or one of My foods) --------------------------------------------- + +class Portion { + const Portion(this.label, this.grams); + final String label; + final double grams; +} + +class Food { + Food({required this.ref, required this.kind, required this.name, this.category = '', this.brand, this.barcode, required this.per100, + required this.portions, this.nutriscore, this.nova, this.foodId, this.myUid, this.isMeal = false, this.source = '', + this.labels = '', this.sugarsIn, this.dairy, this.addedSugar}); + final String ref, kind, name, category; // ref "usda:ID" / "my:UID"; kind usda / off / my + final String source, labels; // foods.db: foundation / sr_legacy / survey / off; OFF labels ("no added sugar" …) + final String? brand, barcode, nutriscore; + final int? nova, foodId; + // off.py's facts for the added-sugar estimate (sugar.dart): the sweet ingredients ("" = none; null = not known), + // filed as dairy (1 / 0), the label's added sugars g / 100 g + final String? sugarsIn; + final int? dairy; + final double? addedSugar; + final String? myUid; + final Map per100; + final List portions; + final bool isMeal; + + /// g, ml, its portions, and the generic spoons unless it has its own (food.js unitsOf). + List get units { + final own = portions.map((p) => p.label).toList(); + final hasSpoon = own.any((l) => RegExp(r'^(tablespoon|tbsp|teaspoon|tsp)', caseSensitive: false).hasMatch(l)); + return ['g', 'ml', ...own, if (!hasSpoon) ...generic.keys]; + } + + /// Grams of [amount] [unit] (fooddb.portion for the units the form offers), or null. + double? grams(double amount, String unit) { + if (unit == 'g' || unit == 'ml') return amount; + if (generic.containsKey(unit)) return amount * generic[unit]!; + for (final p in portions) { + if (p.label == unit) return amount * p.grams; + } + return null; + } + + /// The food's columns for that many grams (fooddb.nutrients). + Map nutrients(double grams) => + {for (final c in foodCols) c: per100[c] == null ? null : (per100[c]! * grams / 100 * 100).round() / 100}; +} + +// ---- foods.db (the database) --------------------------------------------------------------- + +class FoodDb { + FoodDb._(this.db); + final Database db; + + static FoodDb? _one; + static SyncStore? store; // the synced data: products kept from the archive ("food.product") — set in main.dart + + /// Copies the shipped foods.db out of the app (once per version of the file) and opens it read-only. + static Future open() async { + if (_one != null) return _one!; + final data = await rootBundle.load('assets/foods.db'); + final path = '${(await getApplicationSupportDirectory()).path}/foods.db'; + final f = File(path); + if (!f.existsSync() || f.lengthSync() != data.lengthInBytes) { + await f.writeAsBytes(data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes), flush: true); + } + return _one = FoodDb._(sqlite3.open(path, mode: OpenMode.readOnly)); + } + + static const _stop = {'with', 'and', 'of', 'a', 'an', 'the', 'in', 'on', 'some', 'my'}; + static const _plain = {'nfs', 'raw', 'whole', 'plain', 'regular', 'fresh', 'cooked', 'boiled'}; + static const _rank = {'foundation': 0, 'sr_legacy': 1, 'survey': 2, 'off': 3}; + + static List words(String q) => RegExp(r'\w+', unicode: true) + .allMatches(q.toLowerCase()) + .map((m) => m.group(0)!) + .where((w) => (w.length > 1 || int.tryParse(w) != null) && !_stop.contains(w)) + .toList(); + + Food _food(Row r) { + final off = r['source'] == 'off'; + return Food( + ref: 'usda:${r['id']}', kind: off ? 'off' : 'usda', name: r['name'] as String, category: r['category'] as String? ?? '', + brand: r['brand'] as String?, barcode: r.containsKey('barcode') ? r['barcode'] as String? : null, + nutriscore: r['nutriscore'] as String?, nova: (r['nova'] as num?)?.toInt(), + foodId: r['id'] as int, source: r['source'] as String? ?? '', labels: r['labels'] as String? ?? '', + // a foods.db older than these columns: none of them (the old rule) + sugarsIn: r.containsKey('sugars_in') ? r['sugars_in'] as String? : null, + dairy: r.containsKey('dairy') ? (r['dairy'] as num?)?.toInt() : null, + addedSugar: r.containsKey('added_sugar') ? (r['added_sugar'] as num?)?.toDouble() : null, + per100: {for (final c in foodCols) c: (r[c] as num?)?.toDouble()}, + portions: [ + for (final p in db.select('SELECT label, grams FROM portion WHERE food_id = ? ORDER BY seq, grams', [r['id']])) + Portion(p['label'] as String, (p['grams'] as num).toDouble()) + ], + ); + } + + /// A food of the database by id: foods.db's, else a product kept from the archive. + Food? food(int id) { + final r = db.select('SELECT * FROM food WHERE id = ?', [id]).firstOrNull; + return r != null ? _food(r) : store == null ? null : keptProduct(store!, id); + } + + /// The products with that barcode (foods.db keeps it as on the pack), else kept ones. + List byBarcode(String code) { + final rs = db.select("SELECT * FROM food WHERE barcode = ? OR barcode = ?", [code, code.replaceFirst(RegExp(r'^0+'), '')]); + return rs.isNotEmpty ? [for (final r in rs) _food(r)] : store == null ? [] : keptByBarcode(store!, code); + } + + /// fooddb.search: every word a prefix in name / brand / category; all in the name first, the name starting + /// with the first word, plain versions (raw, NFS …), fewer words, relevance, shorter names; one per name. + List search(String q, {int limit = 10}) { + final ws = words(q); + if (ws.isEmpty) return []; + final terms = ws.map((w) => '"$w"*').join(' '); + final rs = db.select( + 'SELECT f.*, bm25(food_fts, 10, 1) AS rank FROM food_fts JOIN food f ON f.id = food_fts.rowid ' + 'WHERE food_fts MATCH ? ORDER BY rank LIMIT 200', [terms]); + final first = ws.first; + List key(Row r) { + final name = (r['name'] as String).toLowerCase(); + final nameWords = RegExp(r'\w+', unicode: true).allMatches(name).map((m) => m.group(0)!).toList(); + final lead = nameWords.isEmpty ? '' : nameWords.first; + final exact = (lead == first || lead == '${first}s' || lead == '${first}es' || first == '${lead}s' || first == '${lead}es') + ? 0 : lead.startsWith(first) ? 1 : 2; + final inName = ws.every((w) => nameWords.any((x) => x.startsWith(w))) ? 0 : 1; + final plain = nameWords.any(_plain.contains) ? 0 : 1; + return [inName, exact, plain, nameWords.length, ((r['rank'] as num) * 10).round() / 10, name.length, + _rank[r['source']] ?? 3]; + } + final sorted = rs.toList() + ..sort((a, b) { + final ka = key(a), kb = key(b); + for (var i = 0; i < ka.length; i++) { + final c = ka[i].compareTo(kb[i]); + if (c != 0) return c; + } + return 0; + }); + final seen = {}, out = []; + for (final r in sorted) { + if (seen.add((r['name'] as String).toLowerCase())) out.add(_food(r)); + if (out.length >= limit) break; + } + return out; + } +} + +// ---- My foods ------------------------------------------------------------------------------ + +Food myFood(Map r) { + final ps = (jsonDecode((r['portions'] as String?) ?? '[]') as List).cast>(); + return Food( + ref: 'my:${r['_u']}', kind: 'my', name: r['name'] as String, category: 'My foods', myUid: r['_u'] as String, + per100: {for (final c in foodCols) c: (r[c] as num?)?.toDouble()}, + portions: [for (final p in ps) Portion(p['label'] as String, (p['grams'] as num).toDouble())], + isMeal: r['recipe'] != null, + ); +} + +/// My foods (not deleted) with every word of q in the name; exact / starting first, then the most used. +List myFoods(SyncStore store, String q, {int limit = 8}) { + final ws = q.toLowerCase().split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList(); + final uses = {}; + for (final e in store.rows('food.entry')) { + final m = e['my_food_id']; + if (m is String) uses[m] = (uses[m] ?? 0) + 1; + } + final all = [ + for (final r in store.rows('food.food')) + if ((r['gone'] ?? 0) == 0 && ws.every((w) => (r['name'] as String).toLowerCase().contains(w))) r + ]; + final ql = q.trim().toLowerCase(); + all.sort((a, b) { + int k(Map r) { + final n = (r['name'] as String).toLowerCase(); + return n == ql ? 0 : n.startsWith(ql) ? 1 : 2; + } + final c = k(a).compareTo(k(b)); + return c != 0 ? c : (uses[b['_u']] ?? 0).compareTo(uses[a['_u']] ?? 0); + }); + return all.take(limit).map(myFood).toList(); +} + +Food? myFoodByUid(SyncStore store, String uid) { + final r = store.row('food.food', uid); + return r == null ? null : myFood(r); +} + +// ---- entries ------------------------------------------------------------------------------ + +class Entry { + Entry(this.row); + final Map row; + String get u => row['_u'] as String; + String get day => row['day'] as String; + String get meal => mealKeys.contains(row['meal']) ? row['meal'] as String : ''; + String get name => (row['name'] as String?) ?? ''; + double? n(String k) => (row[k] as num?)?.toDouble(); + double get kcal => n('kcal') ?? 0; + double? get amount => n('amount'); + String? get unit => row['unit'] as String?; + int? get foodId => (row['food_id'] as num?)?.toInt(); + String? get myFoodId => row['my_food_id'] is String ? row['my_food_id'] as String : null; + String get source => (row['source'] as String?) ?? ''; + String get portion => amount == null ? '' : '${_num(amount!)} ${unit ?? ''}'.trim(); + int get stamp => (row['_h'] as num?)?.toInt() ?? 0; +} + +String _num(double v) => v == v.roundToDouble() ? v.round().toString() : v.toStringAsFixed(v < 10 ? 2 : 1).replaceFirst(RegExp(r'0+$'), ''); + +List entriesOn(SyncStore store, String day) { + final es = [for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') = ?", args: [day])) Entry(r)]; + es.sort((a, b) { + final c = a.stamp.compareTo(b.stamp); + if (c != 0) return c; + return ((a.row['time'] as String?) ?? '').compareTo((b.row['time'] as String?) ?? ''); + }); + return es; +} + +/// {day: kcal} for the days in [a, z] (the week strip). +Map kcalByDay(SyncStore store, String a, String z) { + final out = {}; + for (final r in store.db.select( + "SELECT json_extract(data, '\$.day') AS dday, sum(json_extract(data, '\$.kcal')) AS k FROM rec " + "WHERE t = 'food.entry' AND json_extract(data, '\$.day') BETWEEN ? AND ? GROUP BY dday", [a, z])) { // not 'd': rec.d is the device + out[r['dday'] as String] = (r['k'] as num?)?.toDouble() ?? 0; + } + return out; +} + +/// Foods eaten before (db.foods): one per name — its latest entry — most eaten first; q anywhere in the name. +List<(Entry, int)> recentFoods(SyncStore store, String q, {int limit = 8}) { + final groups = {}; + for (final r in store.rows('food.entry')) { + final e = Entry(r); + if (!reuseSources.contains(e.source) || e.name.trim().isEmpty) continue; + final k = e.name.trim().toLowerCase(); + final g = groups[k]; + final newer = g == null || e.day.compareTo(g.$1.day) > 0 || (e.day == g.$1.day && e.stamp > g.$1.stamp); + groups[k] = (newer ? e : g.$1, (g?.$2 ?? 0) + 1); + } + final ql = q.trim().toLowerCase(); + final hits = groups.entries.where((e) => e.key.contains(ql)).map((e) => e.value).toList() + ..sort((a, b) { + final sa = a.$1.name.toLowerCase().startsWith(ql) ? 0 : 1, sb = b.$1.name.toLowerCase().startsWith(ql) ? 0 : 1; + if (sa != sb) return sa.compareTo(sb); + if (a.$2 != b.$2) return b.$2.compareTo(a.$2); + return b.$1.day.compareTo(a.$1.day); + }); + return hits.take(limit).toList(); +} + +// ---- products kept from the archive ("food.product", the dashboard's db.product) --------------- + +const tProduct = 'food.product'; +const offId = 20000000000000; // off.OFF_ID: + the barcode + +/// A product from the archive (or as kept: the same keys) → a Food (kind "off"). +Food productFood(Map d) { + final per = (d['per100'] as Map?)?.cast() ?? {}; + return Food( + ref: 'usda:${d['id']}', kind: 'off', name: d['name'] as String? ?? '?', category: d['category'] as String? ?? '', + brand: d['brand'] as String?, barcode: d['barcode'] as String?, nutriscore: d['nutriscore'] as String?, + nova: (d['nova'] as num?)?.toInt(), foodId: (d['id'] as num).toInt(), source: 'off', labels: d['labels'] as String? ?? '', + sugarsIn: d['sugars_in'] as String?, dairy: (d['dairy'] as num?)?.toInt(), addedSugar: (d['added_sugar'] as num?)?.toDouble(), + per100: {for (final c in foodCols) c: (per[c] as num?)?.toDouble()}, + portions: [ + for (final p in ((d['portions'] as List?) ?? []).cast()) + if ((p['grams'] as num?) != null) Portion('${p['label']}', (p['grams'] as num).toDouble()) + ], + ); +} + +Food? _kept(Map? row) { + try { + return row == null ? null : productFood(jsonDecode(row['data'] as String) as Map); + } catch (_) { + return null; + } +} + +Food? keptProduct(SyncStore store, int id) => _kept(store.row(tProduct, 'p:$id')); + +List keptByBarcode(SyncStore store, String code) => + [for (final r in store.rows(tProduct, where: "json_extract(data, '\$.barcode') = ?", args: [code])) ?_kept(r)]; + +/// Kept products whose name / brand has every word of [q] (folded: no diacritics). +List keptProducts(SyncStore store, String q, {required String Function(String) fold, int limit = 4}) { + final ws = fold(q).split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList(); + if (ws.isEmpty) return []; + return [ + for (final r in store.rows(tProduct)) + if (ws.every(fold('${r['name']} ${r['brand'] ?? ''}').contains)) ?_kept(r), + ].take(limit).toList(); +} + +/// Keep a product picked from the archive (the dashboard's db.save_product: checked, then stored and synced). +Food? keepProduct(SyncStore store, Map d) { + final id = (d['id'] as num?)?.toInt(); + final per = d['per100']; + if (id == null || id < offId || id >= offId * 1.5 || per is! Map || '${d['name'] ?? ''}'.trim().isEmpty) return null; + String? t(String k, int n) => d[k] == null ? null : '${d[k]}'.substring(0, min(n, '${d[k]}'.length)); + final v = { + for (final (k, n) in [('name', 120), ('category', 120), ('brand', 60), ('barcode', 14), ('countries', 200), ('nutriscore', 1), + ('allergens', 400), ('labels', 400), ('ingredients', 1600), ('sugars_in', 200)]) k: t(k, n), + 'id': id, + 'per100': {for (final c in foodCols) c: (per[c] as num?)?.toDouble()}, + 'portions': [ + for (final p in ((d['portions'] as List?) ?? []).cast().take(6)) + if ((p['grams'] as num? ?? 0) > 0 && (p['grams'] as num) <= 10000) {'label': '${p['label']}', 'grams': (p['grams'] as num).toDouble()} + ], + 'nova': [1, 2, 3, 4].contains(d['nova']) ? d['nova'] : null, + 'dairy': [0, 1].contains(d['dairy']) ? d['dairy'] : null, + 'added_sugar': (d['added_sugar'] as num?)?.toDouble(), + }; + final old = store.row(tProduct, 'p:$id'); + final data = jsonEncode(v); + if (old?['data'] != data) { + store.put(tProduct, 'p:$id', {'food_id': id, 'name': v['name'], 'brand': v['brand'] ?? '', 'barcode': v['barcode'], 'data': data, + 'added': old?['added'] ?? DateTime.now().toUtc().toIso8601String().substring(0, 19).replaceFirst('T', ' ')}); + } + return productFood(v); +} + +/// The food an entry was made from, if it still exists (database or My foods). +Food? foodOf(SyncStore store, FoodDb? fdb, Entry e) { + if (e.myFoodId != null) return myFoodByUid(store, e.myFoodId!); + if (e.foodId != null) return fdb?.food(e.foodId!); + return null; +} + +/// Save an entry made from [food] (amount × unit → grams → its nutrients) — new (u null) or changed. +/// The numbers are the entry's own, worked out now (later changes to the food don't touch it). +String? saveFromFood(SyncStore store, {String? u, required String day, required String meal, required Food food, + required double amount, required String unit, String note = ''}) { + final g = food.grams(amount, unit); + if (g == null) return "Can't tell the grams of that portion."; + final old = u == null ? null : store.row('food.entry', u); + store.put('food.entry', u ?? SyncStore.randomId(), { + 'micros': '{}', 'src_id': null, 'time': null, + ...?old, + 'day': day, 'meal': meal, 'name': food.name, ...food.nutrients(g), + 'amount': amount, 'unit': unit, 'grams': g, 'note': note, + 'food_id': food.foodId, 'my_food_id': food.myUid, 'source': old?['source'] ?? 'manual', + }); + return null; +} + +/// Save an entry without a food (its numbers typed, or copied from an older one and scaled by amount). +String? saveTotals(SyncStore store, {String? u, required String day, required String meal, required String name, + required Map values, double? amount, String? unit, Map? copyFrom, String note = ''}) { + if (name.trim().isEmpty) return 'What was it?'; + if (values['kcal'] == null) return 'How much energy? A guess is fine.'; + final old = u == null ? null : store.row('food.entry', u); + final extra = {}; + if (old == null && copyFrom != null && (copyFrom['kcal'] as num?) != null && (copyFrom['kcal'] as num) > 0) { + final f = values['kcal']! / (copyFrom['kcal'] as num); // db.save `from`: the other nutrients, scaled + for (final k in foodCols) { + if (!values.containsKey(k) && copyFrom[k] != null) extra[k] = ((copyFrom[k] as num) * f * 1000).round() / 1000; + } + } + store.put('food.entry', u ?? SyncStore.randomId(), { + 'micros': '{}', 'src_id': null, 'time': null, 'food_id': null, 'grams': null, 'my_food_id': null, + ...?old, ...extra, + 'day': day, 'meal': meal, 'name': name.trim(), ...values, 'amount': amount, 'unit': unit, 'note': note, + 'source': old?['source'] ?? 'manual', + }); + return null; +} + +/// Add an older entry again as it was (yesterday's +): a food entry is worked out again, else copied. +void addAgain(SyncStore store, FoodDb? fdb, Entry e, String day, String meal) { + final f = foodOf(store, fdb, e); + if (f != null && e.amount != null && e.unit != null && f.grams(e.amount!, e.unit!) != null) { + saveFromFood(store, day: day, meal: meal, food: f, amount: e.amount!, unit: e.unit!); + return; + } + saveTotals(store, day: day, meal: meal, name: e.name, amount: e.amount, unit: e.unit, + values: {for (final k in ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'sodium_mg']) k: e.n(k)}, + copyFrom: e.row); +} + +// ---- totals, targets, ring (views.py) ---------------------------------------------------------- + +Map totals(Iterable es) { + final out = {}; + for (final k in ['kcal', 'protein', 'carbs', 'sugar', 'fiber', 'fat', 'sat_fat', 'sodium_mg']) { + final vs = es.map((e) => e.n(k)).whereType().toList(); + out[k] = vs.isEmpty ? null : vs.reduce((a, b) => a + b); + } + out['kcal'] ??= 0; + return out; +} + +class Plan { + Plan(this.kcal, this.maint, this.basis, this.deficit, this.capped); + final int kcal; + final int? maint; + final String basis; + final int deficit; + final bool capped; +} + +/// views.plan: your usual day from Health (the Pi's energy summary: resting + walking + workouts, +/// averaged over 28 days with step data — at least 7) minus the weight goal; resting × 1.4 until then. +Plan plan(SyncStore store, FoodSettings s) { + final e = Summaries(store).meta('energy') ?? {}; + final b = BodyView(store, profileOf(store)); + final w = (e['weight'] as num?)?.toDouble() ?? b.weight; + final bmr = (e['bmr'] as num?)?.toDouble() ?? bmrMifflin(w, b.p.height, b.p.sex, b.age); + if (s.kcalTarget > 0) return Plan(s.kcalTarget, null, 'set by hand', 0, false); + final tdee = (e['tdee'] as num?)?.toInt(), days = (e['days'] as num?)?.toInt() ?? 0; + final int? maint; + final String basis; + if (tdee != null && days >= 7) { + maint = tdee; + basis = 'your average day in Health (resting + walking + workouts, $days days)'; + } else if (bmr != null) { + maint = (bmr * 1.4).round(); + basis = 'resting energy × 1.4 (not enough step data in Health yet)'; + } else { + return Plan(2000, null, 'no weight yet — 2000 kcal', 0, false); + } + if (w == null) return Plan(2000, maint, basis, 0, false); + var deficit = w * s.goalRate / 100 * 7700 / 7; + var capped = deficit > 1000; + deficit = min(deficit, 1000); + var kcal = maint - deficit; + final floor = b.p.sex == female ? 1200 : 1500; + if (kcal < floor) { + kcal = floor.toDouble(); + capped = true; + } + return Plan((kcal / 10).round() * 10, maint, basis, deficit.round(), capped); +} + +/// {key: (target, kind)} — kind goal / min / max (views.targets). +Map targets(SyncStore store, FoodSettings s) { + final kcal = plan(store, s).kcal.toDouble(); + final pct = [s.split.$1, s.split.$2, s.split.$3]; + return { + 'kcal': (kcal, 'goal'), + for (var i = 0; i < 3; i++) macros[i]: ((kcal * pct[i] / 100 / kcalPerG[macros[i]]!).roundToDouble(), 'goal'), + 'fiber': (s.fiberMin.toDouble(), 'min'), + 'sugar': (0, 'info'), // total sugar: shown, no limit (natural sugar counts too) + 'added_sugar': ((kcal * 0.10 / 4).roundToDouble(), 'max'), // WHO: added ("free") sugars under 10 % of the energy (sugar.dart) + 'sat_fat': ((kcal * 0.10 / 9).roundToDouble(), 'max'), + 'sodium_mg': (s.sodiumMax.toDouble(), 'max'), + }; +} + +String dayIso(DateTime d) => iso(d); +String num1(double v) => _num(v); + +// ---- My foods: save / delete (db.clean_food, save_food, delete_food) --------------------------- + +/// What the food editor edits per 100 g (db.FIELDS): key → (label, unit, max). +const foodFields = { + 'kcal': ('Energy', 'kcal', 10000.0), 'protein': ('Protein', 'g', 1000.0), 'carbs': ('Carbs', 'g', 1000.0), + 'sugar': ('of which sugar', 'g', 1000.0), 'fat': ('Fat', 'g', 1000.0), 'sat_fat': ('of which saturated', 'g', 1000.0), + 'fiber': ('Fibre', 'g', 500.0), 'sodium_mg': ('Sodium', 'mg', 50000.0), +}; + +/// New (uid null) or changed food: name unique among the live ones, energy required, portions need a +/// name + grams. The nutrients the editor doesn't show stay as they were. → (uid, error). +/// [sugarKind]: "Sugar counts as" (added / dairy / natural; '' = estimated; null = left as it is). +(String?, String?) saveMyFood(SyncStore store, {String? uid, required String name, required Map per100, + required List portions, String note = '', String? sugarKind}) { + final n = name.trim().split(RegExp(r'\s+')).join(' '); + if (n.isEmpty) return (null, 'Name the food.'); + if (per100['kcal'] == null) return (null, 'Energy per 100 g — from the label.'); + for (final e in per100.entries) { + final max = foodFields[e.key]?.$3; + if (e.value != null && max != null && (e.value! < 0 || e.value! > max)) return (null, '${foodFields[e.key]!.$1}: 0–${max.round()}.'); + } + for (final p in portions) { + if (p.label.trim().isEmpty || p.grams <= 0) return (null, 'A portion needs a name and its grams.'); + if (['g', 'ml'].contains(p.label.trim().toLowerCase())) return (null, 'g and ml are there already.'); + } + final clash = store.rows('food.food').any((r) => + (r['gone'] ?? 0) == 0 && r['_u'] != uid && (r['name'] as String).toLowerCase() == n.toLowerCase()); + if (clash) return (null, 'You already have a food with that name in My foods — pick it, or name this one differently.'); + final now = DateTime.now().toIso8601String().substring(0, 19); + final old = uid == null ? null : store.row('food.food', uid); + final u = uid ?? SyncStore.randomId(); + store.put('food.food', u, { + 'based_on': null, 'based_on_name': null, 'recipe': null, 'gone': 0, 'created': now, + for (final c in foodCols) c: null, + ...?old, + 'name': n, ...per100, 'note': note.trim(), 'updated': now, + if (sugarKind != null) 'sugar_kind': const ['added', 'dairy', 'natural'].contains(sugarKind) ? sugarKind : null, + 'portions': jsonEncode([for (final p in portions) {'label': p.label.trim().split(RegExp(r'\s+')).join(' '), 'grams': p.grams}]), + }); + return (u, null); +} + +/// Deleted foods are only hidden (gone): entries made from them keep pointing at them. +void deleteMyFood(SyncStore store, String uid) { + final r = store.row('food.food', uid); + if (r == null) return; + store.put('food.food', uid, {...r, 'gone': 1, 'updated': DateTime.now().toIso8601String().substring(0, 19)}); +} + +/// All My foods (not deleted), by name, with how often each was used. +List<(Map, int)> allMyFoods(SyncStore store) { + final uses = {}; + for (final e in store.rows('food.entry')) { + if (e['my_food_id'] is String) uses[e['my_food_id'] as String] = (uses[e['my_food_id'] as String] ?? 0) + 1; + } + final rs = store.rows('food.food').where((r) => (r['gone'] ?? 0) == 0).toList() + ..sort((a, b) => (a['name'] as String).toLowerCase().compareTo((b['name'] as String).toLowerCase())); + return [for (final r in rs) (r, uses[r['_u']] ?? 0)]; +} + +// ---- history (views.history) ------------------------------------------------------------------- + +/// {day: totals} for [a, z] (ISO days) — one pass over the entries. +Map> dayTotals(SyncStore store, String a, String z) { + final out = >{}; + for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') BETWEEN ? AND ?", args: [a, z])) { + final t = out.putIfAbsent(r['day'] as String, () => {}); + for (final k in ['kcal', 'protein', 'carbs', 'fat', 'fiber', 'sugar', 'sodium_mg', 'sat_fat']) { + t[k] = (t[k] ?? 0) + ((r[k] as num?)?.toDouble() ?? 0); + } + } + return out; +} + +/// The foods eaten most in [a, z]: (name, times, average kcal). +List<(String, int, double)> topFoods(SyncStore store, String a, String z, {int limit = 12}) { + final g = {}; + for (final r in store.rows('food.entry', where: "json_extract(data, '\$.day') BETWEEN ? AND ?", args: [a, z])) { + final name = (r['name'] as String?)?.trim() ?? ''; + if (name.isEmpty) continue; + final k = name.toLowerCase(), cur = g[k]; + final kcal = (r['kcal'] as num?)?.toDouble() ?? 0; + g[k] = cur == null ? (name, 1, kcal) : (cur.$1, cur.$2 + 1, cur.$3 + kcal); + } + final out = [for (final v in g.values) (v.$1, v.$2, v.$3 / v.$2)] + ..sort((x, y) => x.$2 != y.$2 ? y.$2.compareTo(x.$2) : (y.$3 * y.$2).compareTo(x.$3 * x.$2)); + return out.take(limit).toList(); +} + +// ---- meals (db.save_meal) ------------------------------------------------------------------------ + +const mealMax = 40; // ingredients + +/// One ingredient of a meal: a food + amount + unit, or (an entry logged without a food) its own numbers. +class Ingredient { + Ingredient.food(Food this.food, this.amount, this.unit) : fixed = null, name = food.name, grams = null; + Ingredient.fixed(Map this.fixed, this.name, this.amount, this.unit, this.grams) : food = null; + final Food? food; + final Map? fixed; + final String name; + double? amount, grams; + String? unit; + + double? get g => food != null ? (amount == null ? null : food!.grams(amount!, unit ?? 'g')) : grams; + Map get values => food != null ? (g == null ? {} : food!.nutrients(g!)) : fixed!; +} + +/// The meal's ingredients from its synced recipe (refs "usda:ID" / "my:~ID"). +List recipeOf(SyncStore store, FoodDb? fdb, Map row) { + final r = row['recipe'] is String ? jsonDecode(row['recipe'] as String) as Map : null; + final out = []; + for (final i in ((r?['ingredients'] as List?) ?? []).cast>()) { + final amount = (i['amount'] as num?)?.toDouble(), unit = i['unit'] as String?; + if (i['fixed'] is Map) { + out.add(Ingredient.fixed({for (final e in (i['fixed'] as Map).entries) e.key as String: (e.value as num?)?.toDouble()}, + (i['name'] as String?) ?? '', amount, unit, (i['grams'] as num?)?.toDouble())); + continue; + } + final ref = (i['food'] as String?) ?? ''; + final f = ref.startsWith('usda:') ? fdb?.food(int.parse(ref.substring(5))) + : ref.startsWith('my:') ? myFoodByUid(store, ref.substring(3).replaceFirst('~', '')) : null; + if (f != null) { + out.add(Ingredient.food(f, amount, unit)); + } else { + // gone: keep it as its own numbers so the meal still adds up (the web says "remove it and pick it again") + out.add(Ingredient.fixed({}, '${(i['name'] as String?) ?? '?'} (gone)', amount, unit, (i['grams'] as num?)?.toDouble())); + } + } + return out; +} + +double? doneGramsOf(Map row) { + final r = row['recipe'] is String ? jsonDecode(row['recipe'] as String) as Map : null; + return (r?['done_grams'] as num?)?.toDouble(); +} + +/// The meals inside a meal (by id) — a meal may hold another meal, not itself. +Set mealIds(SyncStore store, String uid, [int depth = 0]) { + final row = store.row('food.food', uid); + final r = row?['recipe'] is String ? jsonDecode(row!['recipe'] as String) as Map : null; + final out = {}; + for (final i in ((r?['ingredients'] as List?) ?? []).cast>()) { + final ref = (i['food'] as String?) ?? ''; + if (ref.startsWith('my:')) { + final id = ref.substring(3).replaceFirst('~', ''); + out.add(id); + if (depth < 4) out.addAll(mealIds(store, id, depth + 1)); + } + } + return out; +} + +/// Save a meal (new: uid null): its values per 100 g worked out from the ingredients as they are now; +/// portions get "whole meal" (its whole weight). → (uid, error). +(String?, String?) saveMeal(SyncStore store, {String? uid, required String name, required List ings, + double? doneGrams, required List portions, String note = ''}) { + if (name.trim().isEmpty) return (null, 'Name the meal.'); + if (ings.isEmpty) return (null, 'Add what goes into it.'); + if (ings.length > mealMax) return (null, 'At most $mealMax ingredients.'); + final tot = {for (final c in foodCols) c: null}; + var grams = 0.0; + final unweighed = [], recipe = >[]; + for (final i in ings) { + if (i.food != null) { + if (uid != null && i.food!.myUid != null && (i.food!.myUid == uid || mealIds(store, i.food!.myUid!).contains(uid))) { + return (null, '${i.name}: a meal can’t contain itself.'); + } + final g = i.g; + if (g == null || g <= 0) return (null, '${i.name}: how much of it — amount and unit?'); + i.food!.nutrients(g).forEach((c, v) { + if (v != null) tot[c] = (tot[c] ?? 0) + v; + }); + grams += g; + recipe.add({'food': i.food!.myUid != null ? 'my:~${i.food!.myUid}' : 'usda:${i.food!.foodId}', 'name': i.food!.name, + 'amount': i.amount, 'unit': i.unit ?? 'g', 'grams': (g * 100).round() / 100}); + } else { + if (i.fixed!['kcal'] == null) return (null, '${i.name}: no energy on that one.'); + i.fixed!.forEach((c, v) { + if (v != null && tot.containsKey(c)) tot[c] = (tot[c] ?? 0) + v; + }); + if (i.grams != null && i.grams! > 0) { + grams += i.grams!; + } else { + unweighed.add(i.name); + } + recipe.add({'fixed': i.fixed, 'name': i.name, 'amount': i.amount, 'unit': i.unit, 'grams': i.grams}); + } + } + final weight = doneGrams ?? grams; + if (unweighed.isNotEmpty && doneGrams == null) { + return (null, 'No weight for ${unweighed.take(3).join(', ')}${unweighed.length > 3 ? ' …' : ''} — weigh the meal (or guess) and enter it as the weight when done.'); + } + if (weight <= 0) return (null, 'How much does it weigh?'); + final per100 = {for (final e in tot.entries) e.key: e.value == null ? null : (e.value! * 100 / weight * 1000).round() / 1000}; + final (u, err) = saveMyFood(store, uid: uid, name: name, per100: per100, + portions: [...portions.where((p) => p.label.trim().toLowerCase() != 'whole meal'), Portion('whole meal', (weight * 10).round() / 10)], + note: note); + if (err != null) return (null, err); + final row = store.row('food.food', u!)!; + store.put('food.food', u, {...row, 'recipe': jsonEncode({'ingredients': recipe, 'done_grams': doneGrams})}); + return (u, null); +} + +/// An entry dragged into another meal (db.move: only the meal changes). +void moveEntry(SyncStore store, String u, String meal) { + final r = store.row('food.entry', u); + if (r != null && r['meal'] != meal) store.put('food.entry', u, {...r, 'meal': meal}); +} diff --git a/app/lib/health/food_page.dart b/app/lib/health/food_page.dart new file mode 100644 index 0000000..cc51bf4 --- /dev/null +++ b/app/lib/health/food_page.dart @@ -0,0 +1,397 @@ +// Food: one day — ‹ day ›, the week strip, the energy ring (eaten ÷ target, split by where the energy +// came from: protein / carbs / fat) + the nutrient bars, and the four meals (tap a food = edit it, +// long-press = drag it to another meal, + = add to that meal), Make a meal. Days up to 60 ahead for +// planning, like the web page. +import 'dart:math'; + +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'cycle_model.dart' show plus, today, daysBetween; +import 'food_model.dart'; +import 'food_sheet.dart'; +import 'meal_builder.dart'; +import 'summaries.dart'; +import 'sugar.dart'; + +const proteinC = Color(0xFF5CC8FF), carbsC = Color(0xFFFFB33A), fatC = Color(0xFFC792EA); +const macroColors = {'protein': proteinC, 'carbs': carbsC, 'fat': fatC}; +const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; +const _dow = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; +const ahead = 60; + +/// P / C / F as coloured dots + grams (the web page's macDots). +Widget macroDots(Map t, {double size = 12.5}) => Row(mainAxisSize: MainAxisSize.min, children: [ + for (final m in macros) ...[ + Icon(Icons.circle, size: 7, color: macroColors[m]), + Padding(padding: const EdgeInsets.only(left: 2, right: 7), + child: Text('${(t[m] ?? 0).round()}', style: TextStyle(fontSize: size, color: muted))), + ], + ]); + +class FoodPage extends StatefulWidget { + const FoodPage({super.key, required this.sync}); + final SyncService sync; + @override + State createState() => _FoodPageState(); +} + +class _FoodPageState extends State { + DateTime d = today(); + FoodDb? fdb; + FoodSettings get s => FoodSettings.of(widget.sync.store); // Settings ▸ Food on the dashboard + + @override + void initState() { + super.initState(); + FoodDb.open().then((x) => mounted ? setState(() => fdb = x) : null); + } + + String _title() { + final n = daysBetween(today(), d); + final name = n == 0 ? 'Today' : n == -1 ? 'Yesterday' : n == 1 ? 'Tomorrow' : _dow[d.weekday - 1]; + return '$name · ${d.day} ${_mon[d.month - 1]}${d.year != today().year ? ' ${d.year}' : ''}'; + } + + Future _sheet({Entry? e, String? meal}) => showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => FoodSheet(sync: widget.sync, fdb: fdb, day: dayIso(d), meal: meal ?? e?.meal ?? _mealNow(), entry: e), + ); + + Future _makeMeal(List es) async { + final picked = es.isEmpty ? [] : await pickEntries(context, es); + if (picked == null || !mounted) return; + Navigator.push(context, MaterialPageRoute(builder: (_) => MealBuilder(sync: widget.sync, fdb: fdb, fromEntries: picked))); + } + + static String _mealNow() { + final h = DateTime.now().hour; + return h < 10 ? 'breakfast' : h < 15 ? 'lunch' : h < 21 ? 'dinner' : 'snack'; + } + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: widget.sync, + builder: (context, _) { + final store = widget.sync.store; + final es = entriesOn(store, dayIso(d)); + final tg = targets(store, s); + return LayoutBuilder(builder: (context, box) { + final wide = box.maxWidth >= 700; + final head = [_nav(), const SizedBox(height: 6), _week(tg['kcal']!.$1), const SizedBox(height: 10), + FoodDayCard(sync: widget.sync, day: d, fdb: fdb)]; + final meals = [ + for (final m in [...mealKeys, if (es.any((e) => e.meal == '')) '']) + Padding(padding: const EdgeInsets.only(bottom: 10), child: _meal(m, es.where((e) => e.meal == m).toList())), + OutlinedButton.icon( + onPressed: () => _makeMeal(es), + icon: const Icon(Icons.soup_kitchen_outlined), + label: Text(es.isEmpty ? 'Make a meal' : 'Make a meal (from this day’s entries)'), + ), + ]; + return ListView(padding: const EdgeInsets.fromLTRB(12, 10, 12, 24), children: [ + if (wide) + Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Expanded(child: Column(children: head)), + const SizedBox(width: 12), + Expanded(child: Column(children: meals)), + ]) + else ...[...head, const SizedBox(height: 10), ...meals], + ]); + }); + }, + ); + + Widget _nav() => Row(children: [ + IconButton(onPressed: () => setState(() => d = plus(d, -1)), icon: const Icon(Icons.chevron_left)), + Expanded( + child: GestureDetector( + onTap: () => setState(() => d = today()), + child: Text(_title(), textAlign: TextAlign.center, + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)), + ), + ), + IconButton( + onPressed: daysBetween(today(), d) < ahead ? () => setState(() => d = plus(d, 1)) : null, + icon: const Icon(Icons.chevron_right)), + ]); + + Widget _week(double target) { + final mon = plus(d, -(d.weekday - 1)); + final k = kcalByDay(widget.sync.store, dayIso(mon), dayIso(plus(mon, 6))); + return Row(children: [ + for (var i = 0; i < 7; i++) + () { + final x = plus(mon, i), kc = k[dayIso(x)]; + final h = min(1.15, (kc ?? 0) / target); + final sel = x == d, over = kc != null && kc > target * 1.05; + return Expanded( + child: GestureDetector( + onTap: () => setState(() => d = x), + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 2), + padding: const EdgeInsets.symmetric(vertical: 5), + decoration: BoxDecoration(color: sel ? card2 : null, borderRadius: BorderRadius.circular(8)), + child: Column(children: [ + Text(_dow[i].substring(0, 2), style: TextStyle(fontSize: 11.5, color: x == today() ? accent : muted)), + const SizedBox(height: 3), + Container( + width: 12, height: 32, alignment: Alignment.bottomCenter, + decoration: BoxDecoration(color: card2, borderRadius: BorderRadius.circular(3)), + child: FractionallySizedBox(heightFactor: h / 1.15, + child: Container(decoration: BoxDecoration(color: over ? bad : good, borderRadius: BorderRadius.circular(3)))), + ), + const SizedBox(height: 2), + Text(kc == null ? '' : '${kc.round()}', style: const TextStyle(fontSize: 10.5, color: muted)), + ]), + ), + ), + ); + }(), + ]); + } + + Widget _meal(String m, List es) { + final t = totals(es); + // a long-pressed food can be dropped on another meal's card (db.move: only the meal changes) + return DragTarget( + onWillAcceptWithDetails: (d) => m != '' && d.data.meal != m, + onAcceptWithDetails: (d) { + moveEntry(widget.sync.store, d.data.u, m); + widget.sync.changed(); + }, + builder: (context, cand, _) => Card( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12), + side: cand.isNotEmpty ? const BorderSide(color: accent, width: 2) : BorderSide.none), + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 6, 6, 8), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + Text(mealLabels[m]!, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + const SizedBox(width: 10), + if (es.isNotEmpty) Text('${(t['kcal'] ?? 0).round()} kcal', style: const TextStyle(color: accent)), + const Spacer(), + if (es.isNotEmpty) macroDots(t), + if (m != '') + IconButton(tooltip: 'Add to ${mealLabels[m]!.toLowerCase()}', onPressed: () => _sheet(meal: m), + icon: const Icon(Icons.add_circle_outline, color: accent)), + ]), + if (es.isEmpty && m != '') + InkWell( + onTap: () => _sheet(meal: m), + child: const Padding(padding: EdgeInsets.symmetric(vertical: 6), child: Text('Nothing yet — add', style: TextStyle(color: muted))), + ), + for (final e in es) + LongPressDraggable( + data: e, + feedback: Material( + color: card2, + borderRadius: BorderRadius.circular(10), + elevation: 6, + child: Padding(padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + child: Text('${e.name} · ${e.kcal.round()} kcal', style: const TextStyle(color: Colors.white))), + ), + childWhenDragging: Opacity(opacity: 0.35, child: _row(e)), + child: InkWell(onTap: () => _sheet(e: e), child: _row(e)), + ), + ]), + ), + ), + ); + } + + Widget _row(Entry e) => Padding( + padding: const EdgeInsets.fromLTRB(0, 6, 8, 6), + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(e.name), + Row(children: [ + if (e.portion.isNotEmpty) Padding(padding: const EdgeInsets.only(right: 8), + child: Text(e.portion, style: const TextStyle(color: muted, fontSize: 12.5))), + macroDots({for (final k in macros) k: e.n(k)}, size: 11.5), + ]), + ])), + Text('${e.kcal.round()}', style: const TextStyle(fontWeight: FontWeight.bold)), + ]), + ); +} + +/// The energy ring (views.ring): as far round as eaten ÷ target, split by the macros' share of +/// the energy; past 105 % the track turns red. +/// The day's energy ring (eaten ÷ target, split by macro), what's left, burned (Health) and the nutrient +/// bars — the Food page's top card, also on Health ▸ Overview. +class FoodDayCard extends StatelessWidget { + const FoodDayCard({super.key, required this.sync, required this.day, this.fdb}); + final SyncService sync; + final DateTime day; + final FoodDb? fdb; + FoodSettings get s => FoodSettings.of(sync.store); + + @override + Widget build(BuildContext context) { + final store = sync.store; + final es = entriesOn(store, dayIso(day)); + final t = totals(es); + if (fdb != null) { + final fs = AddedSugar(store, fdb); + t['added_sugar'] = es.fold(0, (a, e) => a + fs.entry(e)); + } + return _ringCard(t, targets(store, s), plan(store, s), es.isNotEmpty); + } + + Widget _ringCard(Map t, Map tg, Plan p, bool any) { + final target = tg['kcal']!.$1, kcal = t['kcal'] ?? 0, left = target - kcal; + final rows = [('protein', 'Protein', 'g'), ('carbs', 'Carbs', 'g'), ('fat', 'Fat', 'g'), ('fiber', 'Fibre', 'g'), + ('sugar', 'Sugar', 'g'), if (t['added_sugar'] != null) ('added_sugar', 'Added sugar ≈', 'g'), ('sat_fat', 'Saturated fat', 'g'), + ('sodium_mg', 'Sodium', 'mg')]; + return Card( + child: Padding( + padding: const EdgeInsets.all(14), + child: Column(children: [ + Row(children: [ + Tooltip( + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 8), + message: 'Target ${target.round()} kcal: ${p.basis}' + '${p.maint != null ? ' = ${p.maint} kcal, minus ${p.deficit} to lose 0.5 % a week' : ''}' + '${p.capped ? ' (limited)' : ''}.', + child: SizedBox( + width: 120, height: 120, + child: CustomPaint( + painter: _Ring(t, target), + child: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [ + Text('${kcal.round()}', style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), + Text('of ${target.round()} kcal', style: const TextStyle(fontSize: 11.5, color: muted)), + ])), + ), + ), + ), + const SizedBox(width: 16), + Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(left >= 0 ? '${left.round()} left' : '${(-left).round()} over', + style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: kcal > target * 1.05 ? bad : null)), + const SizedBox(height: 6), + if (any) macroDots(t, size: 14) else const Text('Nothing logged yet', style: TextStyle(color: muted)), + ..._burned(kcal, any), + ])), + ]), + const SizedBox(height: 12), + for (final (k, label, unit) in rows) _bar(label, unit, t[k], tg[k]!, macroColors[k]), + ]), + ), + ); + } + + /// The day's activity from Health (the Pi's summary): "Burned ≈ N kcal" (breakdown on tap) and + /// eaten − burned (only when something's logged) — past days and today ("so far"). + List _burned(double kcal, bool any) { + if (day.isAfter(today())) return []; + final e = (Summaries(sync.store).day(dayIso(day))?['energy'] as Map?)?.cast(); + if (e == null) return []; + final total = (e['total'] as num).toDouble(), bal = kcal - total; + return [ + const SizedBox(height: 8), + Tooltip( + triggerMode: TooltipTriggerMode.tap, + message: 'Resting ${e['bmr']} + walking ${e['walk']} + workouts ${e['workouts']} kcal — estimated from your band', + child: Text('Burned ≈ ${total.round()} kcal${day == today() ? ' so far' : ''}', style: const TextStyle(color: muted)), + ), + if (any) + Text('eaten − burned ${bal >= 0 ? '+' : '−'}${bal.abs().round()}', + style: TextStyle(color: bal <= 0 ? good : accent, fontWeight: FontWeight.bold)), + ]; + } + + Widget _bar(String label, String unit, double? v, (double, String) tg, Color? c) { + final (target, kind) = tg; + if (kind == 'info') { // total sugar: the value, no limit + return Tooltip( + triggerMode: TooltipTriggerMode.tap, + message: 'All sugar, natural sugar included (fruit, vegetables, milk) — the limit is on added sugar, below.', + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 3.5), + child: Row(children: [ + SizedBox(width: 104, child: Text(label, style: const TextStyle(color: muted, fontSize: 13.5))), + const Spacer(), + Text('${v == null ? '—' : v.round()} $unit', style: const TextStyle(fontSize: 12.5)), + ]), + ), + ); + } + final frac = target > 0 ? (v ?? 0) / target : 0.0; + final over = kind == 'max' && (v ?? 0) > target, ok = kind == 'min' && (v ?? 0) >= target, + high = kind == 'goal' && (v ?? 0) > target * 1.15; + final color = over || high ? bad : ok ? good : (c ?? muted); + final word = kind == 'min' ? 'at least ' : kind == 'max' ? 'at most ' : ''; + final row = Padding( + padding: const EdgeInsets.symmetric(vertical: 3.5), + child: Row(children: [ + SizedBox(width: 104, child: Text(label, style: const TextStyle(color: muted, fontSize: 13.5))), + Expanded( + child: ClipRRect( + borderRadius: BorderRadius.circular(4), + child: LinearProgressIndicator(value: min(1.0, frac), minHeight: 8, backgroundColor: card2, color: color), + ), + ), + SizedBox( + width: 118, + child: Text('${v == null ? '—' : v.round()} / $word${target.round()} $unit', textAlign: TextAlign.right, + style: TextStyle(fontSize: 12.5, color: over || high ? bad : null)), + ), + ]), + ); + if (label != 'Added sugar ≈') return row; + return Tooltip( + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 8), + message: 'Added sugar, estimated: sugar, honey, syrups added to food, plus fruit juice (WHO\'s "free sugars") — ' + 'not the sugar inside whole fruit, ' + 'vegetables and plain milk / yogurt. WHO: under 10 % of the energy.', + child: row, + ); + } + +} + +class _Ring extends CustomPainter { + _Ring(this.t, this.target); + final Map t; + final double target; + + @override + void paint(Canvas c, Size size) { + final r = size.width / 2 - 8, o = Offset(size.width / 2, size.height / 2); + final kcal = t['kcal'] ?? 0; + final over = kcal > target * 1.05; + // rounded ends like the web page's ring (stroke-linecap: round) + Paint p(Color col, {StrokeCap cap = StrokeCap.round}) => + Paint()..color = col..style = PaintingStyle.stroke..strokeWidth = 11..strokeCap = cap; + c.drawCircle(o, r, p(over ? bad.withValues(alpha: .45) : card2, cap: StrokeCap.butt)); + final frac = target > 0 ? min(1.0, kcal / target) : 0.0; + if (frac == 0) return; + final energy = {for (final m in macros) m: (t[m] ?? 0) * kcalPerG[m]!}; + final known = energy.values.reduce((a, b) => a + b); + final rect = Rect.fromCircle(center: o, radius: r); + var at = -pi / 2; + if (known == 0) { + c.drawArc(rect, at, frac * 2 * pi, false, p(accent)); + return; + } + // thin separators between the macros only (views.ring's gap: 0.006 of the circle each side), none at 12 o'clock + final gap = frac > 0.05 ? 0.006 * 2 * pi : 0.0; + final parts = [for (final m in macros) if (energy[m]! > 0) m]; + for (var i = 0; i < parts.length; i++) { + final sweep = frac * energy[parts[i]]! / known * 2 * pi; + final g0 = i == 0 ? 0.0 : gap, g1 = i == parts.length - 1 ? 0.0 : gap; + if (sweep > g0 + g1) c.drawArc(rect, at + g0, sweep - g0 - g1, false, p(macroColors[parts[i]]!)); + at += sweep; + } + } + + @override + bool shouldRepaint(covariant _Ring old) => true; +} + diff --git a/app/lib/health/food_sheet.dart b/app/lib/health/food_sheet.dart new file mode 100644 index 0000000..3850734 --- /dev/null +++ b/app/lib/health/food_sheet.dart @@ -0,0 +1,420 @@ +// Adding / editing a food entry (the web page's inline editor as a bottom sheet, lifted by the +// keyboard). Modes: +// search — the box: empty = yesterday's foods (this meal first; + adds one as it was, a tap picks +// it to change the portion); typed = My foods · Eaten before · Food database · Products +// (+ ones kept from the archive); a barcode (typed or scanned — the camera button) = that +// product; "Search all products…" = the archive on the sync server (food_archive.dart) +// food — the picked food: amount + unit (g, ml, its portions, tbsp / tsp), the numbers live, meal +// totals — an entry without a food (Lifesum imports, estimates): name, kcal / P / C / F +// Editing an entry opens it in food or totals mode; Delete = tap twice. +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'cycle_model.dart' show parseDay, plus; +import 'food_archive.dart'; +import 'food_model.dart'; +import 'food_page.dart' show macroDots; +import 'my_foods.dart'; +import 'sugar.dart' show fold; + +class FoodSheet extends StatefulWidget { + const FoodSheet({super.key, required this.sync, required this.fdb, required this.day, required this.meal, this.entry}); + final SyncService sync; + final FoodDb? fdb; + final String day, meal; + final Entry? entry; + @override + State createState() => _FoodSheetState(); +} + +class _FoodSheetState extends State { + late String meal = widget.meal.isEmpty ? 'snack' : widget.meal; + String mode = 'search'; + final q = TextEditingController(); + Food? food; + final amount = TextEditingController(), name = TextEditingController(), unitCtl = TextEditingController(); + String unit = 'g'; + final totalsCtl = {for (final k in ['kcal', 'protein', 'carbs', 'fat']) k: TextEditingController()}; + Map? copyFrom; // totals mode from an older entry: its other nutrients come along, scaled + String? error; + bool armed = false; + + @override + void initState() { + super.initState(); + final e = widget.entry; + if (e != null) { + final f = foodOf(widget.sync.store, widget.fdb, e); + if (f != null && e.amount != null && e.unit != null && f.units.contains(e.unit)) { + _pick(f, e.amount!, e.unit!); + } else { + _totals(e); + } + } + } + + void _pick(Food f, [double? a, String? u]) => setState(() { + food = f; + mode = 'food'; + unit = u ?? (f.portions.isNotEmpty ? f.portions.first.label : 'g'); + amount.text = num1(a ?? (unit == 'g' ? 100 : 1)); + error = null; + }); + + void _totals(Entry e, {bool copy = false}) => setState(() { + mode = 'totals'; + name.text = e.name; + amount.text = e.amount == null ? '' : num1(e.amount!); + unit = e.unit ?? ''; + unitCtl.text = unit; + for (final k in totalsCtl.keys) { + totalsCtl[k]!.text = e.n(k) == null ? '' : num1(e.n(k)!); + } + copyFrom = copy ? e.row : null; + error = null; + }); + + void _done() { + widget.sync.changed(); + Navigator.pop(context); + } + + void _save() { + final store = widget.sync.store; + final u = widget.entry?.u; + String? err; + if (mode == 'food') { + final a = double.tryParse(amount.text.trim().replaceAll(',', '.')); + if (a == null || a <= 0) return setState(() => error = 'How much?'); + err = saveFromFood(store, u: u, day: widget.entry?.day ?? widget.day, meal: meal, food: food!, amount: a, unit: unit, + note: (widget.entry?.row['note'] as String?) ?? ''); + } else { + double? v(String k) => double.tryParse(totalsCtl[k]!.text.trim().replaceAll(',', '.')); + err = saveTotals(store, u: u, day: widget.entry?.day ?? widget.day, meal: meal, name: name.text, + values: {for (final k in totalsCtl.keys) k: v(k)}, + amount: double.tryParse(amount.text.trim().replaceAll(',', '.')), unit: unit.isEmpty ? null : unit, + copyFrom: copyFrom, note: (widget.entry?.row['note'] as String?) ?? ''); + } + if (err != null) return setState(() => error = err); + _done(); + } + + @override + Widget build(BuildContext context) { + final h = MediaQuery.of(context).size.height; + return Padding( + padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), + child: ConstrainedBox( + constraints: BoxConstraints(maxHeight: h * 0.8), + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 12), + child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + Expanded(child: Text(widget.entry == null ? 'Add to ${mealLabels[meal]!.toLowerCase()}' : 'Edit', + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent))), + DropdownButton( + value: meal, + underline: const SizedBox(), + dropdownColor: card2, + items: [for (final m in mealKeys) DropdownMenuItem(value: m, child: Text(mealLabels[m]!))], + onChanged: (m) => setState(() => meal = m!), + ), + ]), + if (mode == 'search') Flexible(child: _search()) else if (mode == 'food') _foodForm() else _totalsForm(), + ]), + ), + ), + ); + } + + // ---- search + Widget _search() { + final store = widget.sync.store; + final text = q.text.trim(); + final sections = <(String, List)>[]; + if (text.isEmpty) { + final yday = parseDay(widget.day); + final ys = entriesOn(store, dayIso(plus(yday, -1))).where((e) => e.meal.isNotEmpty).toList(); + final here = entriesOn(store, widget.day); + bool already(Entry y) => here.any((e) => e.meal == meal && e.name == y.name && e.amount == y.amount && e.unit == y.unit); + final mine = ys.where((e) => e.meal == meal).toList(), rest = ys.where((e) => e.meal != meal).toList(); + if (mine.isNotEmpty) sections.add(('Yesterday · ${mealLabels[meal]!.toLowerCase()}', [for (final e in mine) _yday(e, already(e))])); + if (rest.isNotEmpty) sections.add(('Yesterday · other meals', [for (final e in rest) _yday(e, already(e))])); + final recent = recentFoods(store, '', limit: 8); + if (recent.isNotEmpty) sections.add(('Eaten often', [for (final (e, n) in recent) _recent(e, n)])); + } else if (RegExp(r'^\d{8,14}$').hasMatch(text)) { // a barcode: that product, here or kept + final found = widget.fdb?.byBarcode(text) ?? keptByBarcode(store, text); + sections.add(('Barcode $text', [ + for (final f in found) _foodTile(f), + if (found.isEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6), + child: Text('Not in the food database here — look it up in all products:', style: TextStyle(color: muted))), + ])); + } else { + final my = myFoods(store, text); + final recent = recentFoods(store, text, limit: 5); + final db = widget.fdb?.search(text, limit: 14) ?? []; + if (my.isNotEmpty) sections.add(('My foods', [for (final f in my) _foodTile(f)])); + if (recent.isNotEmpty) sections.add(('Eaten before', [for (final (e, n) in recent) _recent(e, n)])); + final kept = keptProducts(store, text, fold: fold); + final usda = db.where((f) => f.kind == 'usda').take(8).toList(), + off = [...kept, ...db.where((f) => f.kind == 'off' && !kept.any((k) => k.foodId == f.foodId))].take(6).toList(); + if (usda.isNotEmpty) sections.add(('Food database', [for (final f in usda) _foodTile(f)])); + if (off.isNotEmpty) sections.add(('Products', [for (final f in off) _foodTile(f)])); + if (widget.fdb == null) sections.add(('', [const Text('Loading the food database…', style: TextStyle(color: muted))])); + } + return Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + TextField( + controller: q, + autofocus: true, + decoration: InputDecoration( + prefixIcon: const Icon(Icons.search), + hintText: 'Search foods…', + suffixIcon: IconButton(tooltip: 'Scan a barcode', icon: const Icon(Icons.qr_code_scanner), onPressed: _scan), + ), + onChanged: (_) => setState(() {}), + ), + const SizedBox(height: 6), + Flexible( + child: ListView(shrinkWrap: true, children: [ + for (final (title, items) in sections) ...[ + if (title.isNotEmpty) + Padding(padding: const EdgeInsets.only(top: 10, bottom: 2), + child: Text(title, style: const TextStyle(color: muted, fontSize: 12.5, fontWeight: FontWeight.bold))), + ...items, + ], + if (sections.isEmpty && text.isNotEmpty) const Padding(padding: EdgeInsets.all(12), + child: Text('Nothing found', style: TextStyle(color: muted))), + if (text.length >= 3) + TextButton.icon( + onPressed: () => _archive(text), + icon: const Icon(Icons.travel_explore), + label: Text(RegExp(r'^\d{8,14}$').hasMatch(text) ? 'Look up barcode $text in all products' : 'Search all products for “$text”'), + ), + if (text.isNotEmpty) + TextButton.icon( + onPressed: () async { + final uid = await openFoodEditor(context, widget.sync, name: text); + final f = uid == null ? null : myFoodByUid(widget.sync.store, uid); + if (f != null && mounted) _pick(f); + }, + icon: const Icon(Icons.add), + label: Text('New food “$text” (from its label)'), + ), + if (text.isNotEmpty) + TextButton.icon( + onPressed: () => setState(() { + mode = 'totals'; + name.text = text; + amount.text = ''; + unit = ''; + unitCtl.text = ''; + copyFrom = null; + }), + icon: const Icon(Icons.edit_note), + label: Text('“$text” with my own numbers'), + ), + ]), + ), + ]); + } + + /// The archive (every Open Food Facts product) → the one picked, kept, then as any food. + Future _archive(String text) async { + final f = await openArchive(context, widget.sync, widget.fdb, text); + if (f != null && mounted) _pick(f); + } + + /// The camera → a barcode: its product here, else straight to the archive. + Future _scan() async { + final code = await scanBarcode(context); + if (code == null || !mounted) return; + final here = widget.fdb?.byBarcode(code) ?? keptByBarcode(widget.sync.store, code); + if (here.length == 1) return _pick(here.first); + setState(() => q.text = code); + if (here.isEmpty) await _archive(code); + } + + Widget _yday(Entry e, bool done) => ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + title: Text(e.name), + subtitle: Text('${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal', style: const TextStyle(color: muted)), + onTap: () => _fromEntry(e), + trailing: done + ? const Icon(Icons.check, color: good) + : IconButton( + tooltip: 'Add as it was', + icon: const Icon(Icons.add_circle, color: accent), + onPressed: () { + addAgain(widget.sync.store, widget.fdb, e, widget.day, meal); + widget.sync.changed(); + setState(() {}); + }, + ), + ); + + Widget _recent(Entry e, int n) => ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + title: Text(e.name), + subtitle: Text('${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal · $n×', style: const TextStyle(color: muted)), + onTap: () => _fromEntry(e), + ); + + /// An older entry picked: its food with its portion, else its numbers (scaled with the amount). + void _fromEntry(Entry e) { + final f = foodOf(widget.sync.store, widget.fdb, e); + if (f != null && e.amount != null && e.unit != null && f.units.contains(e.unit)) { + _pick(f, e.amount!, e.unit!); + } else { + _totals(e, copy: true); + } + } + + Widget _foodTile(Food f) { + final k = f.per100['kcal']; + final sub = [ + if (f.kind == 'off') f.brand ?? '' else if (f.kind != 'my') f.category, + if (k != null) '${k.round()} kcal / 100 g', + if (f.isMeal) 'meal', + ].where((x) => x.isNotEmpty).join(' · '); + return ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + title: Text(f.name), + subtitle: Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted)), + trailing: f.nutriscore == null ? null : _score(f.nutriscore!), + onTap: () => _pick(f), + ); + } + + static Widget _score(String s) { + const colors = {'a': Color(0xFF1E8F4E), 'b': Color(0xFF7AC547), 'c': Color(0xFFF2C40F), 'd': Color(0xFFEE8100), 'e': Color(0xFFE63E11)}; + return Container( + padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 2), + decoration: BoxDecoration(color: colors[s] ?? card2, borderRadius: BorderRadius.circular(5)), + child: Text(s.toUpperCase(), style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold)), + ); + } + + // ---- food: amount + unit + Widget _foodForm() { + final f = food!; + final a = double.tryParse(amount.text.trim().replaceAll(',', '.')); + final g = a == null ? null : f.grams(a, unit); + final nut = g == null ? null : f.nutrients(g); + final source = switch (f.kind) { + 'my' => f.isMeal ? 'My meal' : 'My food', + 'off' => 'Product (Open Food Facts)${f.brand != null ? ' · ${f.brand}' : ''}', + _ => 'Food database (USDA)', + }; + return Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + InkWell( + onTap: () => setState(() => mode = 'search'), + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row(children: [ + Expanded(child: Text(f.name, style: const TextStyle(fontSize: 16.5, fontWeight: FontWeight.bold))), + const Icon(Icons.search, color: muted, size: 18), + ]), + ), + ), + Text(source, style: const TextStyle(color: muted, fontSize: 12.5)), + const SizedBox(height: 10), + Row(children: [ + SizedBox( + width: 100, + child: TextField( + controller: amount, + autofocus: widget.entry == null, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(labelText: 'Amount'), + onChanged: (_) => setState(() {}), + onSubmitted: (_) => _save(), + ), + ), + const SizedBox(width: 12), + Expanded( + child: DropdownButtonFormField( + initialValue: f.units.contains(unit) ? unit : 'g', + isExpanded: true, + dropdownColor: card2, + decoration: const InputDecoration(labelText: 'Unit'), + items: [ + for (final u in f.units) + DropdownMenuItem(value: u, child: Text(f.portions.any((p) => p.label == u) + ? '$u (${num1(f.portions.firstWhere((p) => p.label == u).grams)} g)' : u, overflow: TextOverflow.ellipsis)), + ], + onChanged: (u) => setState(() => unit = u!), + ), + ), + ]), + const SizedBox(height: 10), + if (nut != null) + Row(children: [ + Text('${(nut['kcal'] ?? 0).round()} kcal', style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16)), + Text(' · ${num1(g!)} g · ', style: const TextStyle(color: muted)), + macroDots(nut), + ]), + if (nut != null && (nut['fiber'] != null || nut['sugar'] != null)) + Padding( + padding: const EdgeInsets.only(top: 3), + child: Text([ + if (nut['fiber'] != null) 'fibre ${num1(nut['fiber']!)} g', + if (nut['sugar'] != null) 'sugar ${num1(nut['sugar']!)} g', + if (nut['sat_fat'] != null) 'sat. fat ${num1(nut['sat_fat']!)} g', + if (nut['sodium_mg'] != null) 'sodium ${nut['sodium_mg']!.round()} mg', + ].join(' · '), style: const TextStyle(color: muted, fontSize: 12.5)), + ), + _actions(), + ]); + } + + // ---- totals: an entry without a food + Widget _totalsForm() => Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + TextField(controller: name, decoration: const InputDecoration(labelText: 'What was it?')), + Row(children: [ + SizedBox(width: 100, child: TextField(controller: amount, keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(labelText: 'Amount'))), + const SizedBox(width: 12), + Expanded(child: TextField(controller: unitCtl, onChanged: (v) => unit = v.trim(), + decoration: const InputDecoration(labelText: 'Unit (g, pcs, bowl…)'))), + ]), + Row(children: [ + for (final (k, l) in [('kcal', 'kcal'), ('protein', 'Protein g'), ('carbs', 'Carbs g'), ('fat', 'Fat g')]) + Expanded(child: Padding( + padding: const EdgeInsets.only(right: 8), + child: TextField(controller: totalsCtl[k], keyboardType: const TextInputType.numberWithOptions(decimal: true), + textInputAction: TextInputAction.next, decoration: InputDecoration(labelText: l)), + )), + ]), + if (widget.entry != null && widget.entry!.source != 'manual') + Padding(padding: const EdgeInsets.only(top: 6), + child: Text('Imported from ${widget.entry!.source} — its other nutrients stay as they are.', + style: const TextStyle(color: muted, fontSize: 12.5))), + _actions(), + ]); + + Widget _actions() => Padding( + padding: const EdgeInsets.only(top: 12), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + if (error != null) Padding(padding: const EdgeInsets.only(bottom: 6), child: Text(error!, style: const TextStyle(color: bad))), + Row(children: [ + if (widget.entry != null) + TextButton.icon( + icon: Icon(Icons.delete_outline, color: armed ? Colors.white : bad), + style: TextButton.styleFrom(backgroundColor: armed ? const Color(0xFF8A2B2B) : null), + label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? Colors.white : bad)), + onPressed: () { + if (!armed) return setState(() => armed = true); + widget.sync.store.delete('food.entry', widget.entry!.u); + _done(); + }, + ), + const Spacer(), + FilledButton(onPressed: _save, child: Text(widget.entry == null ? 'Add' : 'Save')), + ]), + ]), + ); +} diff --git a/app/lib/health/heart_page.dart b/app/lib/health/heart_page.dart new file mode 100644 index 0000000..2d19dc0 --- /dev/null +++ b/app/lib/health/heart_page.dart @@ -0,0 +1,309 @@ +// Health ▸ Heart (as on the web page's Heart tab): heart rate from the band (the Pi's summaries: +// the latest day, resting, lowest / highest / resting per day), then the vitals — Blood pressure and +// Blood oxygen, each its own card: latest + category (ESC 2024 / SpO₂ bands), 30-day average, chart, +// the readings (tap = edit) and + Add. +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import '../widgets/line_chart.dart'; +import 'body_model.dart'; +import 'body_page.dart' show classColor, dm, dmy; +import 'cycle_model.dart' show day, parseDay, plus, today; +import 'range.dart'; +import 'summaries.dart'; + +String _hm(DateTime t) => t.toIso8601String().substring(11, 16); + +class HeartPage extends StatefulWidget { + const HeartPage({super.key, required this.sync, required this.range}); + final SyncService sync; + final HealthRange range; + @override + State createState() => _HeartPageState(); +} + +class _HeartPageState extends State { + final shown = {'bp': 5, 'ox': 5}; + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: Listenable.merge([widget.sync, widget.range]), + builder: (context, _) { + final all = vitals(widget.sync.store); + final bp = all.where((v) => v.isBp).toList(), ox = all.where((v) => v.spo2 != null).toList(); + return LayoutBuilder(builder: (context, box) { + final cards = [_bp(bp), _ox(ox)]; + final hrCard = _hr(); + return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [ + if (hrCard != null) ...[hrCard, const SizedBox(height: 12)], + if (box.maxWidth >= 700) + Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Expanded(child: cards[0]), const SizedBox(width: 12), Expanded(child: cards[1])]) + else ...[cards[0], const SizedBox(height: 12), cards[1]], + ]); + }); + }, + ); + + /// Heart rate from the band (the Pi's day summaries): the latest day's low – high, the resting rate + /// used for zones / calories, and lowest / highest / resting per day over the period. + Widget? _hr() { + final sm = Summaries(widget.sync.store); + final days = sm.all('day').where((x) => x['hr'] != null).toList(); + if (days.isEmpty) return null; + final person = sm.meta('person') ?? {}; + final last = days.last, h = (last['hr'] as Map).cast(); + final from = widget.range.from(parseDay(days.first['_day'] as String), today()); + List<(DateTime, double)> pts(String k) => [ + for (final x in days) + if ((x['hr'] as Map)[k] != null) (parseDay(x['_day'] as String), ((x['hr'] as Map)[k] as num).toDouble()) + ]; + final lastDay = parseDay(last['_day'] as String); + return Card( + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 8, 10), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + const Expanded(child: Text('Heart rate', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold))), + Tooltip( + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 8), + message: 'From your band (Gadgetbridge → the dashboard). Resting = the median of the last 90 days ' + '${person['rest_set'] == true ? '(your setting)' : '(worked out)'}; max ${person['hrmax'] ?? '—'} bpm. ' + 'Zones and workout calories use both.', + child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)), + ), + ]), + Row(crossAxisAlignment: CrossAxisAlignment.end, children: [ + Text('${h['low'] ?? '—'}–${h['high'] ?? '—'}', style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), + const Text(' bpm', style: TextStyle(color: muted)), + const Spacer(), + Column(crossAxisAlignment: CrossAxisAlignment.end, children: [ + Text('resting ${person['rest'] ?? '—'} bpm', style: const TextStyle(color: good)), + Text(lastDay == today() ? 'today so far' : dm(lastDay), style: const TextStyle(color: muted, fontSize: 12.5)), + ]), + const SizedBox(width: 6), + ]), + const SizedBox(height: 10), + Padding( + padding: const EdgeInsets.only(right: 6), + child: LineChart(from: from, to: plus(today(), 1), unit: 'bpm', decimals: 0, range: widget.range, series: [ + Series('Highest', pts('high'), bad), + Series('Lowest', pts('low'), const Color(0xFF5CC8FF)), + Series('Resting', pts('rest'), good), + ]), + ), + ]), + ), + ); + } + + /// The readings inside the charts' period (the latest is shown on top regardless). + List _inPeriod(List vs) => vs.where((v) => !day(v.t).isBefore(_from(vs))).toList(); + + DateTime _from(List vs) => widget.range.from(vs.isEmpty ? today() : day(vs.last.t), today()); + + Widget _bp(List vs) { + final last = vs.firstOrNull; + final listed = _inPeriod(vs); + final since = plus(today(), -30); + final month = vs.where((v) => !v.t.isBefore(since)).toList(); + final avg = month.isEmpty ? null : ( + (month.map((v) => v.sys!).reduce((a, b) => a + b) / month.length).round(), + (month.map((v) => v.dia!).reduce((a, b) => a + b) / month.length).round()); + final c = bpClass(last?.sys, last?.dia); + return _VitalCard( + title: 'Blood pressure', + head: last == null ? 'No readings yet' : '${last.sys} / ${last.dia} mmHg', + sub: last == null ? '' : '${c!.$1} · ${dm(last.t)} ${_hm(last.t)}', + subColor: classColor(c?.$2), + extra: avg == null ? null : '30-day average ${avg.$1} / ${avg.$2} (${month.length} reading${month.length != 1 ? 's' : ''})', + info: 'ESC 2024 (office readings): under 120 / 70 non-elevated · 120–139 / 70–89 elevated · 140 / 90+ hypertension · ' + '180 / 110+ severe. The higher of the two numbers decides; the average of several readings on different days is what counts.', + chart: vs.isEmpty ? null : LineChart(from: _from(vs), to: plus(today(), 1), unit: 'mmHg', decimals: 0, range: widget.range, series: [ + Series('Systolic', vitalSeries(vs, (v) => v.sys?.toDouble()), accent), + Series('Diastolic', vitalSeries(vs, (v) => v.dia?.toDouble()), const Color(0xFF5CC8FF)), + ]), + rows: [ + if (listed.isEmpty && vs.isNotEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6), + child: Text('No readings in this period', style: TextStyle(color: muted))), + for (final v in listed.take(shown['bp']!)) + _ReadingRow(v, '${v.sys} / ${v.dia}', classColor(bpClass(v.sys, v.dia)?.$2), () => _edit('bp', v)), + ], + more: listed.length - shown['bp']!, + onMore: () => setState(() => shown['bp'] = shown['bp']! + 10), + onAdd: () => _edit('bp', null), + ); + } + + Widget _ox(List vs) { + final last = vs.firstOrNull; + final listed = _inPeriod(vs); + final c = spo2Class(last?.spo2); + return _VitalCard( + title: 'Blood oxygen', + head: last == null ? 'No readings yet' : '${last.spo2!.round()} %', + sub: last == null ? '' : '${c!.$1} · ${dm(last.t)} ${_hm(last.t)}${last.source != null ? ' · ${vitalSources[last.source] ?? last.source}' : ''}', + subColor: classColor(c?.$2), + info: 'At rest: 95–100 % normal · 91–94 % low · 90 % or less very low (see a doctor). Wrist sensors read a couple of % low ' + 'now and then — a single low spot check isn\'t a verdict.', + chart: vs.isEmpty ? null : LineChart(from: _from(vs), to: plus(today(), 1), unit: '%', decimals: 0, band: (95, 100), limits: (85, 100), range: widget.range, + series: [Series('SpO₂', vitalSeries(vs, (v) => v.spo2), accent)]), + rows: [ + if (listed.isEmpty && vs.isNotEmpty) const Padding(padding: EdgeInsets.symmetric(vertical: 6), + child: Text('No readings in this period', style: TextStyle(color: muted))), + for (final v in listed.take(shown['ox']!)) + _ReadingRow(v, '${v.spo2!.round()} %', classColor(spo2Class(v.spo2)?.$2), () => _edit('ox', v)), + ], + more: listed.length - shown['ox']!, + onMore: () => setState(() => shown['ox'] = shown['ox']! + 10), + onAdd: () => _edit('ox', null), + ); + } + + Future _edit(String kind, Vital? v) => showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => VitalSheet(kind: kind, v: v, sync: widget.sync), + ); +} + +class _VitalCard extends StatelessWidget { + const _VitalCard({required this.title, required this.head, required this.sub, required this.subColor, this.extra, + required this.info, required this.chart, required this.rows, required this.more, required this.onMore, required this.onAdd}); + final String title, head, sub, info; + final String? extra; + final Color subColor; + final Widget? chart; + final List rows; + final int more; + final VoidCallback onMore, onAdd; + + @override + Widget build(BuildContext context) => Card( + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 8, 10), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))), + Tooltip(triggerMode: TooltipTriggerMode.tap, message: info, showDuration: const Duration(seconds: 8), + child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted))), + TextButton.icon(onPressed: onAdd, icon: const Icon(Icons.add, size: 18), label: const Text('Add')), + ]), + Text(head, style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), + if (sub.isNotEmpty) Text(sub, style: TextStyle(color: subColor)), + if (extra != null) Text(extra!, style: const TextStyle(color: muted, fontSize: 13)), + if (chart != null) ...[const SizedBox(height: 10), Padding(padding: const EdgeInsets.only(right: 6), child: chart!)], + ...rows, + if (more > 0) TextButton(onPressed: onMore, child: Text('Show more ($more)')), + ]), + ), + ); +} + +class _ReadingRow extends StatelessWidget { + const _ReadingRow(this.v, this.value, this.color, this.onTap); + final Vital v; + final String value; + final Color color; + final VoidCallback onTap; + @override + Widget build(BuildContext context) => InkWell( + onTap: onTap, + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row(children: [ + SizedBox(width: 160, child: Text('${v.t.year == today().year ? dm(v.t) : dmy(v.t)} ${_hm(v.t)}', maxLines: 1, + style: const TextStyle(color: muted))), + SizedBox(width: 72, child: Text(value, style: TextStyle(color: color))), + Expanded(child: Text(v.note.isNotEmpty ? v.note : vitalSources[v.source] ?? '', overflow: TextOverflow.ellipsis, + style: const TextStyle(color: muted, fontSize: 13))), + ]), + ), + ); +} + +/// Add / edit one reading: date + time, the numbers of its kind, note; Delete = tap twice. +class VitalSheet extends StatefulWidget { + const VitalSheet({super.key, required this.kind, required this.v, required this.sync}); + final String kind; + final Vital? v; + final SyncService sync; + @override + State createState() => _VitalSheetState(); +} + +class _VitalSheetState extends State { + late DateTime t = widget.v?.t ?? () { + final n = DateTime.now(); + return DateTime.utc(n.year, n.month, n.day, n.hour, n.minute); + }(); + late final sys = TextEditingController(text: widget.v?.sys?.toString() ?? ''); + late final dia = TextEditingController(text: widget.v?.dia?.toString() ?? ''); + late final ox = TextEditingController(text: widget.v?.spo2 == null ? '' : widget.v!.spo2!.round().toString()); + late final note = TextEditingController(text: widget.v?.note ?? ''); + String? error; + bool armed = false; + + @override + Widget build(BuildContext context) { + final bp = widget.kind == 'bp'; + return Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 16 + MediaQuery.of(context).viewInsets.bottom), + child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Text('${widget.v == null ? 'Add' : 'Edit'} ${bp ? 'blood pressure' : 'blood oxygen'}', + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)), + Row(children: [ + TextButton.icon(icon: const Icon(Icons.event, size: 18), label: Text(dmy(t)), onPressed: () async { + final p = await showDatePicker(context: context, initialDate: t, firstDate: DateTime.utc(2000), lastDate: today()); + if (p != null) setState(() => t = DateTime.utc(p.year, p.month, p.day, t.hour, t.minute)); + }), + TextButton.icon(icon: const Icon(Icons.schedule, size: 18), label: Text(_hm(t)), onPressed: () async { + final p = await showTimePicker(context: context, initialTime: TimeOfDay(hour: t.hour, minute: t.minute)); + if (p != null) setState(() => t = DateTime.utc(t.year, t.month, t.day, p.hour, p.minute)); + }), + ]), + if (bp) + Row(children: [ + Expanded(child: TextField(controller: sys, keyboardType: TextInputType.number, autofocus: widget.v == null, + textInputAction: TextInputAction.next, + decoration: const InputDecoration(labelText: 'Systolic (upper)', suffixText: 'mmHg'))), + const SizedBox(width: 12), + Expanded(child: TextField(controller: dia, keyboardType: TextInputType.number, + decoration: const InputDecoration(labelText: 'Diastolic (lower)', suffixText: 'mmHg'))), + ]) + else + TextField(controller: ox, keyboardType: const TextInputType.numberWithOptions(decimal: true), autofocus: widget.v == null, + decoration: const InputDecoration(labelText: 'Blood oxygen', suffixText: '%')), + TextField(controller: note, maxLength: 500, decoration: const InputDecoration(labelText: 'Note')), + if (error != null) Text(error!, style: const TextStyle(color: bad)), + Row(children: [ + if (widget.v != null) + TextButton( + onPressed: () { + if (!armed) return setState(() => armed = true); + widget.sync.store.delete('health.vital', widget.v!.u); + widget.sync.changed(); + Navigator.pop(context); + }, + child: Text(armed ? 'Tap again to delete' : 'Delete', style: const TextStyle(color: bad)), + ), + const Spacer(), + FilledButton( + onPressed: () { + final err = saveVital(widget.sync.store, u: widget.v?.u, kind: widget.kind, t: t, + sys: int.tryParse(sys.text.trim()), dia: int.tryParse(dia.text.trim()), + spo2: double.tryParse(ox.text.trim().replaceAll(',', '.')), note: note.text); + if (err != null) return setState(() => error = err); + widget.sync.changed(); + Navigator.pop(context); + }, + child: const Text('Save'), + ), + ]), + ]), + ); + } +} diff --git a/app/lib/health/meal_builder.dart b/app/lib/health/meal_builder.dart new file mode 100644 index 0000000..d84197f --- /dev/null +++ b/app/lib/health/meal_builder.dart @@ -0,0 +1,314 @@ +// The meal builder (the web page's #fd-meal): a meal = one of My foods made of others. Name, +// ingredients (a food + amount + unit, or an entry's own numbers), the total, "weight when done" +// (soup boils down / takes on water; empty = the ingredients' sum), per 100 g, portions ("whole meal" +// is added by itself), note. Saving works the values out from the ingredients as they are now. +// Ways in: My foods (a meal, or + ▸ New meal) and Food ⋮ ▸ Make a meal (from the day's entries: +// "put them together as one entry" replaces them by one entry of the meal — the day's total stays). +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'food_model.dart'; +import 'food_page.dart' show macroDots; +import 'sugar.dart' show fold; + +/// Search My foods + the database and pick one (for an ingredient). +Future pickFood(BuildContext context, SyncService sync, FoodDb? fdb) => showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => _Picker(sync: sync, fdb: fdb), + ); + +class _Picker extends StatefulWidget { + const _Picker({required this.sync, required this.fdb}); + final SyncService sync; + final FoodDb? fdb; + @override + State<_Picker> createState() => _PickerState(); +} + +class _PickerState extends State<_Picker> { + final q = TextEditingController(); + + @override + Widget build(BuildContext context) { + final t = q.text.trim(); + final my = t.isEmpty ? [] : myFoods(widget.sync.store, t); + final kept = t.isEmpty ? [] : keptProducts(widget.sync.store, t, fold: fold); // picked from the archive before + final db = t.isEmpty ? [] : [...kept, ...(widget.fdb?.search(t, limit: 12) ?? []).where((f) => !kept.any((k) => k.foodId == f.foodId))]; + Widget tile(Food f) => ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + title: Text(f.name), + subtitle: Text([ + if (f.kind == 'my') f.isMeal ? 'My meal' : 'My food' else if (f.kind == 'off') f.brand ?? 'product' else f.category, + '${(f.per100['kcal'] ?? 0).round()} kcal / 100 g', + ].join(' · '), style: const TextStyle(color: muted)), + onTap: () => Navigator.pop(context, f), + ); + return Padding( + padding: EdgeInsets.fromLTRB(16, 14, 16, 12 + MediaQuery.of(context).viewInsets.bottom), + child: ConstrainedBox( + constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.75), + child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + const Text('Add an ingredient', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)), + TextField(controller: q, autofocus: true, onChanged: (_) => setState(() {}), + decoration: const InputDecoration(prefixIcon: Icon(Icons.search), hintText: 'Search foods…')), + Flexible(child: ListView(shrinkWrap: true, children: [ + if (my.isNotEmpty) const Padding(padding: EdgeInsets.only(top: 8), child: Text('My foods', style: TextStyle(color: muted, fontSize: 12.5))), + ...my.map(tile), + if (db.isNotEmpty) const Padding(padding: EdgeInsets.only(top: 8), child: Text('Food database · products', style: TextStyle(color: muted, fontSize: 12.5))), + ...db.map(tile), + ])), + ]), + ), + ); + } +} + +/// The day's entries to tick for a meal → (picked entries) or null; "from scratch" = []. +Future?> pickEntries(BuildContext context, List es) => showModalBottomSheet>( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => _EntryPicker(es), + ); + +class _EntryPicker extends StatefulWidget { + const _EntryPicker(this.es); + final List es; + @override + State<_EntryPicker> createState() => _EntryPickerState(); +} + +class _EntryPickerState extends State<_EntryPicker> { + final picked = {}; + + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 12), + child: ConstrainedBox( + constraints: BoxConstraints(maxHeight: MediaQuery.of(context).size.height * 0.75), + child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + const Text('Make a meal', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)), + const Text('Tick what went into it — or start from scratch.', style: TextStyle(color: muted)), + Flexible(child: ListView(shrinkWrap: true, children: [ + for (final e in widget.es) + CheckboxListTile( + dense: true, + contentPadding: EdgeInsets.zero, + value: picked.contains(e.u), + onChanged: (x) => setState(() => x! ? picked.add(e.u) : picked.remove(e.u)), + title: Text(e.name), + subtitle: Text('${mealLabels[e.meal]} · ${e.portion.isEmpty ? '' : '${e.portion} · '}${e.kcal.round()} kcal', + style: const TextStyle(color: muted)), + ), + ])), + Row(children: [ + TextButton(onPressed: () => Navigator.pop(context, []), child: const Text('Start from scratch')), + const Spacer(), + FilledButton( + onPressed: picked.isEmpty ? null : () => Navigator.pop(context, widget.es.where((e) => picked.contains(e.u)).toList()), + child: Text('Next (${picked.length})'), + ), + ]), + ]), + ), + ); +} + +class MealBuilder extends StatefulWidget { + /// [row] = the meal being edited; [fromEntries] = entries to build it from (they may be replaced). + const MealBuilder({super.key, required this.sync, required this.fdb, this.row, this.fromEntries = const []}); + final SyncService sync; + final FoodDb? fdb; + final Map? row; + final List fromEntries; + @override + State createState() => _MealBuilderState(); +} + +class _MealBuilderState extends State { + late final name = TextEditingController(text: widget.row?['name'] as String? ?? ''); + late final note = TextEditingController(text: widget.row?['note'] as String? ?? ''); + late final done = TextEditingController( + text: widget.row == null || doneGramsOf(widget.row!) == null ? '' : num1(doneGramsOf(widget.row!)!)); + late final List ings = widget.row != null + ? recipeOf(widget.sync.store, widget.fdb, widget.row!) + : [for (final e in widget.fromEntries) _fromEntry(e)]; + late final amounts = [for (final i in ings) TextEditingController(text: i.amount == null ? '' : num1(i.amount!))]; + late final portions = [ + for (final p in (widget.row == null ? [] : myFood(widget.row!).portions).where((p) => p.label != 'whole meal')) + (TextEditingController(text: p.label), TextEditingController(text: num1(p.grams))) + ]; + bool together = true, armed = false; + String? error; + + Ingredient _fromEntry(Entry e) { + final f = foodOf(widget.sync.store, widget.fdb, e); + if (f != null && e.amount != null && e.unit != null && f.units.contains(e.unit)) return Ingredient.food(f, e.amount, e.unit); + // its grams when known — an amount in g / ml is its weight + final g = e.n('grams') ?? (e.amount != null && (e.unit == 'g' || e.unit == 'ml') ? e.amount : null); + return Ingredient.fixed({for (final c in foodCols) c: e.n(c)}, e.name, e.amount, e.unit, g); + } + + double? _n(TextEditingController c) => double.tryParse(c.text.trim().replaceAll(',', '.')); + + Future _add() async { + final f = await pickFood(context, widget.sync, widget.fdb); + if (f == null) return; + setState(() { + final unit = f.portions.isNotEmpty ? f.portions.first.label : 'g'; + ings.add(Ingredient.food(f, unit == 'g' ? 100 : 1, unit)); + amounts.add(TextEditingController(text: unit == 'g' ? '100' : '1')); + }); + } + + void _save() { + for (var i = 0; i < ings.length; i++) { + ings[i].amount = _n(amounts[i]); + } + final ps = [for (final (l, g) in portions) if (l.text.trim().isNotEmpty || g.text.trim().isNotEmpty) Portion(l.text, _n(g) ?? 0)]; + final store = widget.sync.store; + final (uid, err) = saveMeal(store, uid: widget.row?['_u'] as String?, name: name.text, ings: ings, + doneGrams: _n(done), portions: ps, note: note.text); + if (err != null) return setState(() => error = err); + if (widget.fromEntries.isNotEmpty && together) { + // one entry of the meal (its whole weight) replaces the picked ones: their day, the most common meal + final es = widget.fromEntries; + final counts = {}; + for (final e in es) { + counts[e.meal] = (counts[e.meal] ?? 0) + 1; + } + final meal = (counts.entries.toList()..sort((a, b) => b.value.compareTo(a.value))).first.key; + saveFromFood(store, day: es.first.day, meal: meal.isEmpty ? 'snack' : meal, food: myFoodByUid(store, uid!)!, + amount: 1, unit: 'whole meal'); + for (final e in es) { + store.delete('food.entry', e.u); + } + } + widget.sync.changed(); + Navigator.pop(context, uid); + } + + @override + Widget build(BuildContext context) { + for (var i = 0; i < ings.length; i++) { + ings[i].amount = _n(amounts[i]); + } + final tot = {}; + var grams = 0.0; + for (final i in ings) { + i.values.forEach((c, v) { + if (v != null) tot[c] = (tot[c] ?? 0) + v; + }); + grams += i.g ?? 0; + } + final weight = _n(done) ?? grams; + return Scaffold( + appBar: AppBar(title: Text(widget.row == null ? 'New meal' : 'Edit meal')), + body: ListView(padding: const EdgeInsets.fromLTRB(16, 8, 16, 24), children: [ + TextField(controller: name, decoration: const InputDecoration(labelText: 'Name (e.g. “Cabbage soup (20th Oct 2026)”)')), + const SizedBox(height: 14), + Row(children: [ + const Expanded(child: Text('Ingredients', style: TextStyle(fontWeight: FontWeight.bold))), + TextButton.icon(onPressed: _add, icon: const Icon(Icons.add, size: 18), label: const Text('Ingredient')), + ]), + for (var i = 0; i < ings.length; i++) _ing(i), + if (ings.isEmpty) const Text('Nothing yet — + Ingredient.', style: TextStyle(color: muted)), + const Divider(color: card2, height: 24), + Row(children: [ + const Text('All together ', style: TextStyle(color: muted)), + Text('${(tot['kcal'] ?? 0).round()} kcal · ${num1(grams)} g', style: const TextStyle(fontWeight: FontWeight.bold)), + const SizedBox(width: 8), + macroDots(tot), + ]), + TextField(controller: done, keyboardType: const TextInputType.numberWithOptions(decimal: true), onChanged: (_) => setState(() {}), + decoration: InputDecoration(labelText: 'Weight when done (empty = ${num1(grams)} g)', suffixText: 'g')), + if (weight > 0) + Padding(padding: const EdgeInsets.only(top: 6), child: Text( + 'Per 100 g: ${((tot['kcal'] ?? 0) * 100 / weight).round()} kcal · ' + 'P ${num1((tot['protein'] ?? 0) * 100 / weight)} · C ${num1((tot['carbs'] ?? 0) * 100 / weight)} · ' + 'F ${num1((tot['fat'] ?? 0) * 100 / weight)} g', style: const TextStyle(color: muted))), + const SizedBox(height: 12), + Row(children: [ + const Expanded(child: Text('Portions (“whole meal” is added by itself)', style: TextStyle(color: muted, fontSize: 13))), + TextButton.icon(onPressed: () => setState(() => portions.add((TextEditingController(), TextEditingController()))), + icon: const Icon(Icons.add, size: 18), label: const Text('Portion')), + ]), + for (var i = 0; i < portions.length; i++) + Row(children: [ + Expanded(flex: 3, child: TextField(controller: portions[i].$1, decoration: const InputDecoration(hintText: 'bowl, plate…', isDense: true))), + const SizedBox(width: 10), + Expanded(flex: 2, child: TextField(controller: portions[i].$2, keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(suffixText: 'g', isDense: true))), + IconButton(onPressed: () => setState(() => portions.removeAt(i)), icon: const Icon(Icons.close, size: 18, color: muted)), + ]), + TextField(controller: note, decoration: const InputDecoration(labelText: 'Note')), + if (widget.fromEntries.isNotEmpty) + CheckboxListTile( + contentPadding: EdgeInsets.zero, + value: together, + onChanged: (x) => setState(() => together = x!), + title: Text('Put the ${widget.fromEntries.length} picked entries together in the diary as one entry'), + subtitle: const Text('the day’s total stays the same', style: TextStyle(color: muted)), + ), + if (error != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(error!, style: const TextStyle(color: bad))), + const SizedBox(height: 12), + Row(children: [ + if (widget.row != null) + TextButton.icon( + icon: Icon(Icons.delete_outline, color: armed ? Colors.white : bad), + style: TextButton.styleFrom(backgroundColor: armed ? const Color(0xFF8A2B2B) : null), + label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? Colors.white : bad)), + onPressed: () { + if (!armed) return setState(() => armed = true); + deleteMyFood(widget.sync.store, widget.row!['_u'] as String); + widget.sync.changed(); + Navigator.pop(context); + }, + ), + const Spacer(), + FilledButton(onPressed: _save, child: const Text('Save')), + ]), + ]), + ); + } + + Widget _ing(int i) { + final ing = ings[i]; + final v = ing.values; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row(children: [ + Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(ing.name, maxLines: 2, overflow: TextOverflow.ellipsis), + Text(ing.food == null ? 'its own numbers${ing.grams == null ? ' · no weight' : ' · ${num1(ing.grams!)} g'}' + : '${(v['kcal'] ?? 0).round()} kcal${ing.g == null ? '' : ' · ${num1(ing.g!)} g'}', + style: const TextStyle(color: muted, fontSize: 12.5)), + ])), + if (ing.food != null) ...[ + SizedBox(width: 64, child: TextField(controller: amounts[i], keyboardType: const TextInputType.numberWithOptions(decimal: true), + onChanged: (_) => setState(() {}), decoration: const InputDecoration(isDense: true))), + const SizedBox(width: 8), + SizedBox( + width: 110, + child: DropdownButton( + value: ing.food!.units.contains(ing.unit) ? ing.unit : 'g', + isExpanded: true, + dropdownColor: card2, + items: [for (final u in ing.food!.units) DropdownMenuItem(value: u, child: Text(u, overflow: TextOverflow.ellipsis))], + onChanged: (u) => setState(() => ing.unit = u), + ), + ), + ] else + Text('${(v['kcal'] ?? 0).round()} kcal', style: const TextStyle(fontWeight: FontWeight.bold)), + IconButton(onPressed: () => setState(() { + ings.removeAt(i); + amounts.removeAt(i); + }), icon: const Icon(Icons.close, size: 18, color: muted)), + ]), + ); + } +} diff --git a/app/lib/health/my_foods.dart b/app/lib/health/my_foods.dart new file mode 100644 index 0000000..b4c71b0 --- /dev/null +++ b/app/lib/health/my_foods.dart @@ -0,0 +1,219 @@ +// Food ▸ My foods: your own food database (values per 100 g, portions) — the list (tap = edit; a meal +// opens the meal builder), + New food / New meal, and the food editor sheet (also opened from the add +// sheet's "+ New food"). +// Delete = hidden (entries made from it keep their numbers), tap twice. +import 'dart:convert'; + +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'food_model.dart'; +import 'meal_builder.dart'; + +class MyFoodsPage extends StatelessWidget { + const MyFoodsPage({super.key, required this.sync}); + final SyncService sync; + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('My foods')), + floatingActionButton: FloatingActionButton( + backgroundColor: accent, + foregroundColor: bg, + tooltip: 'New food', + onPressed: () => showModalBottomSheet( + context: context, + backgroundColor: card, + builder: (c) => SafeArea(child: Column(mainAxisSize: MainAxisSize.min, children: [ + ListTile(leading: const Icon(Icons.label_outline), title: const Text('New food'), + subtitle: const Text('from its label', style: TextStyle(color: muted)), + onTap: () { + Navigator.pop(c); + openFoodEditor(context, sync); + }), + ListTile(leading: const Icon(Icons.soup_kitchen_outlined), title: const Text('New meal'), + subtitle: const Text('from its ingredients', style: TextStyle(color: muted)), + onTap: () async { + Navigator.pop(c); + final fdb = await FoodDb.open(); + if (context.mounted) { + Navigator.push(context, MaterialPageRoute(builder: (_) => MealBuilder(sync: sync, fdb: fdb))); + } + }), + ])), + ), + child: const Icon(Icons.add), + ), + body: ListenableBuilder( + listenable: sync, + builder: (context, _) { + final all = allMyFoods(sync.store); + if (all.isEmpty) { + return const Center(child: Text('None yet — + to add a food from its label.', style: TextStyle(color: muted))); + } + return ListView(padding: const EdgeInsets.fromLTRB(12, 8, 12, 88), children: [ + for (final (r, uses) in all) + Card( + margin: const EdgeInsets.only(bottom: 8), + child: ListTile( + title: Text(r['name'] as String), + subtitle: Text([ + '${((r['kcal'] as num?) ?? 0).round()} kcal / 100 g', + if (r['recipe'] != null) 'meal', + ...((jsonDecode((r['portions'] as String?) ?? '[]') as List).map((p) => '${p['label']} ${num1((p['grams'] as num).toDouble())} g')), + if (uses > 0) 'used $uses×', + ].join(' · '), style: const TextStyle(color: muted)), + onTap: () async { + if (r['recipe'] == null) { + await openFoodEditor(context, sync, row: r); + return; + } + final fdb = await FoodDb.open(); + if (context.mounted) { + Navigator.push(context, MaterialPageRoute(builder: (_) => MealBuilder(sync: sync, fdb: fdb, row: r))); + } + }, + ), + ), + ]); + }, + ), + ); +} + +/// The editor as a bottom sheet; → the saved food's id (null = cancelled / deleted). +Future openFoodEditor(BuildContext context, SyncService sync, {Map? row, String name = ''}) => + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => FoodEditor(sync: sync, row: row, name: name), + ); + +class FoodEditor extends StatefulWidget { + const FoodEditor({super.key, required this.sync, this.row, this.name = ''}); + final SyncService sync; + final Map? row; + final String name; + @override + State createState() => _FoodEditorState(); +} + +class _FoodEditorState extends State { + late final name = TextEditingController(text: widget.row?['name'] as String? ?? widget.name); + late final note = TextEditingController(text: widget.row?['note'] as String? ?? ''); + late String sugarKind = widget.row?['sugar_kind'] as String? ?? ''; // '' = estimated (sugar.dart) + late final values = { + for (final k in foodFields.keys) + k: TextEditingController(text: widget.row?[k] == null ? '' : num1((widget.row![k] as num).toDouble())) + }; + late final portions = [ + for (final p in (jsonDecode((widget.row?['portions'] as String?) ?? '[]') as List).cast>()) + (TextEditingController(text: p['label'] as String), TextEditingController(text: num1((p['grams'] as num).toDouble()))) + ]; + String? error; + bool armed = false; + + bool get isMeal => widget.row?['recipe'] != null; + + double? _n(TextEditingController c) => double.tryParse(c.text.trim().replaceAll(',', '.')); + + void _save() { + final ps = []; + for (final (l, g) in portions) { + if (l.text.trim().isEmpty && g.text.trim().isEmpty) continue; + ps.add(Portion(l.text, _n(g) ?? 0)); + } + final (uid, err) = saveMyFood(widget.sync.store, uid: widget.row?['_u'] as String?, name: name.text, + per100: isMeal ? {for (final k in foodFields.keys) k: (widget.row![k] as num?)?.toDouble()} : {for (final e in values.entries) e.key: _n(e.value)}, + portions: ps, note: note.text, sugarKind: sugarKind); + if (err != null) return setState(() => error = err); + widget.sync.changed(); + Navigator.pop(context, uid); + } + + @override + Widget build(BuildContext context) => Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 12 + MediaQuery.of(context).viewInsets.bottom), + child: SingleChildScrollView( + child: Column(mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Text(widget.row == null ? 'New food' : isMeal ? 'Meal' : 'Edit food', + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent)), + TextField(controller: name, autofocus: widget.row == null && widget.name.isEmpty, + decoration: const InputDecoration(labelText: 'Name')), + const SizedBox(height: 10), + Text(isMeal ? 'Per 100 g — from its ingredients (change them with the meal builder)' : 'Per 100 g (from the label)', + style: const TextStyle(color: muted, fontSize: 13)), + GridView.count( + crossAxisCount: 2, shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), + crossAxisSpacing: 12, childAspectRatio: 3.2, + children: [ + for (final e in foodFields.entries) + TextField( + controller: values[e.key], + enabled: !isMeal, + autofocus: widget.row == null && widget.name.isNotEmpty && e.key == 'kcal', + keyboardType: const TextInputType.numberWithOptions(decimal: true), + textInputAction: TextInputAction.next, + decoration: InputDecoration(labelText: e.value.$1, suffixText: e.value.$2), + ), + ], + ), + const SizedBox(height: 10), + Row(children: [ + const Expanded(child: Text('Portions', style: TextStyle(color: muted, fontSize: 13))), + TextButton.icon( + onPressed: () => setState(() => portions.add((TextEditingController(), TextEditingController()))), + icon: const Icon(Icons.add, size: 18), label: const Text('Portion'), + ), + ]), + for (var i = 0; i < portions.length; i++) + Row(children: [ + Expanded(flex: 3, child: TextField(controller: portions[i].$1, + decoration: const InputDecoration(hintText: 'slice, pot, bowl…', isDense: true))), + const SizedBox(width: 10), + Expanded(flex: 2, child: TextField(controller: portions[i].$2, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration(suffixText: 'g', isDense: true))), + IconButton(onPressed: () => setState(() => portions.removeAt(i)), icon: const Icon(Icons.close, size: 18, color: muted)), + ]), + TextField(controller: note, decoration: const InputDecoration(labelText: 'Note')), + // when the added-sugar estimate gets this one wrong (homemade jam, unsweetened yogurt …) + Row(children: [ + const Expanded(child: Text('Sugar counts as', style: TextStyle(color: muted))), + DropdownButton( + value: sugarKind, + underline: const SizedBox(), + dropdownColor: card2, + items: const [ + DropdownMenuItem(value: '', child: Text('estimated')), + DropdownMenuItem(value: 'added', child: Text('all added')), + DropdownMenuItem(value: 'dairy', child: Text('milk\'s own, beyond it added')), + DropdownMenuItem(value: 'natural', child: Text('natural (none added)')), + ], + onChanged: (v) => setState(() => sugarKind = v ?? ''), + ), + ]), + if (error != null) Padding(padding: const EdgeInsets.only(top: 8), child: Text(error!, style: const TextStyle(color: bad))), + const SizedBox(height: 10), + Row(children: [ + if (widget.row != null) + TextButton.icon( + icon: Icon(Icons.delete_outline, color: armed ? Colors.white : bad), + style: TextButton.styleFrom(backgroundColor: armed ? const Color(0xFF8A2B2B) : null), + label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? Colors.white : bad)), + onPressed: () { + if (!armed) return setState(() => armed = true); + deleteMyFood(widget.sync.store, widget.row!['_u'] as String); + widget.sync.changed(); + Navigator.pop(context); + }, + ), + const Spacer(), + FilledButton(onPressed: _save, child: const Text('Save')), + ]), + ]), + ), + ); +} diff --git a/app/lib/health/overview_page.dart b/app/lib/health/overview_page.dart new file mode 100644 index 0000000..ed93140 --- /dev/null +++ b/app/lib/health/overview_page.dart @@ -0,0 +1,120 @@ +// Health ▸ Overview: today at a glance — the food eaten today (the Food page's day card), last night's +// sleep (Sleep's night card, or that it isn't in yet), then steps today | the next period. Each part's +// heading opens its page. +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'activity_page.dart' show thousands; +import 'cycle_model.dart' show CycleSettings, CycleView, Status, iso, parseDay, plus, today; +import 'cycle_page.dart' show cycleStatus; +import 'food_model.dart' show FoodDb; +import 'food_page.dart' show FoodDayCard; +import 'body_page.dart' show dm; +import 'sleep_page.dart' show Night, NightCard; +import 'summaries.dart'; + +class OverviewPage extends StatefulWidget { + const OverviewPage({super.key, required this.sync, required this.onFood}); + final SyncService sync; + final VoidCallback onFood; // → the Food section + @override + State createState() => _OverviewPageState(); +} + +class _OverviewPageState extends State { + FoodDb? fdb; + + @override + void initState() { + super.initState(); + FoodDb.open().then((x) => mounted ? setState(() => fdb = x) : null); + } + + void _tab(String name) { + const tabs = ['Overview', 'Cycle', 'Body', 'Sleep', 'Heart', 'Activity']; + DefaultTabController.of(context).animateTo(tabs.indexOf(name)); + } + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: widget.sync, + builder: (context, _) { + final sm = Summaries(widget.sync.store); + final now = today(); + final nights = [for (final x in sm.all('night', a: iso(plus(now, -400)))) Night(parseDay(x['_day'] as String), x)]; + final goal = (((sm.meta('sleep') ?? {})['goal'] as num?) ?? 8).toDouble(); + final last = nights.isNotEmpty && nights.last.day == now; + final steps = sm.day(iso(now))?['steps'] as num?; + final week = [for (var k = 1; k <= 7; k++) sm.day(iso(plus(now, -k)))?['steps'] as num?].whereType().toList(); + final cv = CycleView(widget.sync.store, const CycleSettings()); + var (head, sub) = cycleStatus(cv); + if (cv.status == Status.wait) head = cv.daysToNext == 0 ? 'today' : 'in ${cv.daysToNext} ${cv.daysToNext == 1 ? 'day' : 'days'}'; + if (cv.status == Status.period) head = 'day ${cv.cycleDay}'; + final wide = MediaQuery.of(context).size.width >= 700; + + final food = Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + _heading('Food today', widget.onFood), + FoodDayCard(sync: widget.sync, day: now, fdb: fdb), + ]); + final sleep = Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + _heading('Sleep', () => _tab('Sleep')), + if (last) + NightCard(all: nights, i: nights.length - 1, goal: goal) + else + Card(child: Padding( + padding: const EdgeInsets.all(16), + child: Text( + 'Last night isn\'t logged yet${nights.isEmpty ? '' : ' — the latest is the night to ${dm(nights.last.day)}'}. ' + 'It comes from the band once Gadgetbridge has exported and the dashboard has synced.', + style: const TextStyle(color: muted)), + )), + ]); + final tiles = Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Expanded(child: _tile('Steps today', steps == null ? '—' : thousands(steps), + week.isEmpty ? 'nothing from the band yet' : 'last 7 days: ${thousands(week.reduce((a, b) => a + b) / week.length)} a day', + () => _tab('Activity'))), + const SizedBox(width: 10), + Expanded(child: _tile(cv.status == Status.period ? 'Period' : 'Next period', head, sub, () => _tab('Cycle'), + color: cv.status == Status.late ? bad : cv.status == Status.period ? const Color(0xFFFF6B7A) : null)), + ]); + return ListView(padding: const EdgeInsets.fromLTRB(12, 4, 12, 24), children: [ + if (wide) + Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Expanded(child: food), + const SizedBox(width: 12), + Expanded(child: Column(children: [sleep, const SizedBox(height: 12), tiles])), + ]) + else ...[food, const SizedBox(height: 4), sleep, const SizedBox(height: 12), tiles], + ]); + }, + ); + + Widget _heading(String title, VoidCallback go) => InkWell( + onTap: go, + child: Padding( + padding: const EdgeInsets.fromLTRB(4, 8, 4, 8), + child: Row(children: [ + Text(title, style: const TextStyle(color: muted, fontSize: 13, fontWeight: FontWeight.bold, letterSpacing: .5)), + const Icon(Icons.chevron_right, size: 18, color: muted), + ]), + ), + ); + + Widget _tile(String label, String value, String sub, VoidCallback go, {Color? color}) => Card( + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: go, + child: Padding( + padding: const EdgeInsets.all(12), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)), + const SizedBox(height: 2), + Text(value, style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: color)), + const SizedBox(height: 2), + Text(sub, style: const TextStyle(color: muted, fontSize: 12)), + ]), + ), + ), + ); +} diff --git a/app/lib/health/range.dart b/app/lib/health/range.dart new file mode 100644 index 0000000..7523a4a --- /dev/null +++ b/app/lib/health/range.dart @@ -0,0 +1,27 @@ +// The one time period every Health chart shows (as the web pages' shared range): 1 day … all. +// Any chart's corner chip changes it for all of them; kept on this phone (store meta, not synced). +import 'package:flutter/foundation.dart'; + +import '../sync/store.dart'; +import 'cycle_model.dart' show plus; + +const ranges = [('1d', '1 day', 1), ('1w', '1 week', 7), ('1m', '1 month', 30), ('3m', '3 months', 91), + ('1y', '1 year', 365), ('all', 'All', 0)]; + +class HealthRange extends ValueNotifier { + HealthRange(this._store) : super(ranges[(_store.meta('ui_range') == 0 ? 2 : _store.meta('ui_range')) - 1].$1); + final SyncStore _store; + + String get label => ranges.firstWhere((r) => r.$1 == value).$2; + + void set(String key) { + value = key; + _store.setMeta('ui_range', ranges.indexWhere((r) => r.$1 == key) + 1); // 0 = never set → 1 week + } + + /// The first day shown: [days] back including today, or (All) the data's first day. + DateTime from(DateTime first, DateTime now) { + final days = ranges.firstWhere((r) => r.$1 == value).$3; + return days == 0 ? first : plus(now, -(days - 1)); + } +} diff --git a/app/lib/health/sleep_page.dart b/app/lib/health/sleep_page.dart new file mode 100644 index 0000000..852bc42 --- /dev/null +++ b/app/lib/health/sleep_page.dart @@ -0,0 +1,620 @@ +// Health ▸ Sleep (as on the web page's Sleep tab), from the Pi's summaries: one night on top (score ring — +// breakdown on tap —, numbers, the hypnogram; ‹ › or a bar below picks another), then over the shared +// period: tiles, stages per night (stacked, goal line), bedtime → wake-up, score per night, What stands +// out (the Pi's watch.findings) and by weekday. Per week from 4 months: the average night. +import 'dart:math'; + +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import '../widgets/bar_chart.dart' show weeklyFrom; +import '../widgets/line_chart.dart'; +import 'activity_page.dart' show hm; +import 'body_page.dart' show dm; +import 'cycle_model.dart' show daysBetween, parseDay, plus, today; +import 'range.dart'; +import 'summaries.dart'; + +const stages = ['deep', 'light', 'rem', 'asleep', 'awake', 'nap']; // stacking order, bottom up (watch.STAGES) +const stageNames = {'deep': 'Deep', 'light': 'Light', 'rem': 'REM', 'asleep': 'Asleep (no stage)', 'awake': 'Awake', 'nap': 'Nap'}; +const stageColors = { + 'deep': Color(0xFF4F6BED), 'light': Color(0xFF5CC8FF), 'rem': Color(0xFFC792EA), + 'asleep': Color(0xFF7A8399), 'awake': Color(0xFFFFB33A), 'nap': Color(0xFFFF8FC8), +}; +const _scoreC = Color(0xFF4F6BED); +const _weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; +const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +/// watch._from_noon: hours since the noon before (21:00 → 9, 07:00 → 19) +double fromNoon(DateTime t) { + final h = t.hour + t.minute / 60; + return h >= 12 ? h - 12 : h + 12; +} + +/// watch._wake: wake-up as hours from the noon before the night began (07:00 → 19, 13:00 → 25) +double wakeH(DateTime start, DateTime end) { + final s = DateTime(start.year, start.month, start.day, 12); + final noon = start.hour >= 12 ? s : s.subtract(const Duration(days: 1)); + return end.difference(noon).inMinutes / 60; +} + +/// watch.clock: hours since noon → "HH:MM" +String clock(double h) { + final m = ((h + 12) * 60).round() % (24 * 60); + return '${(m ~/ 60).toString().padLeft(2, '0')}:${(m % 60).toString().padLeft(2, '0')}'; +} + +String _t(DateTime d) => d.toIso8601String().substring(11, 16); + +class Night { + Night(this.day, this.m) : start = DateTime.parse(m['start'] as String), end = DateTime.parse(m['end'] as String); + final DateTime day; // the wake-up day + final Map m; + final DateTime start, end; + num n(String k) => (m[k] as num?) ?? 0; + double get asleep => n('asleep').toDouble(); + int get score => n('score').round(); + double? get deepPct => (m['deep_pct'] as num?)?.toDouble(); + double get bed => fromNoon(start); + double get up => wakeH(start, end); + Map get parts => { + 'deep': n('deep').toDouble(), 'light': n('light').toDouble(), 'rem': n('rem').toDouble(), + 'asleep': n('unstaged').toDouble(), 'awake': n('awake').toDouble(), + }; +} + +class SleepPage extends StatefulWidget { + const SleepPage({super.key, required this.sync, required this.range}); + final SyncService sync; + final HealthRange range; + @override + State createState() => _SleepPageState(); +} + +class _SleepPageState extends State { + DateTime? picked; // the night shown on top (null = the last) + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: Listenable.merge([widget.sync, widget.range]), + builder: (context, _) { + final sm = Summaries(widget.sync.store); + final all = [for (final x in sm.all('night')) Night(parseDay(x['_day'] as String), x)]; + if (all.isEmpty) { + return const Center(child: Padding( + padding: EdgeInsets.all(24), + child: Text('No nights from the band yet — they come from the dashboard once it has synced.', + textAlign: TextAlign.center, style: TextStyle(color: muted)), + )); + } + final meta = sm.meta('sleep') ?? {}; + final goal = ((meta['goal'] as num?) ?? 8).toDouble(); + final now = today(); + final a = widget.range.from(all.first.day, now); + final ns = all.where((n) => !n.day.isBefore(a)).toList(); + final naps = { + for (final d in sm.all('day', a: _iso(a))) + if ((d['naps'] as List?)?.isNotEmpty ?? false) + parseDay(d['_day'] as String): (d['naps'] as List).fold(0, (s, p) => s + ((p as Map)['minutes'] as num)) + }; + var i = picked == null ? all.length - 1 : all.indexWhere((n) => n.day == picked); + if (i < 0) i = all.length - 1; + double? avg(Iterable xs) { + final v = xs.whereType().toList(); + return v.isEmpty ? null : v.reduce((p, q) => p + q) / v.length; + } + + final found = ((meta['findings'] as Map?)?[widget.range.value] as List?) ?? const []; + final wide = MediaQuery.of(context).size.width >= 700; + void pick(DateTime d) => setState(() => picked = d); + + return ListView(padding: const EdgeInsets.fromLTRB(12, 12, 12, 24), children: [ + NightCard(all: all, i: i, goal: goal, onPick: (d) => setState(() => picked = d)), + const SizedBox(height: 12), + GridView.count( + crossAxisCount: wide ? 4 : 2, + shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), + mainAxisSpacing: 10, crossAxisSpacing: 10, childAspectRatio: 1.75, + children: [ + _tile('Asleep', hm(avg(ns.map((n) => n.asleep))), 'a night · goal ${goal.toStringAsFixed(goal % 1 == 0 ? 0 : 1)} h', + 'The average night of the ${ns.length} in this period'), + _tile('Score', avg(ns.map((n) => n.score.toDouble()))?.round().toString() ?? '—', 'of 100, on average', + 'Our own 0–100: duration 50, deep sleep 20, efficiency 15, interruptions 15'), + _tile('Deep', '${avg(ns.map((n) => n.deepPct))?.round() ?? '—'} %', 'of sleep · typical 13–23 %', + 'Deep sleep as a share of the staged sleep'), + _tile('Bed → up', ns.isEmpty ? '—' : '${clock(avg(ns.map((n) => n.bed))!)}–${clock(avg(ns.map((n) => n.up))!)}', 'on average', + 'Average bedtime and wake-up time'), + ], + ), + const SizedBox(height: 12), + _card('Stages per night', 'Hours of each stage a night (pink = naps that day), the dashed line = your goal. ' + 'Tap a night to show it on top.', + _Stacked(nights: ns, naps: naps, from: a, to: now, goal: goal, range: widget.range, onPick: pick)), + const SizedBox(height: 12), + _card('Bedtime → wake-up', 'Each night from going to bed to getting up (evening on top); red = under 7 h asleep.', + _Window(nights: ns, from: a, to: now, onPick: pick)), + const SizedBox(height: 12), + _card('Score per night', 'Our sleep score, 0–100', + LineChart(from: a, to: now, decimals: 0, limits: (0, 100), series: [ + Series('Score', [for (final n in ns) (n.day, n.score.toDouble())], _scoreC), + ])), + if (found.isNotEmpty) ...[ + const SizedBox(height: 12), + Card(child: Padding( + padding: const EdgeInsets.all(14), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + const Text('What stands out', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + for (final f in found) + Padding( + padding: const EdgeInsets.only(top: 10), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text((f as List)[0] as String, style: const TextStyle(color: accent, fontWeight: FontWeight.bold)), + Text(f[1] as String, style: const TextStyle(height: 1.35)), + ]), + ), + ]), + )), + ], + if (ns.length >= 7) ...[const SizedBox(height: 12), _weekdayCard(ns)], + ]); + }, + ); + + Widget _weekdayCard(List ns) { + final by = >{}; + for (final n in ns) { + by.putIfAbsent(plus(n.day, -1).weekday - 1, () => []).add(n); // the evening you went to bed + } + double? av(List xs, double Function(Night) f) => xs.isEmpty ? null : xs.map(f).reduce((p, q) => p + q) / xs.length; + final top = [for (var i = 0; i < 7; i++) av(by[i] ?? [], (n) => n.asleep) ?? 0].reduce(max); + return _card('By weekday', 'The night after each weekday evening: average asleep, bedtime and score', Column(children: [ + for (var i = 0; i < 7; i++) + Padding( + padding: const EdgeInsets.symmetric(vertical: 4), + child: Row(children: [ + SizedBox(width: 38, child: Text(_weekdays[i])), + Expanded(child: ClipRRect( + borderRadius: BorderRadius.circular(3), + child: LinearProgressIndicator(value: top == 0 ? 0 : (av(by[i] ?? [], (n) => n.asleep) ?? 0) / top, + minHeight: 8, color: stageColors['light'], backgroundColor: card2), + )), + SizedBox(width: 150, child: Text( + by[i] == null ? '—' : '${hm(av(by[i]!, (n) => n.asleep))} · ${clock(av(by[i]!, (n) => n.bed)!)} · ${av(by[i]!, (n) => n.score.toDouble())!.round()}', + textAlign: TextAlign.right, style: const TextStyle(fontSize: 12.5))), + ]), + ), + ])); + } + + Widget _tile(String label, String value, String sub, String tip) => Tooltip( + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 6), + message: tip, + child: Card(child: Padding( + padding: const EdgeInsets.all(12), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, mainAxisAlignment: MainAxisAlignment.center, children: [ + Text(label.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11.5)), + FittedBox(fit: BoxFit.scaleDown, child: Text(value, style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold))), + Text(sub, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 12)), + ]), + )), + ); + + Widget _card(String title, String tip, Widget child) => Card(child: Padding( + padding: const EdgeInsets.fromLTRB(14, 8, 10, 10), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + Expanded(child: Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))), + Tooltip( + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 8), + message: tip, + child: const Padding(padding: EdgeInsets.all(6), child: Icon(Icons.info_outline, size: 18, color: muted)), + ), + ]), + child, + ]), + )); +} + +/// One night: ‹ › (with [onPick]), score ring (breakdown on tap), numbers, the hypnogram — Sleep's top card, +/// also on Health ▸ Overview (last night, no arrows). +class NightCard extends StatelessWidget { + const NightCard({super.key, required this.all, required this.i, required this.goal, this.onPick}); + final List all; + final int i; + final double goal; + final void Function(DateTime)? onPick; + + @override + Widget build(BuildContext context) { + final n = all[i]; + final p = (n.m['parts'] as Map?)?.cast() ?? {}; + const maxOf = {'Duration': 50, 'Deep sleep': 20, 'Efficiency': 15, 'Interruptions': 15}; + final stats = [ + ('Asleep', hm(n.asleep)), + ('In bed', '${_t(n.start)}–${_t(n.end)}'), + ('Deep', n.deepPct == null ? '—' : '${hm(n.n('deep'))} · ${n.deepPct!.round()} %'), + ('Light', n.n('light') > 0 ? hm(n.n('light')) : '—'), + ('Awake', '${hm(n.n('awake'))} · ${n.n('wakeups')}×'), + ('Efficiency', '${(n.n('eff') * 100).round()} %'), + ]; + final night = '${dm(plus(n.day, -1))} → ${dm(n.day)}${n.day.year != today().year ? ' ${n.day.year}' : ''}'; + return Card(child: Padding( + padding: EdgeInsets.fromLTRB(6, onPick == null ? 14 : 6, 6, 12), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + if (onPick != null) IconButton(onPressed: i > 0 ? () => onPick!(all[i - 1].day) : null, icon: const Icon(Icons.chevron_left)), + Expanded(child: Text(i == all.length - 1 && n.day == today() ? 'Last night · $night' : night, + textAlign: TextAlign.center, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: accent))), + if (onPick != null) IconButton(onPressed: i < all.length - 1 ? () => onPick!(all[i + 1].day) : null, icon: const Icon(Icons.chevron_right)), + ]), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8), + child: Row(children: [ + Tooltip( + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 10), + message: 'Sleep score ${n.score} / 100\n' + '${maxOf.entries.map((e) => '${e.key}: ${p[e.key] ?? '—'} / ${e.value}').join('\n')}\n' + 'Duration: full at ${(min(goal, 8) - 0.5).toStringAsFixed(1)} h+; deep: full at 20 %;\n' + 'efficiency: asleep ÷ in bed, full at 95 %; interruptions: −4 per wake-up.', + child: SizedBox( + width: 82, height: 82, + child: CustomPaint( + painter: _ScoreRing(n.score / 100), + child: Center(child: Column(mainAxisSize: MainAxisSize.min, children: [ + Text('${n.score}', style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold, height: 1)), + const Text('score', style: TextStyle(color: muted, fontSize: 12)), + ])), + ), + ), + ), + const SizedBox(width: 16), + Expanded(child: Wrap(runSpacing: 8, children: [ + for (final (l, v) in stats) + SizedBox(width: 120, child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(l.toUpperCase(), style: const TextStyle(color: muted, fontSize: 11)), + Text(v, style: const TextStyle(fontWeight: FontWeight.bold)), + ])), + ])), + ]), + ), + const SizedBox(height: 10), + if ((n.m['stages'] as List?)?.isNotEmpty ?? false) + Padding(padding: const EdgeInsets.symmetric(horizontal: 8), child: _Hypnogram(night: n)) + else + const Padding(padding: EdgeInsets.all(8), child: Text('No stages recorded for this night', style: TextStyle(color: muted))), + ]), + )); + } + +} + +String _iso(DateTime d) => d.toIso8601String().substring(0, 10); + +class _ScoreRing extends CustomPainter { + _ScoreRing(this.f); + final double f; + @override + void paint(Canvas c, Size s) { + final r = Rect.fromCircle(center: s.center(Offset.zero), radius: s.width / 2 - 4); + Paint p(Color col) => Paint()..color = col..style = PaintingStyle.stroke..strokeWidth = 6..strokeCap = StrokeCap.round; + c.drawArc(r, 0, 2 * pi, false, p(card2)); + if (f > 0) c.drawArc(r, -pi / 2, 2 * pi * f.clamp(0, 1), false, p(_scoreC)); + } + + @override + bool shouldRepaint(covariant _ScoreRing old) => old.f != f; +} + +/// One night's stages: lanes awake / REM / light / deep, a block per run (watch.hypnogram); tap = that run. +class _Hypnogram extends StatefulWidget { + const _Hypnogram({required this.night}); + final Night night; + @override + State<_Hypnogram> createState() => _HypnogramState(); +} + +class _HypnogramState extends State<_Hypnogram> { + int? hit; + + @override + void didUpdateWidget(covariant _Hypnogram old) { + super.didUpdateWidget(old); + if (old.night.day != widget.night.day) hit = null; + } + + @override + Widget build(BuildContext context) { + final runs = (widget.night.m['stages'] as List).cast(); + final n = widget.night; + final h = hit == null ? null : runs[hit!]; + String at(num min) => _t(n.start.add(Duration(seconds: (min * 60).round()))); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + LayoutBuilder(builder: (context, box) { + final painter = _HypPainter(n, runs, hit); + return GestureDetector( + onTapDown: (d) { + final m = painter.minuteAt(d.localPosition.dx, box.maxWidth); + final j = runs.indexWhere((r) => (r[0] as num) <= m && m <= (r[1] as num)); + setState(() => hit = j < 0 ? null : j); + }, + child: CustomPaint(size: Size(box.maxWidth, 140), painter: painter), + ); + }), + SizedBox( + height: 20, + child: Text( + h == null + ? 'Tap a block for its times' + : '${stageNames[h[2]] ?? h[2]} · ${at(h[0] as num)} – ${at(h[1] as num)} · ${hm((h[1] as num) - (h[0] as num))}', + textAlign: TextAlign.center, + style: TextStyle(color: h == null ? muted : Colors.white, fontSize: 12.5)), + ), + ]); + } +} + +class _HypPainter extends CustomPainter { + _HypPainter(this.n, this.runs, this.hit); + final Night n; + final List runs; + final int? hit; + static const ml = 46.0, mb = 18.0, pad = 15.0; // minutes either side (as the web's) + + double get total => n.end.difference(n.start).inMinutes + 2 * pad; + double x(num min, double w) => ml + (w - ml) * (min + pad) / total; + double minuteAt(double dx, double w) => (dx - ml) / (w - ml) * total - pad; + + @override + void paint(Canvas c, Size size) { + const lanes = {'awake': 0, 'rem': 1, 'light': 2, 'asleep': 2, 'deep': 3}; + final lh = (size.height - mb) / 4; + final txt = const TextStyle(color: muted, fontSize: 10.5); + void label(String s, Offset o, {bool right = false}) { + final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout(); + tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0)); + } + + for (var i = 0; i < 4; i++) { + c.drawLine(Offset(ml, i * lh), Offset(size.width, i * lh), Paint()..color = card2); + label(['Awake', 'REM', 'Light', 'Deep'][i], Offset(ml - 6, i * lh + lh / 2), right: true); + } + for (var i = 0; i < runs.length; i++) { + final r = runs[i]; + final lane = lanes[r[2]] ?? 2; + final x0 = x(r[0] as num, size.width), x1 = x(r[1] as num, size.width); + c.drawRRect(RRect.fromRectAndRadius(Rect.fromLTRB(x0, lane * lh + 2, max(x0 + 0.8, x1), (lane + 1) * lh - 2), const Radius.circular(2)), + Paint()..color = hit == i ? Colors.white : stageColors[r[2]] ?? muted); + } + // hour ticks (every 2 h for long nights) + final a = n.start.subtract(const Duration(minutes: 15)), z = n.end.add(const Duration(minutes: 15)); + final step = z.difference(a).inHours < 6 ? 1 : 2; + for (var t = DateTime(a.year, a.month, a.day, a.hour + 1); t.isBefore(z); t = t.add(const Duration(hours: 1))) { + if (t.hour % step == 0) label(_t(t), Offset(x(t.difference(n.start).inMinutes, size.width), size.height - mb + 4)); + } + } + + @override + bool shouldRepaint(covariant _HypPainter old) => true; +} + +/// Stages per night, stacked (hours), naps on top, the goal dashed; from [weeklyFrom] days the average +/// night of each week. Tap = its numbers (and that night on top). +class _Stacked extends StatefulWidget { + const _Stacked({required this.nights, required this.naps, required this.from, required this.to, required this.goal, + required this.range, required this.onPick}); + final List nights; + final Map naps; + final DateTime from, to; + final double goal; + final HealthRange range; + final void Function(DateTime) onPick; + @override + State<_Stacked> createState() => _StackedState(); +} + +class _StackedState extends State<_Stacked> { + String? tip; + + /// [(first day, {stage: minutes} or null, label, the night's day if one)] + List<(DateTime, Map?, String, DateTime?)> _buckets() { + final per = >{for (final n in widget.nights) n.day: n.parts}; + widget.naps.forEach((d, m) => (per[d] ??= {})['nap'] = m); + final n = daysBetween(widget.from, widget.to) + 1; + final out = <(DateTime, Map?, String, DateTime?)>[]; + if (n >= weeklyFrom) { + for (var s = plus(widget.from, -(widget.from.weekday - 1)); !s.isAfter(widget.to); s = plus(s, 7)) { + final vs = [for (var i = 0; i < 7; i++) per[plus(s, i)]].whereType>().toList(); + out.add((s, vs.isEmpty ? null : {for (final st in stages) st: vs.fold(0, (a, v) => a + (v[st] ?? 0)) / vs.length}, + 'Week of ${s.day} ${_mon[s.month - 1]} · the average night (${vs.length})', null)); + } + } else { + for (var i = 0; i < n; i++) { + final d = plus(widget.from, i); + out.add((d, per[d], 'Night to ${d.day} ${_mon[d.month - 1]}', per.containsKey(d) ? d : null)); + } + } + return out; + } + + @override + Widget build(BuildContext context) { + final b = _buckets(); + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + Expanded(child: Text(tip ?? 'Tap a night for its numbers', + style: TextStyle(color: tip == null ? muted : Colors.white, fontSize: 12.5))), + RangeChip(widget.range), + ]), + const SizedBox(height: 6), + LayoutBuilder(builder: (context, box) => GestureDetector( + onTapDown: (d) { + final i = ((d.localPosition.dx - 30) / (box.maxWidth - 30) * b.length).floor().clamp(0, b.length - 1); + final (_, v, label, day) = b[i]; + if (v == null) return setState(() => tip = '$label · nothing'); + final asleep = ['deep', 'light', 'rem', 'asleep'].fold(0, (s, k) => s + (v[k] ?? 0)); + setState(() => tip = '$label · asleep ${hm(asleep)}' + '${(v['deep'] ?? 0) > 0 ? ', deep ${hm(v['deep'])}' : ''}${(v['nap'] ?? 0) > 0 ? ', nap ${hm(v['nap'])}' : ''}'); + if (day != null) widget.onPick(day); + }, + child: CustomPaint(size: Size(box.maxWidth, 170), painter: _StackPainter(b, widget.goal)), + )), + ]); + } +} + +class _StackPainter extends CustomPainter { + _StackPainter(this.b, this.goal); + final List<(DateTime, Map?, String, DateTime?)> b; + final double goal; + + @override + void paint(Canvas c, Size size) { + const ml = 30.0, mb = 16.0, mt = 4.0; + final h = size.height - mb - mt; + final peak = max(goal + 1, [for (final x in b) if (x.$2 != null) x.$2!.values.fold(0, (a, v) => a + v) / 60].fold(0, max)); + final top = (peak / 2).ceil() * 2.0; + double y(double hours) => mt + h - h * hours / top; + final txt = const TextStyle(color: muted, fontSize: 10.5); + void label(String s, Offset o, {bool right = false}) { + final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout(); + tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0)); + } + + for (var v = 0.0; v <= top; v += top > 10 ? 4 : 2) { + c.drawLine(Offset(ml, y(v)), Offset(size.width, y(v)), Paint()..color = card2); + label('${v.round()}h', Offset(ml - 4, y(v)), right: true); + } + final bw = (size.width - ml) / max(1, b.length), pad = bw > 4 ? bw * 0.18 : 0.0; + final weekly = b.length > 1 && b[1].$1.difference(b[0].$1).inDays == 7; + for (var i = 0; i < b.length; i++) { + final (d, v, _, _) = b[i]; + final x0 = ml + i * bw; + if (v != null) { + var base = 0.0; + for (final st in stages) { + final m = (v[st] ?? 0) / 60; + if (m > 0) c.drawRect(Rect.fromLTRB(x0 + pad, y(base + m), x0 + bw - pad, y(base)), Paint()..color = stageColors[st]!); + base += m; + } + } + final l = weekly + ? (d.day <= 7 && (b.length <= 30 || d.month % 3 == 1) ? _mon[d.month - 1] : null) + : b.length > 35 ? (d.day == 1 ? _mon[d.month - 1] : null) : (d.weekday == 1 || b.length <= 8 ? '${d.day} ${_mon[d.month - 1]}' : null); + if (l != null) label(l, Offset(x0 + bw / 2, size.height - mb + 3)); + } + final gy = y(goal); + for (var x = ml; x < size.width; x += 8) { + c.drawLine(Offset(x, gy), Offset(min(x + 4, size.width), gy), Paint()..color = accent..strokeWidth = 1.2); + } + } + + @override + bool shouldRepaint(covariant _StackPainter old) => true; +} + +/// Each night as a bar from bedtime to wake-up (watch.window_chart); weekly: the average night. +class _Window extends StatefulWidget { + const _Window({required this.nights, required this.from, required this.to, required this.onPick}); + final List nights; + final DateTime from, to; + final void Function(DateTime) onPick; + @override + State<_Window> createState() => _WindowState(); +} + +class _WindowState extends State<_Window> { + String? tip; + + /// [(first day, bed, up, asleep min, label, night day?)] + List<(DateTime, double, double, double, String, DateTime?)> _bars() { + final n = daysBetween(widget.from, widget.to) + 1; + if (n < weeklyFrom) { + return [ + for (final x in widget.nights) + (x.day, x.bed, x.up, x.asleep, 'Night to ${x.day.day} ${_mon[x.day.month - 1]} · ${_t(x.start)} → ${_t(x.end)} · asleep ${hm(x.asleep)}', x.day) + ]; + } + final wk = >{}; + for (final x in widget.nights) { + wk.putIfAbsent(plus(x.day, -(x.day.weekday - 1)), () => []).add(x); + } + double av(List xs, double Function(Night) f) => xs.map(f).reduce((p, q) => p + q) / xs.length; + return [ + for (final e in wk.entries) + (e.key, av(e.value, (x) => x.bed), av(e.value, (x) => x.up), av(e.value, (x) => x.asleep), + 'Week of ${e.key.day} ${_mon[e.key.month - 1]} · average of ${e.value.length} · ' + '${clock(av(e.value, (x) => x.bed))} → ${clock(av(e.value, (x) => x.up))} · asleep ${hm(av(e.value, (x) => x.asleep))}', null) + ]; + } + + @override + Widget build(BuildContext context) { + final bars = _bars(); + if (bars.isEmpty) return const SizedBox(height: 40, child: Center(child: Text('No nights in this period', style: TextStyle(color: muted)))); + final weekly = daysBetween(widget.from, widget.to) + 1 >= weeklyFrom; + final slots = weekly ? ((daysBetween(widget.from, widget.to) + 7) ~/ 7 + 1) : daysBetween(widget.from, widget.to) + 1; + final a0 = weekly ? plus(widget.from, -(widget.from.weekday - 1)) : widget.from; + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Text(tip ?? 'Tap a night for its times', style: TextStyle(color: tip == null ? muted : Colors.white, fontSize: 12.5)), + const SizedBox(height: 6), + LayoutBuilder(builder: (context, box) => GestureDetector( + onTapDown: (d) { + final slot = ((d.localPosition.dx - 40) / (box.maxWidth - 40) * slots).floor(); + final hit = bars.where((x) => (daysBetween(a0, x.$1) ~/ (weekly ? 7 : 1)) == slot).toList(); + setState(() => tip = hit.isEmpty ? null : hit.first.$5); + if (hit.isNotEmpty && hit.first.$6 != null) widget.onPick(hit.first.$6!); + }, + child: CustomPaint(size: Size(box.maxWidth, 180), painter: _WindowPainter(bars, a0, slots, weekly)), + )), + ]); + } +} + +class _WindowPainter extends CustomPainter { + _WindowPainter(this.bars, this.a0, this.slots, this.weekly); + final List<(DateTime, double, double, double, String, DateTime?)> bars; + final DateTime a0; + final int slots; + final bool weekly; + + @override + void paint(Canvas c, Size size) { + const ml = 40.0, mb = 16.0, mt = 4.0; + final top = max(6, bars.map((x) => x.$2).reduce(min).floor() - 1).toDouble(); + final bot = min(26, bars.map((x) => x.$3).reduce(max).floor() + 2).toDouble(); + double y(double hh) => mt + (size.height - mt - mb) * (hh.clamp(top, bot) - top) / (bot - top); + final txt = const TextStyle(color: muted, fontSize: 10.5); + void label(String s, Offset o, {bool right = false}) { + final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout(); + tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0)); + } + + final step = bot - top > 8 ? 2 : 1; + for (var hh = top.toInt(); hh <= bot; hh++) { + if (hh % step != 0) continue; + c.drawLine(Offset(ml, y(hh.toDouble())), Offset(size.width, y(hh.toDouble())), Paint()..color = card2); + label(clock(hh.toDouble()), Offset(ml - 4, y(hh.toDouble())), right: true); + } + final bw = (size.width - ml) / max(1, slots), pad = bw > 4 ? bw * 0.18 : 0.0; + for (final (d, bed, up, asleep, _, _) in bars) { + final i = daysBetween(a0, d) ~/ (weekly ? 7 : 1); + final x0 = ml + i * bw; + c.drawRRect(RRect.fromRectAndRadius(Rect.fromLTRB(x0 + pad, y(bed), x0 + bw - pad, y(up)), const Radius.circular(2)), + Paint()..color = asleep < 7 * 60 ? bad : stageColors['light']!); + } + for (var i = 0; i < slots; i++) { + final d = plus(a0, i * (weekly ? 7 : 1)); + final l = weekly + ? (d.day <= 7 && (slots <= 30 || d.month % 3 == 1) ? _mon[d.month - 1] : null) + : slots > 35 ? (d.day == 1 ? _mon[d.month - 1] : null) : (d.weekday == 1 || slots <= 8 ? '${d.day} ${_mon[d.month - 1]}' : null); + if (l != null) label(l, Offset(ml + i * bw + bw / 2, size.height - mb + 3)); + } + } + + @override + bool shouldRepaint(covariant _WindowPainter old) => true; +} diff --git a/app/lib/health/sugar.dart b/app/lib/health/sugar.dart new file mode 100644 index 0000000..e868d8a --- /dev/null +++ b/app/lib/health/sugar.dart @@ -0,0 +1,184 @@ +// Added sugar, estimated — a port of the dashboard's plugins/food/sugar.py (keep the word lists and +// rules identical): the sugars WHO's limit is about ("free sugars": sugar, honey, syrups added to food, +// plus fruit juice), not the sugar inside whole fruit, vegetables and plain milk. Each food gets a kind +// from its category / name: added (all its sugar counts), dairy (only beyond the milk's own lactose), natural (none). +// Shop products: the label's added-sugar figure, else NOVA 1 / "no added sugar", else their ingredients +// (sugarsIn / dairy, off.py) — see sugar.py's top. Names are matched folded (no diacritics, lower case). +import 'dart:convert'; +import 'dart:math'; + +import '../sync/store.dart'; +import 'food_model.dart'; +import 'sugar_kinds.g.dart'; + +const lactose = 5.0; // g per 100 g of milk / yogurt that is the milk's own sugar + +// lower-cased letters with diacritics → plain ones (sugar.py's FOLD) +final _foldMap = { + for (final (from, to) in [ + ('áàâäãåāăą', 'a'), ('çčć', 'c'), ('ďđ', 'd'), ('éèêëěęē', 'e'), ('íìîïī', 'i'), ('ľĺł', 'l'), ('ňńñ', 'n'), + ('óòôöõőø', 'o'), ('řŕ', 'r'), ('śšşș', 's'), ('ťţț', 't'), ('úùûüůűū', 'u'), ('ýÿ', 'y'), ('žźż', 'z'), + ]) + for (final c in from.split('')) c: to, + 'ß': 'ss', 'æ': 'ae', 'œ': 'oe', +}; + +/// 'Zahăr Brun' → 'zahar brun' (what the word lists are matched against). +String fold(String s) => s.toLowerCase().split('').map((c) => _foldMap[c] ?? c).join(); + +final _added = RegExp( + r'juice|nectar(?!ine)|syrup|honey|\bjam\b|jelly|marmalade|candy|candies|chocolate|cocoa|(? 0 ? lactose * grams / 100 : sugar)); + return 0; +} + +bool _says(String name) { + name = fold(name); + return _added.hasMatch(name) || _dairy.hasMatch(name) || _natural.hasMatch(name); +} +String _byName(String name) => _says(name) ? sugarKind(name) : 'added'; + +String foodKind(Food f) => sugarKind(f.name, category: f.category, source: f.kind == 'off' ? 'off' : f.source, nova: f.nova, + labels: f.labels, sugarsIn: f.sugarsIn, dairy: f.dairy); + +/// Added sugar (g) of [sugar] g of a foods.db food (sugar.food_part): the label's own figure when it gives one, else by its kind. +double foodPart(Food f, double sugar, double? grams) { + final s100 = f.per100['sugar']; + // "0 added" yet sugar in the ingredients: a crowd-typed 0, not the label + final a = f.addedSugar == 0 && (f.sugarsIn ?? '').isNotEmpty ? null : f.addedSugar; + if (a != null && s100 != null && s100 > 0) return sugar * min(1.0, a / s100); + return addedPart(foodKind(f), sugar, grams); +} + +/// Added sugar of entries (sugar.entry_added), the foods they were made from looked up once. +class AddedSugar { + AddedSugar(this.store, this.fdb); + final SyncStore store; + final FoodDb? fdb; + final _foods = {}; + final _mine = ?>{}; + + Food? _food(int id) => _foods.putIfAbsent(id, () => fdb?.food(id)); + Map? _my(String uid) => _mine.putIfAbsent(uid, () => store.row('food.food', uid)); + + double entry(Entry e) { + final sugar = e.n('sugar') ?? 0; + if (sugar == 0) return 0; + final grams = e.n('grams'); + if (e.foodId != null) { + final f = _food(e.foodId!); + if (f != null) return foodPart(f, sugar, grams); + } + if (e.myFoodId != null) { + final m = _my(e.myFoodId!); + if (m != null) return _myAdded(m, sugar, grams, 0); + } + return addedPart(_byName(e.name), sugar, grams); + } + + double _myAdded(Map m, double sugar, double? grams, int depth) { + final set = m['sugar_kind']; // "Sugar counts as" (My foods): as set, whatever the estimate says + if (set is String && const ['added', 'dairy', 'natural'].contains(set)) return addedPart(set, sugar, grams); + final recipe = m['recipe'] is String ? jsonDecode(m['recipe'] as String) as Map? : null; + final ings = (recipe?['ingredients'] as List?)?.cast>(); + if (ings != null && ings.isNotEmpty) { + var totSugar = 0.0, totAdded = 0.0; + for (final ing in ings) { + final ref = (ing['food'] as String?) ?? ''; + final g = (ing['grams'] as num?)?.toDouble(); + if (ref.startsWith('usda:') && g != null) { + final f = _food(int.parse(ref.substring(5))); + if (f != null) { + final s = (f.per100['sugar'] ?? 0) * g / 100; + totSugar += s; + totAdded += foodPart(f, s, g); + continue; + } + } + if (ref.startsWith('my:') && g != null && depth < 4) { + final sub = _my(ref.substring(3).replaceFirst('~', '')); // synced refs are "my:~" + if (sub != null) { + final s = ((sub['sugar'] as num?)?.toDouble() ?? 0) * g / 100; + totSugar += s; + totAdded += _myAdded(sub, s, g, depth + 1); + continue; + } + } + final s = (ing['sugar'] as num?)?.toDouble() ?? 0; // a fixed ingredient: its own numbers + if (s > 0) { + totSugar += s; + totAdded += addedPart(_byName((ing['name'] as String?) ?? ''), s, g); + } + } + return totSugar > 0 ? sugar * totAdded / totSugar : 0; + } + final base = (m['based_on'] as num?)?.toInt(); + if (base != null) { + final f = _food(base); + if (f != null) return foodPart(f, sugar, grams); + } + return addedPart(_byName((m['name'] as String?) ?? ''), sugar, grams); + } +} diff --git a/app/lib/health/sugar_kinds.g.dart b/app/lib/health/sugar_kinds.g.dart new file mode 100644 index 0000000..754501a --- /dev/null +++ b/app/lib/health/sugar_kinds.g.dart @@ -0,0 +1,56 @@ +// GENERATED from the dashboard's plugins/food/sugar_kinds.json by `python3 plugins/food/sugar.py --dart ` +// — don't edit; change the table and run it again. USDA category (lower case) → (kind, names going by their name). +const sugarKinds = { + r'apple juice': (r'added', null), + r'baby food: snacks and sweets': (r'added', null), + r'baby juice': (r'added', null), + r'baked products': (r'added', null), + r'biscuits, muffins, quick breads': (r'added', null), + r'breakfast cereals': (r'added', r'\bplain\b|grits|farina|regular and quick|unsweetened'), + r'cakes and pies': (r'added', null), + r'candy containing chocolate': (r'added', null), + r'candy not containing chocolate': (r'added', null), + r'cereal bars': (r'added', null), + r'cheese': (r'dairy', null), + r'cheese sandwiches': (r'dairy', null), + r'citrus juice': (r'added', null), + r'cookies and brownies': (r'added', null), + r'cottage/ricotta cheese': (r'dairy', null), + r'cream and cream substitutes': (r'dairy', null), + r'cream cheese, sour cream, whipped cream': (r'dairy', null), + r'dairy and egg products': (r'dairy', null), + r'doughnuts, sweet rolls, pastries': (r'added', null), + r'flavored milk, lowfat': (r'added', null), + r'flavored milk, nonfat': (r'added', null), + r'flavored milk, reduced fat': (r'added', null), + r'flavored milk, whole': (r'added', null), + r'fruit drinks': (r'added', null), + r'gelatins, ices, sorbets': (r'added', null), + r'ice cream and frozen dairy desserts': (r'added', null), + r'jams, syrups, toppings': (r'added', null), + r'liquor and cocktails': (r'added', null), + r'milk shakes and other dairy drinks': (r'added', null), + r'milk, lowfat': (r'dairy', null), + r'milk, nonfat': (r'dairy', null), + r'milk, reduced fat': (r'dairy', null), + r'milk, whole': (r'dairy', null), + r'nutrition bars': (r'added', null), + r'nutritional beverages': (r'added', null), + r'other fruit juice': (r'added', null), + r'pancakes, waffles, french toast': (r'added', null), + r'plant-based milk': (r'dairy', null), + r'plant-based yogurt': (r'dairy', null), + r'pudding': (r'added', null), + r'ready-to-eat cereal, higher sugar (>21.2g/100g)': (r'added', null), + r'ready-to-eat cereal, lower sugar (=<21.2g/100g)': (r'added', null), + r'smoothies and grain drinks': (r'added', null), + r'soft drinks': (r'added', null), + r'sport and energy drinks': (r'added', null), + r'sugars and honey': (r'added', null), + r'sweets': (r'added', null), + r'tomato-based condiments': (r'added', null), + r'turnovers and other grain-based items': (r'added', null), + r'vegetable juice': (r'added', null), + r'yogurt, greek': (r'dairy', null), + r'yogurt, regular': (r'dairy', null), +}; diff --git a/app/lib/health/summaries.dart b/app/lib/health/summaries.dart new file mode 100644 index 0000000..da61b41 --- /dev/null +++ b/app/lib/health/summaries.dart @@ -0,0 +1,34 @@ +// The Pi's Health summaries (dashboard plugins/health/summary.py), synced one way as "health.summary" +// rows: day:, night:, wk:, meta:energy, meta:person — each {k, kind, day, data (JSON)}. +// Read-only here: what the band measured, worked out on the Pi with the Health pages' own functions. +import 'dart:convert'; + +import '../sync/store.dart'; + +class Summaries { + Summaries(this.store); + final SyncStore store; + + Map? _get(String k) { + final r = store.row('health.summary', k); + return r == null ? null : jsonDecode(r['data'] as String) as Map; + } + + Map? day(String iso) => _get('day:$iso'); + Map? night(String iso) => _get('night:$iso'); + Map? meta(String name) => _get('meta:$name'); + + /// Every row of a kind (day / night / workout) in [a, z] (ISO days; null = all), by day. + List> all(String kind, {String? a, String? z}) { + final rs = store.rows('health.summary', where: "json_extract(data, '\$.kind') = ?", args: [kind]); + final out = >[]; + for (final r in rs) { + final d = r['day'] as String?; + if (a != null && d != null && d.compareTo(a) < 0) continue; + if (z != null && d != null && d.compareTo(z) > 0) continue; + out.add({'_day': d, ...jsonDecode(r['data'] as String) as Map}); + } + out.sort((x, y) => ((x['_day'] as String?) ?? '').compareTo((y['_day'] as String?) ?? '')); + return out; + } +} diff --git a/app/lib/main.dart b/app/lib/main.dart new file mode 100644 index 0000000..a0c4382 --- /dev/null +++ b/app/lib/main.dart @@ -0,0 +1,176 @@ +// dashPi companion app: Health (with Cycle + Food), Work, Weather — works offline, keeps its own +// copy of the data and syncs it through your dash-sync mailbox (server/) with the dashboard. +// First start: Connect (device token + passphrase); then the app (app/shell.dart). +// +// A build may prefill the server: --dart-define=DEV_SERVER=https://sync.example.com (tool/publish.env); +// dev runs also DEV_TOKEN=… DEV_PASS=… (only ever with a local test mailbox). +import 'dart:io'; + +import 'package:flutter/foundation.dart' show kDebugMode; +import 'package:flutter/material.dart'; +import 'package:flutter_zxing/flutter_zxing.dart' show Format; + +import 'app/background.dart'; +import 'app/scanner.dart'; +import 'app/shell.dart'; +import 'app/sync_service.dart'; +import 'app/theme.dart'; +import 'health/food_model.dart' show FoodDb; +import 'sync/client.dart'; +import 'sync/store.dart'; + +void main() { + WidgetsFlutterBinding.ensureInitialized(); + runApp(const DashApp()); +} + +class DashApp extends StatelessWidget { + const DashApp({super.key}); + + @override + Widget build(BuildContext context) => + MaterialApp(title: 'dashPi', debugShowCheckedModeBanner: false, theme: appTheme(), home: const Start()); +} + +/// Connected → the app, else the connect form. +class Start extends StatefulWidget { + const Start({super.key}); + @override + State createState() => _StartState(); +} + +class _StartState extends State { + SyncService? sync; + bool loading = true; + + @override + void initState() { + super.initState(); + _load(); + } + + Future _load() async { + final s = await SyncSettings.load(); + if (s != null) { + sync = SyncService(s, SyncStore(await dataPath(), s.device)); + FoodDb.store = sync!.store; // products kept from the archive (food_model.dart) + scheduleBackground(); + } + setState(() => loading = false); + } + + Future _connected(SyncSettings s) async { + await s.save(); + final st = SyncStore(await dataPath(), s.device); + FoodDb.store = st; + setState(() => sync = SyncService(s, st)); + scheduleBackground(); + } + + /// Disconnect: the settings are gone already; drop this phone's copy of the data too. + Future _forget() async { + final old = sync; + await stopBackground(); + setState(() => sync = null); + old?.store.db.close(); + old?.dispose(); + final p = await dataPath(); + for (final f in [p, '$p-wal', '$p-shm']) { + if (File(f).existsSync()) File(f).deleteSync(); + } + } + + @override + Widget build(BuildContext context) { + if (loading) return const Scaffold(body: Center(child: CircularProgressIndicator())); + if (sync == null) return ConnectPage(onConnected: _connected); + return Shell(sync: sync!, onForget: _forget); + } +} + +class ConnectPage extends StatefulWidget { + const ConnectPage({super.key, required this.onConnected}); + final Future Function(SyncSettings) onConnected; + @override + State createState() => _ConnectPageState(); +} + +class _ConnectPageState extends State { + final server = TextEditingController(text: const String.fromEnvironment('DEV_SERVER')); + final token = TextEditingController(text: const String.fromEnvironment('DEV_TOKEN')); + final pass = TextEditingController(text: const String.fromEnvironment('DEV_PASS')); + final recovery = TextEditingController(); + bool busy = false, useRecovery = false; + String? error; + + /// The QR code from the dashboard's Settings ▸ General ▸ Add a device: dashpi://connect?server=…&token=… + bool _takeLink(String text) { + final u = Uri.tryParse(text.trim()); + if (u == null || u.scheme != 'dashpi' || u.host != 'connect') return false; + final s = u.queryParameters['server'], t = u.queryParameters['token']; + if (s == null || t == null || s.isEmpty || t.isEmpty) return false; + setState(() { + server.text = s; + token.text = t; + error = null; + }); + return true; + } + + Future _scan() async { + final v = await scanCode(context, title: 'Scan the code from the dashboard', format: Format.qrCode, + accept: (v) => v.startsWith('dashpi://connect?')); + if (v != null && !_takeLink(v)) setState(() => error = "That's not a code from the dashboard."); + } + + Future _go() async { + if (_takeLink(token.text) || _takeLink(server.text)) return; // the link pasted into a field + setState(() { + busy = true; + error = null; + }); + try { + if (!kDebugMode && !server.text.trim().startsWith('https://')) { + throw 'The server needs an https:// address (the token travels with every request).'; + } + final s = await join(server.text.trim(), token.text.trim(), + passphrase: pass.text, recovery: useRecovery ? recovery.text : null); + await widget.onConnected(s); + } catch (e) { + setState(() => error = '$e'); + } finally { + if (mounted) setState(() => busy = false); + } + } + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('Connect to your dashboard')), + body: ListView(padding: const EdgeInsets.all(16), children: [ + const Text('On the dashboard: Settings ▸ General ▸ Devices ▸ Add a device shows a code — scan it, then type ' + 'the passphrase you chose when you set up sync there.', style: TextStyle(color: muted)), + const SizedBox(height: 12), + OutlinedButton.icon(onPressed: busy ? null : _scan, icon: const Icon(Icons.qr_code_scanner), + label: const Text('Scan the code from the dashboard')), + const SizedBox(height: 8), + TextField(controller: server, keyboardType: TextInputType.url, + decoration: const InputDecoration(labelText: 'Server', hintText: 'https://sync.example.com')), + TextField(controller: token, obscureText: true, decoration: const InputDecoration(labelText: 'Device token')), + if (!useRecovery) + TextField(controller: pass, obscureText: true, decoration: const InputDecoration(labelText: 'Sync passphrase')) + else + TextField(controller: recovery, decoration: const InputDecoration(labelText: 'Recovery key (ABCD-EFGH-…)')), + TextButton( + onPressed: () => setState(() => useRecovery = !useRecovery), + child: Text(useRecovery ? 'Use the passphrase instead' : 'Forgot it? Use the recovery key')), + const SizedBox(height: 12), + if (error != null) Text(error!, style: const TextStyle(color: bad)), + const SizedBox(height: 12), + FilledButton( + onPressed: busy ? null : _go, + child: busy + ? const SizedBox(height: 18, width: 18, child: CircularProgressIndicator(strokeWidth: 2)) + : const Text('Connect')), + ]), + ); +} diff --git a/app/lib/notes/markdown.dart b/app/lib/notes/markdown.dart new file mode 100644 index 0000000..a33efa9 --- /dev/null +++ b/app/lib/notes/markdown.dart @@ -0,0 +1,284 @@ +// Markdown → widgets for the notes' preview: the same reading as the web page's (notes.js md): +// headings, paragraphs (a line break is a break), - / 1. lists (nested by indent), - [ ] tasks +// (tappable: onTask(n) with n counted like toggleTask), > quotes, ``` code, tables, --- rules; +// inline **bold**, *italic*, ~~strike~~, ==mark==, `code`, [links](https://…), bare URLs, #tags. +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../app/theme.dart'; + +const _cool = Color(0xFF5CC8FF), _dim = Color(0xFF5D6472), _codeBg = Color(0xFF10131A); +const mono = TextStyle(fontFamily: 'monospace', fontSize: 13.5); + +final _fence = RegExp(r'^\s*(```|~~~)'), _head = RegExp(r'^(#{1,6})\s+(.*)$'), _hr = RegExp(r'^\s*([-*_])(\s*\1){2,}\s*$'); +final _quote = RegExp(r'^\s*>'), _item = RegExp(r'^(\s*)([-*+]|\d+[.)])\s+(.*)$'); +final _tsep = RegExp(r'^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$'); +final _taskLine = RegExp(r'^(\s*(?:>\s*)*(?:[-*+]|\d+[.)])\s+\[)([ xX])(\].*)$'); +final tagRe = RegExp(r'(^|\s)#(\p{L}[\p{L}\p{N}_/-]*)', unicode: true); +final _inline = RegExp( + r'`([^`]+)`' // 1 code + r'|\[([^\]]+)\]\(([^)\s]+)\)' // 2, 3 link + r'''|(https?://[^\s<>()]+[^\s<>().,;:!?'"])''' // 4 bare URL + r'|\*\*(.+?)\*\*|__(.+?)__' // 5, 6 bold + r'|(? createState() => _MarkdownViewState(); +} + +class _MarkdownViewState extends State { + final _taps = []; + int _task = 0; + + @override + void dispose() { + for (final t in _taps) { + t.dispose(); + } + super.dispose(); + } + + TapGestureRecognizer _tap(VoidCallback fn) { + final t = TapGestureRecognizer()..onTap = fn; + _taps.add(t); + return t; + } + + void _openLink(String url) { + Clipboard.setData(ClipboardData(text: url)); + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Link copied: $url'))); + } + + // ---- inline ------------------------------------------------------------------------------ + List _spans(String s, TextStyle st) { + final out = []; + var at = 0; + for (final m in _inline.allMatches(s)) { + if (m.start > at) out.add(TextSpan(text: s.substring(at, m.start), style: st)); + at = m.end; + if (m[1] != null) { + out.add(TextSpan(text: m[1], style: st.merge(mono).copyWith(backgroundColor: _codeBg))); + } else if (m[2] != null || m[4] != null) { + final url = m[3] ?? m[4]!; + if (!RegExp(r'^(https?:|mailto:)', caseSensitive: false).hasMatch(url)) { + out.add(TextSpan(text: m[0], style: st)); + continue; + } + out.add(TextSpan(text: m[2] ?? url, style: st.copyWith(color: _cool, decoration: TextDecoration.underline, + decorationColor: _cool), recognizer: _tap(() => _openLink(url)))); + } else if (m[5] != null || m[6] != null) { + out.addAll(_spans(m[5] ?? m[6]!, st.copyWith(fontWeight: FontWeight.bold))); + } else if (m[7] != null || m[8] != null) { + out.addAll(_spans(m[7] ?? m[8]!, st.copyWith(fontStyle: FontStyle.italic))); + } else if (m[9] != null) { + out.addAll(_spans(m[9]!, st.copyWith(color: _dim, decoration: TextDecoration.lineThrough))); + } else if (m[10] != null) { + out.addAll(_spans(m[10]!, st.copyWith(backgroundColor: const Color(0xFF4A3B1E)))); + } else if (m[11] != null) { + final tag = m[11]!; + out.add(TextSpan(text: '#$tag', style: st.copyWith(color: _cool), + recognizer: widget.onTag == null ? null : _tap(() => widget.onTag!(tag.toLowerCase())))); + } + } + if (at < s.length) out.add(TextSpan(text: s.substring(at), style: st)); + return out; + } + + Widget _text(String s, TextStyle st) => Text.rich(TextSpan(children: _spans(s, st))); + + // ---- blocks ------------------------------------------------------------------------------ + List _blocks(String src, TextStyle base) { + final lines = src.replaceAll('\r\n', '\n').split('\n'); + final out = []; + bool starts(String l) => + _fence.hasMatch(l) || _head.hasMatch(l) || _hr.hasMatch(l) || _quote.hasMatch(l) || _item.hasMatch(l); + var i = 0; + while (i < lines.length) { + final l = lines[i]; + if (l.trim().isEmpty) { + i++; + continue; + } + RegExpMatch? m; + if ((m = _fence.firstMatch(l)) != null) { + final code = []; + for (i++; i < lines.length && !lines[i].trim().startsWith(m![1]!); i++) { + code.add(lines[i]); + } + i++; + out.add(Container( + width: double.infinity, + padding: const EdgeInsets.all(12), + decoration: BoxDecoration(color: _codeBg, borderRadius: BorderRadius.circular(10)), + child: SingleChildScrollView(scrollDirection: Axis.horizontal, child: Text(code.join('\n'), style: mono)), + )); + } else if ((m = _head.firstMatch(l)) != null) { + final n = m![1]!.length; + final size = const [24.0, 20.0, 17.5, 15.5, 15.0, 15.0][n - 1]; + out.add(Padding( + padding: const EdgeInsets.only(top: 6), + child: _text(m[2]!.replaceAll(RegExp(r'\s#+\s*$'), ''), base.copyWith(fontSize: size, + fontWeight: FontWeight.bold, color: n == 1 ? accent : n >= 4 ? muted : null)), + )); + i++; + } else if (_hr.hasMatch(l)) { + out.add(const Divider(color: card2, height: 20)); + i++; + } else if (_quote.hasMatch(l)) { + final q = []; + for (; i < lines.length && _quote.hasMatch(lines[i]); i++) { + q.add(lines[i].replaceFirst(RegExp(r'^\s*>\s?'), '')); + } + out.add(Container( + padding: const EdgeInsets.only(left: 12), + decoration: const BoxDecoration(border: Border(left: BorderSide(color: Color(0xFF3A4253), width: 3))), + child: _column(_blocks(q.join('\n'), base.copyWith(color: muted))), + )); + } else if (l.contains('|') && i + 1 < lines.length && _tsep.hasMatch(lines[i + 1])) { + List cells(String x) => x.trim().replaceAll(RegExp(r'^\||\|$'), '').split('|').map((c) => c.trim()).toList(); + final rows = [cells(l)]; + for (i += 2; i < lines.length && lines[i].contains('|') && lines[i].trim().isNotEmpty; i++) { + rows.add(cells(lines[i])); + } + final w = rows.map((r) => r.length).reduce((a, b) => a > b ? a : b); + out.add(SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Table( + defaultColumnWidth: const IntrinsicColumnWidth(), + border: TableBorder.all(color: card2), + children: [ + for (final (k, r) in rows.indexed) + TableRow( + decoration: k == 0 ? const BoxDecoration(color: _codeBg) : null, + children: [ + for (var c = 0; c < w; c++) + Padding(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5), + child: _text(c < r.length ? r[c] : '', k == 0 ? base.copyWith(fontWeight: FontWeight.bold) : base)), + ], + ), + ], + ), + )); + } else if (_item.hasMatch(l)) { + final items = <(int, bool, String)>[]; + while (i < lines.length) { + final x = lines[i]; + final im = _item.firstMatch(x); + if (im != null) { + items.add((im[1]!.replaceAll('\t', ' ').length, RegExp(r'\d').hasMatch(im[2]!), im[3]!)); + } else if (x.trim().isNotEmpty && RegExp(r'^\s').hasMatch(x) && items.isNotEmpty) { + final (a, b, t) = items.removeLast(); // a wrapped line of the item above + items.add((a, b, '$t\n${x.trim()}')); + } else { + break; + } + i++; + } + out.add(_list(items, base)); + } else { + final p = []; + for (; i < lines.length && lines[i].trim().isNotEmpty && !(p.isNotEmpty && starts(lines[i])); i++) { + p.add(lines[i]); + } + out.add(_text(p.join('\n'), base)); + } + } + return out; + } + + /// One row per item, indented by its depth (the indents seen so far, like nested lists). + Widget _list(List<(int, bool, String)> items, TextStyle base) { + final stack = [], numbers = []; + final rows = []; + for (final (ind, ordered, text) in items) { + while (stack.isNotEmpty && ind < stack.last) { + stack.removeLast(); + numbers.removeLast(); + } + if (stack.isEmpty || ind > stack.last) { + stack.add(ind); + numbers.add(0); + } + numbers[numbers.length - 1]++; + final depth = stack.length - 1; + final t = RegExp(r'^\[([ xX])\](\s+|$)([\s\S]*)$').firstMatch(text); + Widget lead; + Widget body; + if (t != null) { + final n = _task++, done = t[1] != ' '; + lead = InkWell( + onTap: widget.onTask == null ? null : () => widget.onTask!(n), + child: Padding( + padding: const EdgeInsets.only(right: 6), + child: Icon(done ? Icons.check_box : Icons.check_box_outline_blank, size: 21, color: done ? accent : muted), + ), + ); + body = _text(t[3]!, done ? base.copyWith(color: _dim, decoration: TextDecoration.lineThrough) : base); + } else { + lead = SizedBox( + width: 22, + child: Text(ordered ? '${numbers.last}.' : depth.isEven ? '•' : '◦', style: base.copyWith(color: muted)), + ); + body = _text(text, base); + } + rows.add(Padding( + padding: EdgeInsets.only(left: 4 + depth * 20.0, top: 2, bottom: 2), + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [lead, Expanded(child: body)]), + )); + } + return _column(rows, gap: 0); + } + + Widget _column(List ws, {double gap = 8}) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final (k, w) in ws.indexed) ...[if (k > 0) SizedBox(height: gap), w], + ], + ); + + @override + Widget build(BuildContext context) { + for (final t in _taps) { + t.dispose(); + } + _taps.clear(); + _task = 0; + final base = DefaultTextStyle.of(context).style.copyWith(fontSize: 15.5, height: 1.45); + return _column(_blocks(widget.text, base), gap: 10); + } +} diff --git a/app/lib/notes/note_editor.dart b/app/lib/notes/note_editor.dart new file mode 100644 index 0000000..4b3c8d0 --- /dev/null +++ b/app/lib/notes/note_editor.dart @@ -0,0 +1,346 @@ +// One note: Preview (markdown.dart — tap a checkbox to tick it, a #tag to list its notes) or Edit +// (the markdown text, a toolbar above the keyboard; Enter in a list item starts the next one). +// Saves a second after the last key and on leaving; when a sync changed the note meanwhile, the +// text is kept as a copy beside it (notes_model.saveNote). A change arriving while nothing is typed +// here just shows up. +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'markdown.dart'; +import 'notes_model.dart'; +import 'notes_page.dart' show askFolder; + +class NoteEditor extends StatefulWidget { + const NoteEditor({super.key, required this.sync, this.id, this.folder = '', this.pinned = false, this.startText = '', + this.onTag}); + final SyncService sync; + final String? id; // null = a new note (saved once there's text) + final String folder, startText; + final bool pinned; + final void Function(String tag)? onTag; + @override + State createState() => _NoteEditorState(); +} + +final _itemRe = RegExp(r'^(\s*)([-*+]|\d+[.)])(\s+)(\[[ xX]\]\s+)?(.*)$'); + +class _NoteEditorState extends State { + late String? id = widget.id; + late final Note? first = id == null ? null : getNote(widget.sync.store, id!); + late final text = TextEditingController(text: first?.body ?? widget.startText); + late String? base = first?.rev; + late String folder = first?.folder ?? widget.folder; + late bool pinned = first?.pinned ?? widget.pinned; + late bool editing = first == null || first!.body.trim().isEmpty; + late String last = text.text; + bool dirty = false; + Timer? timer; + final focus = FocusNode(); + + SyncService get sync => widget.sync; + Note? get note => id == null ? null : getNote(sync.store, id!); + + @override + void initState() { + super.initState(); + sync.addListener(_synced); + if (first == null) text.selection = const TextSelection.collapsed(offset: 0); + } + + @override + void dispose() { + _save(later: true); + sync.removeListener(_synced); + timer?.cancel(); + text.dispose(); + focus.dispose(); + super.dispose(); + } + + /// Data arrived / changed: the note changed elsewhere and nothing's typed here → show it. + void _synced() { + if (id == null || !mounted) return; + final n = note; + if (n == null) { // deleted on another device + if (dirty) { + id = null; // what's typed becomes a new note + _save(later: true); + } else { + Navigator.of(context).maybePop(); + } + return; + } + if (n.rev != base && !dirty) { + setState(() { + base = n.rev; + text.text = last = n.body; + }); + } + if (n.folder != folder || n.pinned != pinned) { + setState(() { + folder = n.folder; + pinned = n.pinned; + }); + } + } + + /// later: from dispose / a sync callback — the pages hear about it after this frame. + void _save({bool later = false}) { + timer?.cancel(); + if (!dirty) return; + dirty = false; + if (id == null && text.text.trim().isEmpty) return; // an empty new note: nothing to keep + final (nid, conflict) = saveNote(sync.store, id: id, body: text.text, base: base, folder: folder, pinned: pinned); + id = nid; + base = note?.rev; + if (later) { + scheduleMicrotask(sync.changed); + return; + } + sync.changed(); + if (conflict && mounted) { + setState(() {}); + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text('This note changed on another device meanwhile — your text is kept as a separate copy.'))); + } + } + + void _changed(String v) { + // Enter at the end of a list item: the next item (an empty item ends the list) + final p = text.selection.baseOffset; + if (v.length == last.length + 1 && p > 0 && text.selection.isCollapsed && v[p - 1] == '\n' && + v.substring(0, p - 1) + v.substring(p) == last) { + final s = v.lastIndexOf('\n', p - 2) + 1; + final m = _itemRe.firstMatch(v.substring(s, p - 1)); + if (m != null) { + if (m[5]!.trim().isEmpty) { + _set(v.substring(0, s) + v.substring(p), s); + } else { + final n = RegExp(r'^(\d+)([.)])$').firstMatch(m[2]!); + final mark = '${m[1]}${n == null ? m[2] : '${int.parse(n[1]!) + 1}${n[2]}'}${m[3]}${m[4] != null ? '[ ] ' : ''}'; + _set(v.substring(0, p) + mark + v.substring(p), p + mark.length); + } + return; + } + } + last = v; + _dirty(); + } + + void _set(String v, int cursor) { + text.value = TextEditingValue(text: v, selection: TextSelection.collapsed(offset: cursor)); + last = v; + _dirty(); + } + + void _dirty() { + dirty = true; + timer?.cancel(); + timer = Timer(const Duration(seconds: 1), _save); + } + + // ---- toolbar ------------------------------------------------------------------------------- + void _wrap(String a, [String? b, String ph = 'text']) { + b ??= a; + final v = text.text, sel = text.selection.isValid ? text.selection : TextSelection.collapsed(offset: v.length); + final inner = sel.isCollapsed ? ph : sel.textInside(v); + _set(v.replaceRange(sel.start, sel.end, '$a$inner$b'), sel.start + a.length + inner.length); + text.selection = TextSelection(baseOffset: sel.start + a.length, extentOffset: sel.start + a.length + inner.length); + focus.requestFocus(); + } + + void _lines(String Function(String) fn) { + final v = text.text, sel = text.selection.isValid ? text.selection : TextSelection.collapsed(offset: v.length); + final s = sel.start == 0 ? 0 : v.lastIndexOf('\n', sel.start - 1) + 1; + var e = v.indexOf('\n', sel.end); + if (e < 0) e = v.length; + final block = v.substring(s, e).split('\n').map(fn).join('\n'); + _set(v.replaceRange(s, e, block), s + block.length); + focus.requestFocus(); + } + + late final tools = <(Widget, String, VoidCallback)>[ + (const Text('H', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 17)), 'Heading', () => _lines((l) => + RegExp(r'^#{1,5}\s').hasMatch(l) ? '#$l' : RegExp(r'^#{6}\s').hasMatch(l) ? l.replaceFirst(RegExp(r'^#+\s'), '') : '# $l')), + (const Icon(Icons.format_bold), 'Bold', () => _wrap('**')), + (const Icon(Icons.format_italic), 'Italic', () => _wrap('*')), + (const Icon(Icons.format_strikethrough), 'Strikethrough', () => _wrap('~~')), + (const Icon(Icons.format_list_bulleted), 'List', () => _lines((l) => RegExp(r'^\s*[-*+]\s').hasMatch(l) + ? l.replaceFirst(RegExp(r'^(\s*)[-*+]\s+(\[[ xX]\]\s+)?'), '') : '- $l')), + (const Icon(Icons.check_box_outlined), 'Checklist', () => _lines((l) => RegExp(r'^\s*[-*+]\s\[[ xX]\]').hasMatch(l) + ? l.replaceFirst(RegExp(r'^\s*[-*+]\s\[[ xX]\]\s?'), '') : l.replaceFirst(RegExp(r'^\s*(?:[-*+]\s+)?'), '- [ ] '))), + (const Icon(Icons.format_quote), 'Quote', () => _lines((l) => l.startsWith('>') ? l.replaceFirst(RegExp(r'^>\s?'), '') : '> $l')), + (const Icon(Icons.code), 'Code', () => _wrap('`', '`', 'code')), + (const Icon(Icons.link), 'Link', () => _wrap('[', '](https://)', 'link')), + (const Icon(Icons.tag), 'Tag', () => _wrap('#', '', 'tag')), + ]; + + // ---- the menu ------------------------------------------------------------------------------ + Future _move() async { + final f = await askFolder(context, sync, folder); + if (f == null) return; + setState(() => folder = cleanFolder(f)); + if (id != null) { + _save(); + setNote(sync.store, id!, {'folder': folder}); + sync.changed(); + } + } + + void _pin() { + setState(() => pinned = !pinned); + if (id != null) { + _save(); + setNote(sync.store, id!, {'pinned': pinned ? 1 : 0}); + sync.changed(); + } + } + + void _trash() { + _save(); + if (id != null) { + trashNote(sync.store, id!, true); + sync.changed(); + } + dirty = false; + Navigator.pop(context); + } + + @override + Widget build(BuildContext context) { + final n = note; + final trashed = n?.trashed != null; + final showEdit = editing && !trashed; + return Scaffold( + appBar: AppBar( + titleSpacing: 0, + title: InkWell( + onTap: trashed ? null : _move, + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Icon(folder.isEmpty ? Icons.folder_off_outlined : Icons.folder_outlined, size: 18, color: muted), + const SizedBox(width: 6), + Flexible(child: Text(folder.isEmpty ? 'No folder' : folder, overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 15, color: muted))), + ]), + ), + actions: [ + if (!trashed) ...[ + IconButton( + tooltip: editing ? 'Preview' : 'Edit', + icon: Icon(editing ? Icons.visibility_outlined : Icons.edit_outlined), + onPressed: () { + _save(); + setState(() => editing = !editing); + if (editing) focus.requestFocus(); + }, + ), + IconButton( + tooltip: pinned ? 'Unpin' : 'Pin to the top', + icon: Icon(pinned ? Icons.push_pin : Icons.push_pin_outlined, color: pinned ? accent : null), + onPressed: _pin, + ), + ], + PopupMenuButton( + icon: const Icon(Icons.more_vert), + color: card2, + onSelected: (k) { + switch (k) { + case 'move': + _move(); + case 'trash': + _trash(); + case 'restore': + trashNote(sync.store, id!, false); + sync.changed(); + case 'purge': + deleteNote(sync.store, id!); + sync.changed(); + Navigator.pop(context); + } + }, + itemBuilder: (_) => trashed + ? const [ + PopupMenuItem(value: 'restore', child: Text('Restore')), + PopupMenuItem(value: 'purge', child: Text('Delete for good', style: TextStyle(color: bad))), + ] + : const [ + PopupMenuItem(value: 'move', child: Text('Move to folder…')), + PopupMenuItem(value: 'trash', child: Text('Move to the trash')), + ], + ), + ], + ), + body: SafeArea( + top: false, + child: Column(children: [ + if (trashed) + _banner('In the trash — restore it to edit.', null) + else if (n?.origin != null) + _banner('Conflicted copy: this note was changed on two devices at once, and this is the version that didn\'t ' + 'win — the other one kept the original. Take what you need, then keep it or move it to the trash.', + TextButton(onPressed: () { + setNote(sync.store, id!, {'origin': null}); + sync.changed(); + }, child: const Text('Keep as a normal note'))), + Expanded( + child: showEdit + ? Padding( + padding: const EdgeInsets.fromLTRB(16, 4, 16, 0), + child: TextField( + controller: text, + focusNode: focus, + autofocus: first == null, + expands: true, + maxLines: null, + keyboardType: TextInputType.multiline, + textCapitalization: TextCapitalization.sentences, + style: const TextStyle(fontFamily: 'monospace', fontSize: 15, height: 1.45), + decoration: const InputDecoration(border: InputBorder.none, + hintText: 'Write in markdown: # heading, **bold**, - [ ] a task, #tag …'), + onChanged: _changed, + ), + ) + : ListView(padding: const EdgeInsets.fromLTRB(18, 10, 18, 40), children: [ + if (text.text.trim().isEmpty) + const Text('Empty — tap ✎ to write.', style: TextStyle(color: muted)) + else + MarkdownView( + text.text, + onTask: trashed ? null : (i) => setState(() { + _set(toggleTask(text.text, i), 0); + _save(); + }), + onTag: widget.onTag == null ? null : (t) { + widget.onTag!(t); + Navigator.pop(context); + }, + ), + ]), + ), + if (showEdit) + Container( + color: card, + height: 46, + child: ListView(scrollDirection: Axis.horizontal, children: [ + for (final (icon, tip, fn) in tools) IconButton(tooltip: tip, icon: icon, onPressed: fn), + ]), + ), + ]), + ), + ); + } + + Widget _banner(String msg, Widget? action) => Container( + width: double.infinity, + margin: const EdgeInsets.fromLTRB(12, 8, 12, 0), + padding: const EdgeInsets.fromLTRB(12, 10, 12, 4), + decoration: BoxDecoration(color: const Color(0xFF3A2A17), borderRadius: BorderRadius.circular(10)), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(msg, style: const TextStyle(color: Color(0xFFF4D6A8), fontSize: 13.5)), + if (action != null) Align(alignment: Alignment.centerRight, child: action) else const SizedBox(height: 6), + ]), + ); +} diff --git a/app/lib/notes/notes_model.dart b/app/lib/notes/notes_model.dart new file mode 100644 index 0000000..12388b2 --- /dev/null +++ b/app/lib/notes/notes_model.dart @@ -0,0 +1,136 @@ +// Notes: the dashboard's notes plugin (plugins/notes/db.py) on the phone — one synced row per note +// in "notes.note": folder ("Work/Acme", '' = none), body (markdown), pinned, created / updated +// (UTC), rev / revs (versions, for the sync's "keep both copies" — SyncStore.forks), origin (a +// conflicted copy: the rev it keeps), trashed (in the trash since). Title = the first line, tags = +// the #words — worked out on read, like the web page. +import 'dart:math'; + +import '../sync/store.dart'; +import 'markdown.dart' show tagRe; + +const noteTable = 'notes.note'; +const _revs = 200; // versions remembered per note (db.REVS) + +String nowIso() => '${DateTime.now().toUtc().toIso8601String().substring(0, 19)}Z'; + +String newRev() { + final r = Random.secure(); + return List.generate(6, (_) => r.nextInt(256).toRadixString(16).padLeft(2, '0')).join(); +} + +String noteTitle(String body) { + for (final l in body.split('\n')) { + final s = l.trim().replaceFirst(RegExp(r'^#+'), '').trim(); + if (s.isNotEmpty) return s.length > 120 ? s.substring(0, 120) : s; + } + return 'Untitled'; +} + +List noteTags(String body) { + final plain = body.replaceAll(RegExp(r'```[\s\S]*?(```|$)'), '').replaceAll(RegExp(r'`[^`\n]*`'), ''); + return {for (final m in tagRe.allMatches(plain)) m[2]!.toLowerCase()}.toList(); +} + +String noteSnippet(String body) { + final lines = body.split('\n'); + final first = lines.indexWhere((l) => l.trim().isNotEmpty); + final text = lines.skip(first + 1).map((l) => l.replaceFirst(RegExp(r'^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?'), '')).join(' ') + .replaceAll(RegExp(r'[#>*_`~=\[\]]|\(http[^)]*\)'), '').replaceAll(RegExp(r'\s+'), ' ').trim(); + return text.length > 160 ? text.substring(0, 160) : text; +} + +/// " Work / Acme/ " → "Work/Acme". +String cleanFolder(String f) => f.replaceAll('\\', '/').split('/').map((p) => p.trim()).where((p) => p.isNotEmpty).join('/'); + +/// Lower case without accents, for search. +String fold(String s) { + const from = 'áäàâãåčćďéěëèêíïìîľĺňñóöòôõőřŕšśťúůüùûűýÿžźżłąęß'; + const to = 'aaaaaaccdeeeeeiiiillnnoooooorrssstuuuuuuyyzzzlaes'; + final out = StringBuffer(); + for (final c in s.toLowerCase().split('')) { + final i = from.indexOf(c); + out.write(i < 0 ? c : to[i]); + } + return out.toString(); +} + +class Note { + Note(this.r); + final Map r; + String get id => r['_u'] as String; + String get body => (r['body'] as String?) ?? ''; + String get folder => (r['folder'] as String?) ?? ''; + bool get pinned => (r['pinned'] as num? ?? 0) != 0; + String get updated => (r['updated'] as String?) ?? ''; + String get rev => (r['rev'] as String?) ?? ''; + String? get origin => r['origin'] as String?; + String? get trashed => r['trashed'] as String?; + String get title => noteTitle(body); + List get tags => noteTags(body); +} + +List allNotes(SyncStore s) => [for (final r in s.rows(noteTable)) Note(r)]; + +Note? getNote(SyncStore s, String id) { + final r = s.row(noteTable, id); + return r == null ? null : Note(r); +} + +/// Save the text typed on version [base] → (the note's id, conflict). A new note: no id. When the +/// note changed meanwhile (a sync came in), the text becomes a copy beside it (db.save). +(String, bool) saveNote(SyncStore s, {String? id, required String body, String? base, String folder = '', bool pinned = false}) { + final t = nowIso(); + final cur = id == null ? null : s.row(noteTable, id); + if (cur == null || (base != null && base != cur['rev'] && body != cur['body'])) { + final rev = newRev(), nid = SyncStore.randomId(); + final copy = cur != null; + s.put(noteTable, nid, { + 'folder': copy ? cur['folder'] : cleanFolder(folder), 'body': body, 'pinned': copy ? 0 : (pinned ? 1 : 0), + 'created': t, 'updated': t, 'rev': rev, 'revs': rev, 'origin': copy ? rev : null, 'trashed': null, + }); + return (nid, copy); + } + if (body == cur['body']) return (id!, false); + final row = {...cur, 'body': body, 'updated': t}; + if (s.known(noteTable, id!)) { // seen elsewhere: a new version (else typing goes on in this one) + final rev = newRev(); + final revs = [...((cur['revs'] as String?) ?? '').split(' ').where((x) => x.isNotEmpty), rev]; + row['rev'] = rev; + row['revs'] = revs.skip(max(0, revs.length - _revs)).join(' '); + } + s.put(noteTable, id, row); + return (id, false); +} + +/// Pinned, folder, trashed, origin — no new version. +void setNote(SyncStore s, String id, Map fields) { + final cur = s.row(noteTable, id); + if (cur != null) s.put(noteTable, id, {...cur, ...fields}); +} + +void trashNote(SyncStore s, String id, bool on) => setNote(s, id, {'trashed': on ? nowIso() : null}); + +/// For good (from the trash). +void deleteNote(SyncStore s, String id) => s.delete(noteTable, id); + +int emptyTrash(SyncStore s) { + final gone = allNotes(s).where((n) => n.trashed != null).toList(); + for (final n in gone) { + s.delete(noteTable, n.id); + } + return gone.length; +} + +/// Every note in [from] and its sub-folders moves to [to] (same sub-paths). +int renameFolder(SyncStore s, String from, String to) { + from = cleanFolder(from); + to = cleanFolder(to); + var n = 0; + for (final x in allNotes(s)) { + if (x.folder == from || x.folder.startsWith('$from/')) { + setNote(s, x.id, {'folder': cleanFolder(to + x.folder.substring(from.length))}); + n++; + } + } + return n; +} diff --git a/app/lib/notes/notes_page.dart b/app/lib/notes/notes_page.dart new file mode 100644 index 0000000..8b67ef5 --- /dev/null +++ b/app/lib/notes/notes_page.dart @@ -0,0 +1,437 @@ +// Notes: the list — search box, where you are in the title (tap: All / Pinned / conflicted copies / +// folders / tags / Trash), pinned first, newest change first; + = a new note there; tap = the note +// (note_editor.dart), long-press = pin, move, trash. ⋮: rename the folder, empty the trash. +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'note_editor.dart'; +import 'notes_model.dart'; + +/// Where the list is: all, pinned, conflicts, folder (value), tag (value), trash. +typedef NoteFilter = ({String kind, String? value}); + +class NotesPage extends StatefulWidget { + const NotesPage({super.key, required this.sync, this.actions = const []}); + final SyncService sync; + final List actions; + @override + State createState() => _NotesPageState(); +} + +class _NotesPageState extends State { + NoteFilter filter = (kind: 'all', value: null); + final search = TextEditingController(); + + String get label => switch (filter.kind) { + 'pinned' => 'Pinned', + 'conflicts' => 'Conflicted copies', + 'folder' => filter.value!.split('/').last, + 'tag' => '#${filter.value}', + 'trash' => 'Trash', + _ => 'Notes', + }; + + List shown(List all) { + var l = filter.kind == 'trash' ? all.where((n) => n.trashed != null) : all.where((n) => n.trashed == null); + l = switch (filter.kind) { + 'pinned' => l.where((n) => n.pinned), + 'conflicts' => l.where((n) => n.origin != null), + 'folder' => l.where((n) => n.folder == filter.value || n.folder.startsWith('${filter.value}/')), + 'tag' => l.where((n) => n.tags.contains(filter.value)), + _ => l, + }; + final words = fold(search.text).split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList(); + if (words.isNotEmpty) { + l = l.where((n) { + final t = fold('${n.body} ${n.folder}'); + return words.every(t.contains); + }); + } + final out = l.toList() + ..sort((a, b) { + if (filter.kind != 'trash' && a.pinned != b.pinned) return a.pinned ? -1 : 1; + return (b.trashed ?? b.updated).compareTo(a.trashed ?? a.updated); + }); + return out; + } + + void _open(Note? n) => Navigator.push(context, MaterialPageRoute(builder: (_) => NoteEditor( + sync: widget.sync, + id: n?.id, + folder: filter.kind == 'folder' ? filter.value! : '', + pinned: filter.kind == 'pinned', + startText: filter.kind == 'tag' ? '\n\n#${filter.value}' : '', + onTag: (t) => setState(() => filter = (kind: 'tag', value: t)), + ))); + + /// The sheet behind the title: where to look. + void _where(List all) { + final live = all.where((n) => n.trashed == null).toList(); + final folders = {}; + for (final n in live) { + if (n.folder.isEmpty) continue; + final parts = n.folder.split('/'); + for (var i = 1; i <= parts.length; i++) { + final p = parts.take(i).join('/'); + folders[p] = (folders[p] ?? 0) + 1; + } + } + final tags = {}; + for (final n in live) { + for (final t in n.tags) { + tags[t] = (tags[t] ?? 0) + 1; + } + } + final pinned = live.where((n) => n.pinned).length, copies = live.where((n) => n.origin != null).length; + showModalBottomSheet( + context: context, + backgroundColor: card, + isScrollControlled: true, + builder: (c) { + Widget item(NoteFilter f, Widget icon, String text, int n, {int depth = 0}) => ListTile( + dense: true, + contentPadding: EdgeInsets.only(left: 16 + depth * 18.0, right: 16), + leading: icon, + title: Text(text, overflow: TextOverflow.ellipsis), + trailing: n > 0 ? Text('$n', style: const TextStyle(color: muted)) : null, + selected: f == filter, + selectedColor: accent, + onTap: () { + Navigator.pop(c); + setState(() => filter = f); + }, + ); + final names = folders.keys.toList()..sort(); + final tagNames = tags.keys.toList()..sort(); + return DraggableScrollableSheet( + expand: false, + initialChildSize: .6, + maxChildSize: .92, + builder: (_, scroll) => ListView(controller: scroll, children: [ + item((kind: 'all', value: null), const Icon(Icons.notes), 'All notes', live.length), + if (pinned > 0) item((kind: 'pinned', value: null), const Icon(Icons.push_pin_outlined), 'Pinned', pinned), + if (copies > 0) + item((kind: 'conflicts', value: null), const Icon(Icons.warning_amber, color: Color(0xFFFF9A4D)), + 'Conflicted copies', copies), + if (names.isNotEmpty) const _Cap('Folders'), + for (final f in names) + item((kind: 'folder', value: f), const Icon(Icons.folder_outlined, size: 20), f.split('/').last, folders[f]!, + depth: '/'.allMatches(f).length), + if (tagNames.isNotEmpty) ...[ + const _Cap('Tags'), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 14), + child: Wrap(spacing: 6, runSpacing: 6, children: [ + for (final t in tagNames) + ChoiceChip( + label: Text('#$t ${tags[t]}'), + selected: filter == (kind: 'tag', value: t), + onSelected: (_) { + Navigator.pop(c); + setState(() => filter = (kind: 'tag', value: t)); + }, + ), + ]), + ), + ], + const Divider(color: card2), + item((kind: 'trash', value: null), const Icon(Icons.delete_outline), 'Trash', all.length - live.length), + const SizedBox(height: 12), + ]), + ); + }, + ); + } + + /// Long-press: pin, move, trash (or, in the trash: restore, delete for good). + void _actions(Note n) { + final s = widget.sync.store; + showModalBottomSheet( + context: context, + backgroundColor: card, + builder: (c) => SafeArea(child: Column(mainAxisSize: MainAxisSize.min, children: [ + ListTile(title: Text(n.title, style: const TextStyle(fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis)), + if (n.trashed == null) ...[ + ListTile( + leading: Icon(n.pinned ? Icons.push_pin : Icons.push_pin_outlined), + title: Text(n.pinned ? 'Unpin' : 'Pin to the top'), + onTap: () { + Navigator.pop(c); + setNote(s, n.id, {'pinned': n.pinned ? 0 : 1}); + widget.sync.changed(); + }, + ), + ListTile( + leading: const Icon(Icons.drive_file_move_outlined), + title: const Text('Move to folder…'), + onTap: () async { + Navigator.pop(c); + final f = await askFolder(context, widget.sync, n.folder); + if (f != null) { + setNote(s, n.id, {'folder': cleanFolder(f)}); + widget.sync.changed(); + } + }, + ), + ListTile( + leading: const Icon(Icons.delete_outline), + title: const Text('Move to the trash'), + onTap: () { + Navigator.pop(c); + trashNote(s, n.id, true); + widget.sync.changed(); + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: const Text('Moved to the trash'), + persist: false, // with an action Flutter keeps it up until tapped + action: SnackBarAction(label: 'Undo', onPressed: () { + trashNote(s, n.id, false); + widget.sync.changed(); + }), + )); + }, + ), + ] else ...[ + ListTile( + leading: const Icon(Icons.restore), + title: const Text('Restore'), + onTap: () { + Navigator.pop(c); + trashNote(s, n.id, false); + widget.sync.changed(); + }, + ), + ListTile( + leading: const Icon(Icons.delete_forever, color: bad), + title: const Text('Delete for good', style: TextStyle(color: bad)), + onTap: () { + Navigator.pop(c); + deleteNote(s, n.id); + widget.sync.changed(); + }, + ), + ], + ])), + ); + } + + Future _renameFolder() async { + final old = filter.value!; + final to = await askText(context, 'Rename folder', old, hint: 'a/b for a sub-folder'); + if (to == null || cleanFolder(to).isEmpty || cleanFolder(to) == old) return; + renameFolder(widget.sync.store, old, to); + widget.sync.changed(); + setState(() => filter = (kind: 'folder', value: cleanFolder(to))); + } + + void _emptyTrash() => showDialog( + context: context, + builder: (d) => AlertDialog( + title: const Text('Empty the trash?'), + content: const Text('The notes in it are deleted on every device.'), + actions: [ + TextButton(onPressed: () => Navigator.pop(d), child: const Text('Cancel')), + TextButton(onPressed: () { + Navigator.pop(d); + emptyTrash(widget.sync.store); + widget.sync.changed(); + }, child: const Text('Delete them', style: TextStyle(color: bad))), + ], + ), + ); + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: widget.sync, + builder: (context, _) { + final all = allNotes(widget.sync.store); + final list = shown(all); + return Scaffold( + appBar: AppBar( + title: InkWell( + onTap: () => _where(all), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Flexible(child: Text(label, overflow: TextOverflow.ellipsis)), + const Icon(Icons.arrow_drop_down), + ]), + ), + actions: [ + ...widget.actions, + if (filter.kind == 'folder' || filter.kind == 'trash') + PopupMenuButton( + icon: const Icon(Icons.more_vert), + color: card2, + onSelected: (k) => k == 'rename' ? _renameFolder() : _emptyTrash(), + itemBuilder: (_) => [ + if (filter.kind == 'folder') const PopupMenuItem(value: 'rename', child: Text('Rename folder')), + if (filter.kind == 'trash') const PopupMenuItem(value: 'empty', child: Text('Empty the trash')), + ], + ), + ], + ), + floatingActionButton: filter.kind == 'trash' + ? null + : FloatingActionButton( + backgroundColor: accent, + foregroundColor: bg, + tooltip: 'New note', + onPressed: () => _open(null), + child: const Icon(Icons.add), + ), + body: Column(children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 4, 12, 6), + child: TextField( + controller: search, + onChanged: (_) => setState(() {}), + decoration: InputDecoration( + isDense: true, + hintText: 'Search notes', + prefixIcon: const Icon(Icons.search, size: 20), + suffixIcon: search.text.isEmpty ? null : IconButton( + icon: const Icon(Icons.close, size: 18), + onPressed: () => setState(search.clear), + ), + filled: true, + fillColor: card, + border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none), + ), + ), + ), + Expanded( + child: list.isEmpty + ? Center(child: Text( + search.text.isNotEmpty ? 'Nothing matches.' + : filter.kind == 'trash' ? 'The trash is empty.' : 'No notes here yet — + to write one.', + style: const TextStyle(color: muted))) + : ListView.builder( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 88), + itemCount: list.length, + itemBuilder: (_, i) => _tile(list[i]), + ), + ), + ]), + ); + }, + ); + + Widget _tile(Note n) { + final snip = noteSnippet(n.body), tags = n.tags.take(4).toList(); + final showFolder = filter.kind != 'folder' && n.folder.isNotEmpty; + return Card( + margin: const EdgeInsets.only(bottom: 8), + child: InkWell( + borderRadius: BorderRadius.circular(12), + onTap: () => _open(n), + onLongPress: () => _actions(n), + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 14, 10), + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Row(children: [ + if (n.pinned && filter.kind != 'trash') + const Padding(padding: EdgeInsets.only(right: 4), child: Icon(Icons.push_pin, size: 15, color: accent)), + if (n.origin != null) + const Padding(padding: EdgeInsets.only(right: 4), + child: Icon(Icons.warning_amber, size: 16, color: Color(0xFFFF9A4D))), + Expanded(child: Text(n.title, maxLines: 1, overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))), + const SizedBox(width: 8), + Text(when(n.trashed ?? n.updated), style: const TextStyle(color: muted, fontSize: 12)), + ]), + if (snip.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 3), + child: Text(snip, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 13.5)), + ), + if (showFolder || tags.isNotEmpty) + Padding( + padding: const EdgeInsets.only(top: 5), + child: Wrap(spacing: 10, children: [ + if (showFolder) Text('▸ ${n.folder}', style: const TextStyle(color: Color(0xFF5D6472), fontSize: 12)), + for (final t in tags) Text('#$t', style: const TextStyle(color: Color(0xFF5CC8FF), fontSize: 12)), + ]), + ), + ]), + ), + ), + ); + } +} + +class _Cap extends StatelessWidget { + const _Cap(this.text); + final String text; + @override + Widget build(BuildContext context) => Padding( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 4), + child: Text(text.toUpperCase(), style: const TextStyle(color: muted, fontSize: 12, fontWeight: FontWeight.bold)), + ); +} + +/// "14:05" today, "3 Oct" this year, else "3 Oct 2025". +String when(String iso) { + final d = DateTime.tryParse(iso)?.toLocal(); + if (d == null) return ''; + final now = DateTime.now(); + const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + if (d.year == now.year && d.month == now.month && d.day == now.day) { + return '${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}'; + } + return '${d.day} ${months[d.month - 1]}${d.year == now.year ? '' : ' ${d.year}'}'; +} + +/// A one-line text dialog → the text, or null when cancelled. +Future askText(BuildContext context, String title, String value, {String? hint}) { + final c = TextEditingController(text: value); + return showDialog( + context: context, + builder: (d) => AlertDialog( + title: Text(title), + content: TextField(controller: c, autofocus: true, decoration: InputDecoration(hintText: hint), + onSubmitted: (v) => Navigator.pop(d, v)), + actions: [ + TextButton(onPressed: () => Navigator.pop(d), child: const Text('Cancel')), + TextButton(onPressed: () => Navigator.pop(d, c.text), child: const Text('OK')), + ], + ), + ); +} + +/// Pick a folder (the ones there are, or type a new one; '' = none) → null when cancelled. +Future askFolder(BuildContext context, SyncService sync, String current) { + final names = {for (final n in allNotes(sync.store)) if (n.trashed == null && n.folder.isNotEmpty) n.folder}.toList()..sort(); + return showModalBottomSheet( + context: context, + backgroundColor: card, + isScrollControlled: true, + builder: (c) => SafeArea(child: ConstrainedBox( + constraints: BoxConstraints(maxHeight: MediaQuery.of(c).size.height * .7), + child: ListView(shrinkWrap: true, children: [ + const ListTile(title: Text('Move to folder', style: TextStyle(fontWeight: FontWeight.bold))), + ListTile( + leading: const Icon(Icons.create_new_folder_outlined), + title: const Text('New folder…'), + onTap: () async { + final f = await askText(c, 'New folder', current, hint: 'a/b for a sub-folder'); + if (c.mounted) Navigator.pop(c, f); + }, + ), + ListTile( + leading: const Icon(Icons.folder_off_outlined), + title: const Text('No folder'), + selected: current.isEmpty, + selectedColor: accent, + onTap: () => Navigator.pop(c, ''), + ), + for (final f in names) + ListTile( + leading: const Icon(Icons.folder_outlined), + title: Text(f), + selected: f == current, + selectedColor: accent, + onTap: () => Navigator.pop(c, f), + ), + ]), + )), + ); +} diff --git a/app/lib/sync/client.dart b/app/lib/sync/client.dart new file mode 100644 index 0000000..ec45ed4 --- /dev/null +++ b/app/lib/sync/client.dart @@ -0,0 +1,122 @@ +// Talking to the dash-sync mailbox (PROTOCOL.md "HTTP"): join with a device token + the +// passphrase, then pull everyone else's batches and push ours — what the dashboard's +// sync.py does every 5 minutes. The token and the data key live in Android's secure storage +// (Keystore-backed); the rest (clock, how far we've read) in the store. +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:http/http.dart' as http; + +import 'crypto.dart'; +import 'store.dart'; + +const chunk = 2000; // changes per batch, like sync.py + +class SyncSettings { + SyncSettings({required this.server, required this.token, required this.account, required this.name, + required this.device, required this.key}); + + final String server, token, account, name, device; + final Uint8List key; + + static const _storage = FlutterSecureStorage(); + + static Future load() async { + final j = await _storage.read(key: 'sync'); + if (j == null) return null; + final m = jsonDecode(j) as Map; + return SyncSettings(server: m['server'], token: m['token'], account: m['account'], name: m['name'], + device: m['device'], key: base64Decode(m['key'])); + } + + Future save() => _storage.write( + key: 'sync', + value: jsonEncode({'server': server, 'token': token, 'account': account, 'name': name, + 'device': device, 'key': base64Encode(key)})); + + static Future forget() => _storage.delete(key: 'sync'); +} + +class SyncError implements Exception { + SyncError(this.message); + final String message; + @override + String toString() => message; +} + +Future> _call(String server, String token, String method, String path, + {Uint8List? body}) async { + final uri = Uri.parse(server.replaceAll(RegExp(r'/+$'), '') + path); + final headers = {'Authorization': 'Bearer $token', 'Accept': 'application/json'}; + late http.Response r; + try { + r = method == 'POST' + ? await http.post(uri, headers: {...headers, 'Content-Type': 'application/octet-stream'}, body: body) + : await http.get(uri, headers: headers); + } catch (e) { + throw SyncError("Can't reach the server ($e)"); + } + final j = r.body.isEmpty ? {} : jsonDecode(r.body) as Map; + if (r.statusCode >= 400) throw SyncError('Server: ${r.statusCode} ${j['error'] ?? r.body}'); + return j; +} + +/// First start: check the token, fetch the wrapped key, unlock it with the passphrase (or take +/// the recovery key). The server must already have a key — the dashboard makes it (sync.py setup). +Future join(String server, String token, {String? passphrase, String? recovery}) async { + final hello = await _call(server, token, 'GET', '/v1/hello'); + final Uint8List key; + if (recovery != null && recovery.trim().isNotEmpty) { + key = SyncCrypto.fromRecovery(recovery); + } else { + final Map wrapped; + try { + wrapped = await _call(server, token, 'GET', '/v1/key'); + } on SyncError catch (e) { + if (e.message.contains('404')) throw SyncError('No key on the server yet — set up the dashboard first.'); + rethrow; + } + key = await SyncCrypto.unwrap(wrapped, passphrase ?? ''); + } + return SyncSettings(server: server, token: token, account: hello['account'], name: hello['device'], + device: SyncStore.randomId().substring(0, 12), key: key); +} + +class SyncResult { + int batches = 0, applied = 0, skipped = 0, pushed = 0; + @override + String toString() => '$batches batches in ($applied applied, $skipped skipped), $pushed changes out'; +} + +/// Pull everyone else's batches since the last one read, then push ours. +Future runSync(SyncSettings s, SyncStore store, SyncCrypto crypto) async { + final res = SyncResult(); + while (true) { + final j = await _call(s.server, s.token, 'GET', '/v1/batches?after=${store.meta('pulled')}&limit=50'); + final batches = (j['batches'] as List).cast>(); + if (batches.isEmpty) break; + for (final b in batches) { + if (b['device'] != s.name) { + final batch = crypto.openBatch(s.key, base64Decode(b['blob'] as String), s.account); + if (batch['dev'] != s.device) { + final st = store.apply(batch['changes'] as List); + res.applied += st['applied']!; + res.skipped += st['skipped']!; + } + res.batches++; + } + store.setMeta('pulled', b['seq'] as int); // only after the batch is in (applying again is harmless) + } + } + final (items, mark) = store.changes(); + for (var i = 0; i < items.length; i += chunk) { + final part = items.sublist(i, i + chunk > items.length ? items.length : i + chunk); + final blob = crypto.sealBatch(s.key, + {'v': 1, 'dev': s.device, 'made': DateTime.now().millisecondsSinceEpoch, 'changes': part}, s.account); + await _call(s.server, s.token, 'POST', '/v1/batches', body: blob); + res.pushed += part.length; + } + if (items.isNotEmpty) store.markPushed(mark); + return res; +} diff --git a/app/lib/sync/crypto.dart b/app/lib/sync/crypto.dart new file mode 100644 index 0000000..9db133c --- /dev/null +++ b/app/lib/sync/crypto.dart @@ -0,0 +1,117 @@ +// Encryption for dash-sync (PROTOCOL.md "Keys" + "A batch"), byte for byte what the dashboard's +// sync.py does with PyNaCl: a batch = "DS1\0" + 24-byte nonce + XChaCha20-Poly1305-IETF(data key, +// nonce, zlib(JSON), ad = "dash-sync/1/"); the data key sits on the server wrapped with +// Argon2id(passphrase). Argon2id with 64 MB takes a second or two, so it runs in its own isolate. +import 'dart:convert'; +import 'dart:io'; +import 'dart:isolate'; +import 'dart:typed_data'; + +import 'package:sodium/sodium_sumo.dart'; + +const _magic = [0x44, 0x53, 0x31, 0x00]; // "DS1\0" +const _keyAd = 'dash-sync/key/1'; + +class SyncCrypto { + SyncCrypto._(this._sodium); + + static Future create() async => SyncCrypto._(await SodiumSumoInit.init()); + + final SodiumSumo _sodium; + + Aead get _aead => _sodium.crypto.aeadXChaCha20Poly1305IETF; + + Uint8List _ad(String account) => utf8.encode('dash-sync/1/$account'); + + /// JSON → zlib → sealed batch, ready to POST. + Uint8List sealBatch(Uint8List key, Map batch, String account) { + final plain = Uint8List.fromList(ZLibCodec(level: 6).encode(utf8.encode(jsonEncode(batch)))); + final nonce = _sodium.randombytes.buf(24); + final k = SecureKey.fromList(_sodium, key); + try { + final box = _aead.encrypt(message: plain, nonce: nonce, key: k, additionalData: _ad(account)); + return Uint8List.fromList([..._magic, ...nonce, ...box]); + } finally { + k.dispose(); + } + } + + /// A sealed batch → its JSON. Throws on a wrong key / account or a damaged batch. + Map openBatch(Uint8List key, Uint8List blob, String account) { + if (blob.length < 28 + 16 || !_listEq(blob.sublist(0, 4), _magic)) { + throw const FormatException('not a sync batch'); + } + final k = SecureKey.fromList(_sodium, key); + try { + final plain = _aead.decrypt( + cipherText: blob.sublist(28), nonce: blob.sublist(4, 28), key: k, additionalData: _ad(account)); + return jsonDecode(utf8.decode(ZLibCodec().decode(plain))) as Map; + } finally { + k.dispose(); + } + } + + /// The data key from the server's wrapped key + the passphrase (in a background isolate). + /// Throws [WrongPassphrase]. + static Future unwrap(Map w, String passphrase) => + Isolate.run(() async => _unwrap(await SodiumSumoInit.init(), w, passphrase)); + + static Uint8List _unwrap(SodiumSumo s, Map w, String passphrase) { + if (w['kdf'] != 'argon2id13') throw FormatException('unknown kdf ${w['kdf']}'); + final kek = s.crypto.pwhash( + outLen: 32, + password: Int8List.fromList(utf8.encode(passphrase)), + salt: base64Decode(w['salt'] as String), + opsLimit: w['ops'] as int, + memLimit: w['mem'] as int, + alg: CryptoPwhashAlgorithm.argon2id13, + ); + try { + // a copy: what libsodium returns is a view on native memory that's freed with the isolate + return Uint8List.fromList(s.crypto.aeadXChaCha20Poly1305IETF.decrypt( + cipherText: base64Decode(w['box'] as String), + nonce: base64Decode(w['nonce'] as String), + key: kek, + additionalData: utf8.encode(_keyAd), + )); + } on SodiumException { + throw const WrongPassphrase(); + } finally { + kek.dispose(); + } + } + + /// The recovery key ("ABCD-EFGH-…", base32 of the data key) → the data key. + static Uint8List fromRecovery(String code) { + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; + final s = code.replaceAll(RegExp(r'[\s-]'), '').toUpperCase(); + final out = []; + var buf = 0, bits = 0; + for (final ch in s.split('')) { + final v = alphabet.indexOf(ch); + if (v < 0) throw const FormatException("that's not a recovery key"); + buf = (buf << 5) | v; + bits += 5; + if (bits >= 8) { + bits -= 8; + out.add((buf >> bits) & 0xff); + } + } + if (out.length != 32) throw const FormatException("that's not a recovery key"); + return Uint8List.fromList(out); + } + + static bool _listEq(List a, List b) { + if (a.length != b.length) return false; + for (var i = 0; i < a.length; i++) { + if (a[i] != b[i]) return false; + } + return true; + } +} + +class WrongPassphrase implements Exception { + const WrongPassphrase(); + @override + String toString() => 'Wrong passphrase'; +} diff --git a/app/lib/sync/gb_relay.dart b/app/lib/sync/gb_relay.dart new file mode 100644 index 0000000..8d46f92 --- /dev/null +++ b/app/lib/sync/gb_relay.dart @@ -0,0 +1,145 @@ +// The band's data from Gadgetbridge to the dashboard, through the sync (no Syncthing): Gadgetbridge's +// database export on this phone (Gadgetbridge ▸ Settings ▸ Automations ▸ Auto export), picked once, +// is read at every sync (the app's and the background task's, background.dart) when it changed; the new rows of the six tables the dashboard's gb.py reads +// (only those columns) go into the store as health. rows — ids = the band's timestamps, as +// gb.RELAY_SYNC — and travel like any change. The Pi imports them (gb.import_relay). +// +// Incremental like gb.py: rows from the newest relayed minute minus OVERLAP (the band hands over +// sleep and late minutes after the fact); an unchanged row isn't put again. Rows older than KEEP +// days that were sent are dropped here without a delete marker — the Pi keeps them. +// With them goes the phone's time zone (health.RELAY_INFO "tz"): the dashboard reads the band's times in it +// unless Settings ▸ Health sets one. +import 'dart:io'; + +import 'package:gb_export/gb_export.dart'; +import 'package:path_provider/path_provider.dart'; +import 'package:sqlite3/sqlite3.dart'; + +import 'store.dart'; + +const overlapS = 2 * 86400; +const keepDays = 14; + +/// table → (id prefix, timestamp column, timestamp in ms?, columns sent) — gb.RELAY_SCHEMA / RELAY_SYNC +const relayTables = { + 'XIAOMI_ACTIVITY_SAMPLE': ('a', 'TIMESTAMP', false, ['TIMESTAMP', 'HEART_RATE', 'STEPS', 'DISTANCE_CM']), + 'XIAOMI_DAILY_SUMMARY_SAMPLE': ('d', 'TIMESTAMP', true, ['TIMESTAMP', 'HR_RESTING']), + 'XIAOMI_SLEEP_STAGE_SAMPLE': ('s', 'TIMESTAMP', true, ['TIMESTAMP', 'STAGE']), + 'XIAOMI_SLEEP_TIME_SAMPLE': ('t', 'TIMESTAMP', true, ['TIMESTAMP', 'WAKEUP_TIME']), + 'BASE_ACTIVITY_SUMMARY': ('w', 'START_TIME', true, ['START_TIME', 'END_TIME', 'ACTIVITY_KIND', 'OVERRIDE_ACTIVITY_KIND']), + 'XIAOMI_MANUAL_SAMPLE': ('m', 'TIMESTAMP', true, ['TIMESTAMP', 'TYPE', 'VALUE']), +}; + +class GbRelay { + GbRelay(this.store); + final SyncStore store; + + String? get uri => store.metaText('gb_uri'); + String? get lastResult => store.metaText('gb_result'); + int get lastRun => store.meta('gb_run'); // ms + + /// The system file picker → remember the export (null = cancelled). + Future pick() async { + final u = await pickExport(); + if (u == null) return false; + store.setMetaText('gb_uri', u); + store.setMetaText('gb_stamp', null); // read it at the next sync + return true; + } + + void forget() { + store.setMetaText('gb_uri', null); + store.setMetaText('gb_stamp', null); + } + + /// Read the export if it changed → rows put (0 = nothing new; null = no export picked). + Future run() async { + final u = uri; + if (u == null) return null; + final info = await exportInfo(u); + if (info == null) { + _done('can\'t open the export — choose it again'); + return 0; + } + await _zone(); + final stamp = '${info['size']}:${info['modified']}'; + var put = 0; + if (stamp != store.metaText('gb_stamp')) { + final tmp = '${(await getTemporaryDirectory()).path}/gb_export.db'; + if (!await copyExport(u, tmp)) { + _done('can\'t read the export'); + return 0; + } + try { + put = _read(tmp); + store.setMetaText('gb_stamp', stamp); + _done('$put new or changed rows from the export of ${_when(info['modified']!)}'); + } catch (e) { + _done('the export couldn\'t be read: $e'); + } finally { + for (final f in [tmp, '$tmp-wal', '$tmp-shm', '$tmp-journal']) { + final x = File(f); + if (x.existsSync()) x.deleteSync(); + } + } + } + _trim(); + return put; + } + + int _read(String path) { + final gb = sqlite3.open(path, mode: OpenMode.readOnly); + var put = 0, newest = store.meta('gb_last'); + final since = newest == 0 ? 0 : newest - overlapS; + try { + store.db.execute('BEGIN'); + for (final MapEntry(key: t, value: (prefix, ts, ms, cols)) in relayTables.entries) { + final have = gb.select("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?", [t]); + if (have.isEmpty) continue; + for (final r in gb.select('SELECT ${cols.join(', ')} FROM $t WHERE $ts >= ? ORDER BY $ts', [ms ? since * 1000 : since])) { + final data = {for (final c in cols) c: r[c]}; + final id = t == 'XIAOMI_MANUAL_SAMPLE' ? '$prefix:${r['TIMESTAMP']}:${r['TYPE']}' : '$prefix:${r[ts]}'; + final old = store.row('health.$t', id); + if (old != null && cols.every((c) => old[c] == data[c])) continue; + store.put('health.$t', id, data); + put++; + if (t == 'XIAOMI_ACTIVITY_SAMPLE' && (r[ts] as int) > newest) newest = r[ts] as int; + } + } + store.setMeta('gb_last', newest); + store.db.execute('COMMIT'); + } catch (_) { + store.db.execute('ROLLBACK'); + rethrow; + } finally { + gb.close(); + } + return put; + } + + /// The phone's time zone → health.RELAY_INFO (only when it changed: a trip abroad, the clocks moved by hand). + Future _zone() async { + final z = await timeZone(); + if (z == null || z.isEmpty || store.row('health.RELAY_INFO', 'i:tz')?['v'] == z) return; + store.put('health.RELAY_INFO', 'i:tz', {'k': 'tz', 'v': z}); + } + + /// Drop rows older than keepDays that were already sent — here only (no delete marker). + void _trim() { + final cut = DateTime.now().millisecondsSinceEpoch ~/ 1000 - keepDays * 86400, pushed = store.meta('pushed'); + for (final MapEntry(key: t, value: (_, ts, ms, _)) in relayTables.entries) { + store.db.execute("DELETE FROM rec WHERE t = ? AND h <= ? AND json_extract(data, '\$.$ts') < ?", + ['health.$t', pushed, ms ? cut * 1000 : cut]); + } + } + + void _done(String result) { + store.setMetaText('gb_result', result); + store.setMeta('gb_run', DateTime.now().millisecondsSinceEpoch); + } + + static String _when(int ms) { + final d = DateTime.fromMillisecondsSinceEpoch(ms); + return '${d.day}.${d.month}. ${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}'; + } +} diff --git a/app/lib/sync/kick.dart b/app/lib/sync/kick.dart new file mode 100644 index 0000000..950f5ff --- /dev/null +++ b/app/lib/sync/kick.dart @@ -0,0 +1,39 @@ +// "Sync now" to the dashboard over the home network (the dashboard's sync.kick): right after the +// band's rows went out, the Pi pulls them, imports them, rewrites the Health summaries and pushes +// them at once — then the app pulls again. Away from home the Pi doesn't answer and nothing changes +// (the usual 5-minute / hourly rhythm). The message is sealed with the data key, so only a device +// of this account can send one. +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/io_client.dart'; + +import 'client.dart'; +import 'crypto.dart'; +import 'store.dart'; + +/// The dashboard on the home network, e.g. http://192.168.1.50:8080: the Sync page (store meta pi_url), +/// else the build's --dart-define=PI_URL=… (tool/publish.env); empty = no "sync now", the usual rhythm only. +String piUrl(SyncStore store) => + (store.metaText('pi_url') ?? const String.fromEnvironment('PI_URL')).trim().replaceAll(RegExp(r'/+$'), ''); +const _connect = Duration(seconds: 3); // not home → give up quickly +const _answer = Duration(minutes: 3); // the Pi 3: import + summaries ≈ 1 min + +/// → true when the Pi sent something back (pull now). +Future kickPi(SyncSettings s, SyncStore store, SyncCrypto crypto) async { + final pi = piUrl(store); + if (pi.isEmpty) return false; + final blob = crypto.sealBatch(s.key, {'kick': DateTime.now().millisecondsSinceEpoch}, s.account); + final client = IOClient(HttpClient()..connectionTimeout = _connect); + try { + final r = await client + .post(Uri.parse('$pi/api/sync/kick'), headers: {'Content-Type': 'application/octet-stream'}, body: blob) + .timeout(_answer); + if (r.statusCode != 200) return false; + return ((jsonDecode(r.body) as Map)['pushed'] ?? 0) > 0; + } catch (_) { + return false; + } finally { + client.close(); + } +} diff --git a/app/lib/sync/store.dart b/app/lib/sync/store.dart new file mode 100644 index 0000000..de51dbe --- /dev/null +++ b/app/lib/sync/store.dart @@ -0,0 +1,225 @@ +// The phone's copy of the synced data, kept in the wire format of PROTOCOL.md: one row per +// (table, id) with its stamp, device and the columns as JSON — references are already ids there, +// so nothing is translated (the dashboard's syncdb.py turns them into its integer keys; we don't +// need to). The merge rules are syncdb.apply's: the later (stamp, device) wins per row, deletes +// leave a marker, a change older than a marker is skipped, the clock only moves forward. +// +// rec (t "food.entry", u id, h stamp, d device, data JSON) +// tomb (t, u, h, d) a delete marker +// meta (k, v) clock, pushed (my newest stamp sent), pulled (server seq) +import 'dart:convert'; +import 'dart:math'; + +import 'package:sqlite3/sqlite3.dart'; + +class SyncStore { + SyncStore(String path, this.device) : db = sqlite3.open(path) { + db.execute('PRAGMA journal_mode = WAL'); + db.execute('PRAGMA busy_timeout = 10000'); // the app and the background sync share the file + db.execute(''' + CREATE TABLE IF NOT EXISTS rec (t TEXT NOT NULL, u TEXT NOT NULL, h INTEGER NOT NULL, d TEXT NOT NULL, + data TEXT NOT NULL, PRIMARY KEY (t, u)) WITHOUT ROWID; + CREATE TABLE IF NOT EXISTS tomb (t TEXT NOT NULL, u TEXT NOT NULL, h INTEGER NOT NULL, d TEXT NOT NULL, + PRIMARY KEY (t, u)) WITHOUT ROWID; + CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v) WITHOUT ROWID; + CREATE INDEX IF NOT EXISTS rec_mine ON rec (d, h); + CREATE INDEX IF NOT EXISTS tomb_mine ON tomb (d, h); + '''); + } + + final Database db; + final String device; // this device's id (12 hex), in every change it makes + + int meta(String k) => (db.select('SELECT v FROM meta WHERE k = ?', [k]).firstOrNull?['v'] as int?) ?? 0; + + void setMeta(String k, int v) => db.execute('INSERT OR REPLACE INTO meta VALUES (?, ?)', [k, v]); + + String? metaText(String k) => db.select('SELECT v FROM meta WHERE k = ?', [k]).firstOrNull?['v'] as String?; + + void setMetaText(String k, String? v) => + v == null ? db.execute('DELETE FROM meta WHERE k = ?', [k]) : db.execute('INSERT OR REPLACE INTO meta VALUES (?, ?)', [k, v]); + + /// Tables whose rows are documents (syncdb.py "fork"): their text columns, versioned by rev / revs. + /// Two versions written at the same time are both kept — the loser as "copy:" + its rev. + static const forks = {'notes.note': ['body', 'updated']}; + + /// Tables the phone never reads — the dashboards' raw ActivityWatch data (every window, every minute of + /// typing): not kept. What the app shows of it comes as the Pi's blocks (workload.act). + static const skip = ['activity.']; + + static bool newer(int h, String d, int? lh, String? ld) => + h != (lh ?? 0) ? h > (lh ?? 0) : d.compareTo(ld ?? '') > 0; + + /// A new local stamp: never below the last one + 1 (PROTOCOL.md "Stamps"). + int _tick() { + final h = max(meta('clock') + 1, DateTime.now().millisecondsSinceEpoch); + setMeta('clock', h); + return h; + } + + // ---- reading ----------------------------------------------------------------------------- + + /// Every live row of a table ("food.entry") as {_u, _h (its change stamp), …columns}. + List> rows(String t, {String? where, List args = const []}) => [ + for (final r in db.select( + 'SELECT u, h, data FROM rec WHERE t = ?${where == null ? '' : ' AND ($where)'}', [t, ...args])) + {'_u': r['u'], '_h': r['h'], ...jsonDecode(r['data'] as String) as Map} + ]; + + Map? row(String t, String u) { + final r = db.select('SELECT data FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull; + return r == null ? null : {'_u': u, ...jsonDecode(r['data'] as String) as Map}; + } + + Map counts() => { + for (final r in db.select('SELECT t, count(*) AS n FROM rec GROUP BY t ORDER BY t')) + r['t'] as String: r['n'] as int + }; + + // ---- writing here ------------------------------------------------------------------------ + + /// Save a row made / changed on this device (the whole row: columns we don't show are kept + /// by passing the row as read). `u` = its id: a natural one ("day:2026-10-20") or random. + void put(String t, String u, Map data) { + final clean = Map.of(data) + ..remove('_u') + ..remove('_h'); + db.execute('INSERT OR REPLACE INTO rec VALUES (?, ?, ?, ?, ?)', [t, u, _tick(), device, jsonEncode(clean)]); + } + + /// Has another device seen this row as it is (it came from one, or went out)? + bool known(String t, String u) { + final r = db.select('SELECT h, d FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull; + return r == null || r['d'] != device || (r['h'] as int) <= meta('pushed'); + } + + void delete(String t, String u) { + final h = _tick(); + db.execute('DELETE FROM rec WHERE t = ? AND u = ?', [t, u]); + db.execute('INSERT OR REPLACE INTO tomb VALUES (?, ?, ?, ?)', [t, u, h, device]); + } + + /// Drop rows of [t] whose JSON [field] is below [before] — here only, no delete marker (the other side + /// keeps them): only rows another device made, or ours already sent. + void dropOld(String t, String field, num before) => db.execute( + "DELETE FROM rec WHERE t = ? AND json_extract(data, '\$.$field') < ? AND (d != ? OR h <= ?)", + [t, before, device, meta('pushed')]); + + static String randomId() { + final r = Random.secure(); + return List.generate(16, (_) => r.nextInt(256).toRadixString(16).padLeft(2, '0')).join(); + } + + // ---- sync --------------------------------------------------------------------------------- + + /// This device's changes since the last push: (changes, mark) — markPushed(mark) once sent. + (List>, int) changes() { + final since = meta('pushed'); + var mark = since; + final out = >[]; + final items = <(int, Map)>[]; + for (final r in db.select('SELECT t, u, h, d, data FROM rec WHERE d = ? AND h > ?', [device, since])) { + items.add((r['h'] as int, + {'t': r['t'], 'u': r['u'], 'h': r['h'], 'd': r['d'], 'row': jsonDecode(r['data'] as String)})); + } + for (final r in db.select('SELECT t, u, h, d FROM tomb WHERE d = ? AND h > ?', [device, since])) { + items.add((r['h'] as int, {'t': r['t'], 'u': r['u'], 'h': r['h'], 'd': r['d'], 'del': true})); + } + items.sort((a, b) => a.$1.compareTo(b.$1)); + for (final (h, c) in items) { + out.add(c); + mark = max(mark, h); + } + return (out, mark); + } + + void markPushed(int mark) => setMeta('pushed', max(meta('pushed'), mark)); + + /// Another device's changes → {applied, skipped}. Rows first, then the deletes (like syncdb). + Map apply(List changes) { + final stats = {'applied': 0, 'skipped': 0}; + if (changes.isEmpty) return stats; + db.execute('BEGIN IMMEDIATE'); + try { + var top = meta('clock'); + for (final c in changes.cast>()) { + top = max(top, c['h'] as int); + } + setMeta('clock', top); // the clock moves past what arrives + for (final pass in [false, true]) { + for (final c in changes.cast>()) { + if ((c['del'] == true) != pass) continue; + final t = c['t'] as String, u = c['u'] as String, h = c['h'] as int, d = c['d'] as String; + if (skip.any(t.startsWith)) { + stats['skipped'] = stats['skipped']! + 1; + continue; + } + final cur = db.select('SELECT h, d, data FROM rec WHERE t = ? AND u = ?', [t, u]).firstOrNull; + final tomb = db.select('SELECT h, d FROM tomb WHERE t = ? AND u = ?', [t, u]).firstOrNull; + if (pass) { + if (tomb == null || newer(h, d, tomb['h'] as int, tomb['d'] as String)) { + db.execute('INSERT OR REPLACE INTO tomb VALUES (?, ?, ?, ?)', [t, u, h, d]); + } + if (cur != null && newer(h, d, cur['h'] as int, cur['d'] as String)) { + db.execute('DELETE FROM rec WHERE t = ? AND u = ?', [t, u]); + stats['applied'] = stats['applied']! + 1; + } else { + stats['skipped'] = stats['skipped']! + 1; + } + } else { + if (cur != null && forks.containsKey(t) && + (tomb == null || newer(h, d, tomb['h'] as int, tomb['d'] as String)) && + _fork(t, u, h, d, (c['row'] as Map).cast(), cur)) { + stats['applied'] = stats['applied']! + 1; + continue; + } + final beaten = (tomb != null && !newer(h, d, tomb['h'] as int, tomb['d'] as String)) || + (cur != null && !newer(h, d, cur['h'] as int, cur['d'] as String)); + if (beaten) { + stats['skipped'] = stats['skipped']! + 1; + } else { + db.execute('INSERT OR REPLACE INTO rec VALUES (?, ?, ?, ?, ?)', [t, u, h, d, jsonEncode(c['row'])]); + stats['applied'] = stats['applied']! + 1; + } + } + } + } + db.execute('COMMIT'); + } catch (_) { + db.execute('ROLLBACK'); + rethrow; + } + return stats; + } + + /// syncdb._fork: a document row meeting another version of itself → true when settled here, + /// false = go on with the plain last-change-wins (after keeping the loser as a copy). + bool _fork(String t, String u, int h, String d, Map row, Row cur) { + final loc = jsonDecode(cur['data'] as String) as Map; + final mine = loc['rev'] as String?, theirs = row['rev'] as String?; + if (mine == null || theirs == null || mine == theirs) return false; // the same text: only the rest differs + final win = newer(h, d, cur['h'] as int, cur['d'] as String); + final text = [...forks[t]!, 'rev', 'revs']; + List revs(Map m) => ((m['revs'] as String?) ?? '').split(' '); + if (revs(row).contains(mine)) { // written on top of ours: its text + if (win) return false; + final merged = {...loc, for (final k in text) if (row.containsKey(k)) k: row[k]}; + db.execute('UPDATE rec SET data = ? WHERE t = ? AND u = ?', [jsonEncode(merged), t, u]); + return true; + } + if (revs(loc).contains(theirs)) { // ours was written on top of it: our text, their pin / folder — + if (!win) return false; // stamped here, so it goes out (with their stamp our text never would) + final merged = {...row, for (final k in text) if (loc.containsKey(k)) k: loc[k]}; + db.execute('UPDATE rec SET h = ?, d = ?, data = ? WHERE t = ? AND u = ?', [_tick(), device, jsonEncode(merged), t, u]); + return true; + } + // both written at the same time: the later one stays, the other becomes a copy (the same one on every device) + final (lost, lh, ld) = win ? (loc, cur['h'] as int, cur['d'] as String) : (row, h, d); + final cu = 'copy:${lost['rev']}'; + if (db.select('SELECT 1 FROM rec WHERE t = ? AND u = ?', [t, cu]).isEmpty && + db.select('SELECT 1 FROM tomb WHERE t = ? AND u = ?', [t, cu]).isEmpty) { + db.execute('INSERT INTO rec VALUES (?, ?, ?, ?, ?)', [t, cu, lh, ld, jsonEncode({...lost, 'origin': lost['rev']})]); + } + return false; + } +} diff --git a/app/lib/weather/stations.dart b/app/lib/weather/stations.dart new file mode 100644 index 0000000..f7a9d76 --- /dev/null +++ b/app/lib/weather/stations.dart @@ -0,0 +1,115 @@ +// At home: the dashboard's measurement stations (termix sensors), from Weather's home button — each sensor's +// latest values, then temperature and humidity by the hour (24 h / 7 days / 30 days). Synced one way from +// the Pi (plugins/stations: tables now + hourly, db.phone_*), so it shows offline too; the phone keeps +// stationDays of hours. +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import '../widgets/line_chart.dart'; +import 'weather_page.dart' show tempColour; + +const stationDays = 30; +const _colors = [Color(0xFF5CC8FF), Color(0xFFFFB33A), Color(0xFF7FD6A3), Color(0xFFC792EA), Color(0xFFFF8FC8), Color(0xFFFF9A9A)]; + +/// A now row's sensor: its id ("now:2") — device_id is the Pi table's integer key, which the sync leaves out. +int _dev(Map r) => (r['device_id'] as int?) ?? int.parse((r['_u'] as String).split(':')[1]); + +/// Local time in the form the charts use (their day / hour ticks are UTC dates). +DateTime _chartTime(DateTime t) { + final l = t.toLocal(); + return DateTime.utc(l.year, l.month, l.day, l.hour, l.minute); +} + +class StationsPage extends StatefulWidget { + const StationsPage({super.key, required this.sync}); + final SyncService sync; + @override + State createState() => _StationsPageState(); +} + +class _StationsPageState extends State { + int days = 1; + + @override + Widget build(BuildContext context) => Scaffold( + appBar: AppBar(title: const Text('At home')), + body: ListenableBuilder(listenable: widget.sync, builder: (context, _) => _body()), + ); + + Widget _body() { + final store = widget.sync.store; + final now = store.rows('stations.now')..sort((a, b) => _dev(a).compareTo(_dev(b))); + if (now.isEmpty) { + return const Center(child: Padding( + padding: EdgeInsets.all(24), + child: Text('No sensors yet — they come from the dashboard once it has synced.', textAlign: TextAlign.center, + style: TextStyle(color: muted)), + )); + } + final nowS = DateTime.now().millisecondsSinceEpoch ~/ 1000; + final from = DateTime.now().subtract(Duration(days: days)); + final hours = store.rows('stations.hourly', where: "json_extract(data, '\$.t') >= ?", args: [from.millisecondsSinceEpoch ~/ 1000]); + String ago(int t) { + final m = (nowS - t) ~/ 60; + return m < 2 ? 'now' : m < 60 ? '$m min ago' : m < 1440 ? '${m ~/ 60} h ago' : '${m ~/ 1440} d ago'; + } + + List series(String k) => [ + for (var i = 0; i < now.length; i++) + Series(now[i]['name'] as String? ?? '', [ + for (final h in hours.where((h) => h['device_id'] == _dev(now[i]))) + if (h[k] != null) (_chartTime(DateTime.fromMillisecondsSinceEpoch((h['t'] as int) * 1000 + 1800000)), (h[k] as num).toDouble()) + ]..sort((a, b) => a.$1.compareTo(b.$1)), _colors[i % _colors.length]), + ]; + Widget chart(String title, String k, String unit, int decimals) => Card(child: Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 10, 10), + child: Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Text(title, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + const SizedBox(height: 8), + LineChart(height: 170, from: _chartTime(from), to: _chartTime(DateTime.now()), unit: unit, decimals: decimals, series: series(k)), + ]), + )); + + return ListView(padding: const EdgeInsets.fromLTRB(12, 8, 12, 24), children: [ + Card(child: Padding( + padding: const EdgeInsets.fromLTRB(14, 8, 14, 8), + child: Column(children: [ + for (var i = 0; i < now.length; i++) + Padding( + padding: const EdgeInsets.symmetric(vertical: 6), + child: Row(children: [ + Container(width: 9, height: 9, decoration: BoxDecoration(color: _colors[i % _colors.length], shape: BoxShape.circle)), + const SizedBox(width: 10), + Expanded(child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(now[i]['name'] as String? ?? '', style: const TextStyle(fontSize: 15)), + Text(ago(now[i]['t'] as int), style: const TextStyle(color: muted, fontSize: 12)), + ])), + if (now[i]['temp'] != null) + Text('${(now[i]['temp'] as num).toStringAsFixed(1)}°', + style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: tempColour(now[i]['temp'] as num))), + if (now[i]['hum'] != null) + SizedBox(width: 74, child: Row(mainAxisAlignment: MainAxisAlignment.end, children: [ + const Icon(Icons.water_drop_outlined, size: 16, color: Color(0xFF5CC8FF)), + Text(' ${(now[i]['hum'] as num).round()}%', style: const TextStyle(fontSize: 15)), + ])), + ]), + ), + ]), + )), + const SizedBox(height: 8), + Row(children: [ + for (final (d, l) in [(1, '24 h'), (7, '7 days'), (30, '30 days')]) + Padding( + padding: const EdgeInsets.only(right: 8), + child: ChoiceChip(label: Text(l), selected: days == d, showCheckmark: false, + labelStyle: TextStyle(color: days == d ? accent : Colors.white), onSelected: (_) => setState(() => days = d)), + ), + ]), + const SizedBox(height: 8), + chart('Temperature', 'temp', '°C', 1), + const SizedBox(height: 12), + chart('Humidity', 'hum', '%', 0), + ]); + } +} diff --git a/app/lib/weather/weather_page.dart b/app/lib/weather/weather_page.dart new file mode 100644 index 0000000..336a4b7 --- /dev/null +++ b/app/lib/weather/weather_page.dart @@ -0,0 +1,1208 @@ +// Weather (as the dashboard's weather page, plugins/weather): straight from Open-Meteo (free, no key) — +// the same fields as weather.py asks for. The title is the place picker: "Weather · ▾" (Current location — the phone's +// coarse location, its town from OpenStreetMap — the dashboard's places, which stay, added ones, ✕ removes, +// and "Add a place…", Open-Meteo's place search); added places are kept on this phone until the app has synced settings; +// Each +// place's last answer is kept too (store meta), so it shows offline ("saved · …"); fetched again after +// 15 minutes, or pull down. One "now" card (icon + values, details on tap), the sun's arc, the next +// 48 hours, 14 days; icons = the dashboard's. +import 'dart:convert'; +import 'dart:math'; + +import 'package:flutter/material.dart'; +import 'package:http/http.dart' as http; + +import '../app/location.dart'; +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'stations.dart'; + +class Place { + const Place(this.name, this.lat, this.lon); + final String name; + final double lat, lon; +} + +/// The places built in (home first): --dart-define=HOME_PLACES="Home, XX|47.17|24.06;Town, YY|46.77|23.6" +/// (tool/publish.env) — none in a plain build: Current location + the ones added here. Added / removed +/// ones are kept on this phone (store meta wx_places). +final defaultPlaces = [ + for (final p in const String.fromEnvironment('HOME_PLACES').split(';')) + if (p.split('|') case [final name, final lat, final lon] when double.tryParse(lat) != null && double.tryParse(lon) != null) + Place(name.trim(), double.parse(lat), double.parse(lon)), +]; + +const _forecast = 'https://api.open-meteo.com/v1/forecast'; +const _airUrl = 'https://air-quality-api.open-meteo.com/v1/air-quality'; +const _hourly = + 'temperature_2m,apparent_temperature,relative_humidity_2m,dew_point_2m,precipitation_probability,' + 'precipitation,snowfall,weather_code,cloud_cover,visibility,wind_speed_10m,wind_gusts_10m,wind_direction_10m,' + 'uv_index,is_day,pressure_msl'; +const _daily = + 'weather_code,temperature_2m_max,temperature_2m_min,apparent_temperature_max,apparent_temperature_min,' + 'sunrise,sunset,daylight_duration,uv_index_max,precipitation_sum,precipitation_probability_max,precipitation_hours,' + 'wind_speed_10m_max,wind_gusts_10m_max,wind_direction_10m_dominant'; +const _current = + 'temperature_2m,apparent_temperature,relative_humidity_2m,dew_point_2m,weather_code,is_day,cloud_cover,' + 'pressure_msl,wind_speed_10m,wind_gusts_10m,wind_direction_10m,precipitation,visibility,uv_index'; +const _airCurrent = 'european_aqi,pm10,pm2_5,ozone,nitrogen_dioxide'; +const _geocode = 'https://geocoding-api.open-meteo.com/v1/search'; +const refreshAfter = Duration(minutes: 15); + +/// weather.WMO: code → (icon code: assets/weather/d|n.png, description) +const wmo = { + 0: ('01', 'Clear sky'), + 1: ('02', 'Mainly clear'), + 2: ('03', 'Partly cloudy'), + 3: ('04', 'Overcast'), + 45: ('50', 'Fog'), + 48: ('50', 'Rime fog'), + 51: ('09', 'Light drizzle'), + 53: ('09', 'Drizzle'), + 55: ('09', 'Dense drizzle'), + 56: ('09', 'Freezing drizzle'), + 57: ('09', 'Freezing drizzle'), + 61: ('10', 'Light rain'), + 63: ('10', 'Rain'), + 65: ('10', 'Heavy rain'), + 66: ('10', 'Freezing rain'), + 67: ('10', 'Freezing rain'), + 71: ('13', 'Light snow'), + 73: ('13', 'Snow'), + 75: ('13', 'Heavy snow'), + 77: ('13', 'Snow grains'), + 80: ('09', 'Light showers'), + 81: ('09', 'Showers'), + 82: ('09', 'Violent showers'), + 85: ('13', 'Snow showers'), + 86: ('13', 'Heavy snow showers'), + 95: ('11', 'Thunderstorm'), + 96: ('11', 'Thunderstorm, hail'), + 99: ('11', 'Thunderstorm, heavy hail'), +}; + +String wmoText(num? code) => wmo[(code ?? 0).toInt()]?.$2 ?? '—'; + +Widget wxIcon(num? code, {bool day = true, double size = 40}) => + Image.asset('assets/weather/${wmo[(code ?? 0).toInt()]?.$1 ?? '03'}${day ? 'd' : 'n'}.png', width: size, height: size); + +/// panel.temp_colour: by band, in °C +Color tempColour(num c) => c < 20 + ? const Color(0xFF6E9CFF) + : c < 23 + ? good + : c < 26 + ? accent + : c < 29 + ? const Color(0xFFFF9D5C) + : const Color(0xFFFF5F5F); + +/// The dashboard's wind arrow (page.html: polygon 0,-9 6,7 0,3 -6,7 turned deg + 180): points where it +/// blows; [r] = half its height. +void paintWindArrow(Canvas c, Offset o, double deg, double r, {Color color = muted}) { + final a = (deg + 180) * pi / 180, k = r / 9; + Offset p(double x, double y) => o + Offset(x * cos(a) - y * sin(a), x * sin(a) + y * cos(a)) * k; + c.drawPath(Path()..addPolygon([p(0, -9), p(6, 7), p(0, 3), p(-6, 7)], true), Paint()..color = color); +} + +class _Arrow extends CustomPainter { + _Arrow(this.deg); + final double deg; + @override + void paint(Canvas c, Size size) => paintWindArrow(c, size.center(Offset.zero), deg, size.height / 2 - 1); + @override + bool shouldRepaint(covariant _Arrow old) => old.deg != deg; +} + +const _compass = ['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW']; +String compass(num deg) => _compass[(deg / 45).round() % 8]; +const _aqiBands = [ + (20, 'Good', Color(0xFF50F0E6)), + (40, 'Fair', Color(0xFF50CCAA)), + (60, 'Moderate', Color(0xFFF0E641)), + (80, 'Poor', Color(0xFFFF5050)), + (100, 'Very poor', Color(0xFFC0305A)), + (1 << 30, 'Extremely poor', Color(0xFF9B3EA0)), +]; +const _uvBands = [(3, 'low'), (6, 'moderate'), (8, 'high'), (11, 'very high'), (99, 'extreme')]; +const _dows = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']; +String _ordinal(int d) => '$d${d % 100 >= 11 && d % 100 <= 13 ? 'th' : const {1: 'st', 2: 'nd', 3: 'rd'}[d % 10] ?? 'th'}'; + +class WeatherPage extends StatefulWidget { + const WeatherPage({super.key, required this.sync, this.actions = const []}); + final SyncService sync; + final List actions; // the shell's (sync icon) + @override + State createState() => _WeatherPageState(); +} + +class _WeatherPageState extends State { + late List places = _loadPlaces(); + late int at = max(0, min(widget.sync.store.meta('wx_place'), places.length - 1)); // the last city picked + late bool here = widget.sync.store.meta('wx_here') == 1 || places.isEmpty; // Current location selected (no places: always) + String? hereName = ''; // the town where the phone is (reverse geocoding) + String? noFix; // Current location found none (not allowed / off / no fix): why — the error banner; home is shown + final pickKey = GlobalKey(); + Map? data; // {fc, air, at (ms)} + (String, Map)? standIn; // nothing saved for this place yet: another place's, shown meanwhile + String? error; + bool loading = false; + + @override + void initState() { + super.initState(); + _show(); + } + + /// The places that stay: the dashboard's (Settings ▸ Weather, synced as "weather.place": home first), then + /// the build's HOME_PLACES; the ones added on this phone after them. + int fixed = 0; + + List _loadPlaces() { + final synced = [ + for (final r in widget.sync.store.rows('weather.place')..sort((a, b) => ((a['ord'] as num?) ?? 0).compareTo((b['ord'] as num?) ?? 0))) + if (r['name'] is String && r['lat'] is num && r['lon'] is num) + Place(r['name'] as String, (r['lat'] as num).toDouble(), (r['lon'] as num).toDouble()), + ]; + final base = [...synced, ...defaultPlaces.where((d) => !synced.any((p) => p.name == d.name))]; + fixed = base.length; + final t = widget.sync.store.metaText('wx_places'); + final added = [ + for (final p in (t == null ? const [] : jsonDecode(t) as List)) + Place(p['name'] as String, (p['lat'] as num).toDouble(), (p['lon'] as num).toDouble()), + ].where((p) => !base.any((d) => d.name == p.name)); + return [...base, ...added]; // the dashboard's / built-in places first, always + } + + void _savePlaces() => widget.sync.store.setMetaText( + 'wx_places', + jsonEncode([ + for (final p in places.skip(fixed)) {'name': p.name, 'lat': p.lat, 'lon': p.lon}, + ]), + ); + + String get _placeName => here ? (hereName?.isNotEmpty ?? false ? hereName! : 'Current location') : places[at].name.split(',').first; + + /// The town at those coordinates (OpenStreetMap's Nominatim, the coordinates rounded to ~1 km; kept per spot). + Future _townOf(double lat, double lon) async { + final k = 'wx_town:${lat.toStringAsFixed(2)},${lon.toStringAsFixed(2)}'; + var name = widget.sync.store.metaText(k); + if (name == null) { + try { + final r = await http + .get( + Uri.parse( + 'https://nominatim.openstreetmap.org/reverse?format=jsonv2&zoom=10&accept-language=en' + '&lat=${lat.toStringAsFixed(2)}&lon=${lon.toStringAsFixed(2)}', + ), + headers: {'User-Agent': 'dashPi-app/1 (personal weather)'}, + ) + .timeout(const Duration(seconds: 15)); + final a = ((jsonDecode(r.body) as Map)['address'] as Map?) ?? const {}; + name = (a['city'] ?? a['town'] ?? a['village'] ?? a['municipality'] ?? a['county']) as String?; + if (name != null) widget.sync.store.setMetaText(k, name); + } catch (_) {} + } + widget.sync.store.setMetaText('wx_here_name', name); + if (mounted) setState(() => hereName = name); + } + + String get _key => here ? 'wx:@here' : 'wx:${places[at].name}'; + + void _show() { + hereName = widget.sync.store.metaText('wx_here_name'); + final t = widget.sync.store.metaText(_key); + data = t == null ? null : jsonDecode(t) as Map; + error = null; + standIn = null; + if (data == null) { + // never a dark page: the last city's (or any) saved weather meanwhile + for (final p in [if (here && places.isNotEmpty) places[at], ...places]) { + final o = widget.sync.store.metaText('wx:${p.name}'); + if (o != null) { + standIn = (p.name.split(',').first, jsonDecode(o) as Map); + break; + } + } + } + final fc0 = data?['fc'] as Map?; + if (here && (hereName ?? '').isEmpty && fc0 != null) { // the town of the saved forecast (its coordinates) + _townOf((fc0['latitude'] as num).toDouble(), (fc0['longitude'] as num).toDouble()); + } + final age = data == null ? null : DateTime.now().difference(DateTime.fromMillisecondsSinceEpoch(data!['at'] as int)); + if (age == null || age > refreshAfter) _fetch(); + } + + /// Where the phone is (Android's own location — app/location.dart; the town is enough). None found (not allowed, + /// switched off, no fix) → home (the first place), and the error banner on top says why (noFix). + Future _here() async { + var why = ''; + final at = await whereAmI(none: (w) => why = w); + if (mounted) setState(() => noFix = at == null ? why : null); + if (at != null) return Place('Current location', at.lat, at.lon); + if (places.isEmpty) throw 'no location and no place added'; + final home = places.first; + if (mounted) setState(() => hereName = home.name.split(',').first); + return home; + } + + /// Current location found none: an error banner on top — why, what to do, and that home is shown instead. + Widget _noFixBanner(String why) { + final (what, todo) = switch (why) { + 'location not allowed' => ('Location isn\'t allowed for this app', 'Android settings ▸ Apps ▸ dashPi ▸ Permissions ▸ Location.'), + 'location off' => ('Location is switched off on this phone', 'Switch it on in the quick settings, then pull down.'), + _ => ('The phone couldn\'t tell where it is', 'Pull down to try again.'), + }; + return Padding( + padding: const EdgeInsets.fromLTRB(12, 6, 12, 0), + child: Container( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 10), + decoration: BoxDecoration( + color: bad.withValues(alpha: .16), + border: Border.all(color: bad.withValues(alpha: .7)), + borderRadius: BorderRadius.circular(10), + ), + child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [ + const Icon(Icons.location_off, size: 20, color: bad), + const SizedBox(width: 10), + Expanded( + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(what, style: const TextStyle(fontWeight: FontWeight.bold, color: bad)), + Text(todo, style: const TextStyle(fontSize: 13)), + Text(places.isEmpty ? 'Add a place with the location button to see one instead.' + : 'Showing ${places.first.name.split(',').first} (home) instead.', + style: const TextStyle(fontSize: 13, color: muted)), + ]), + ), + ]), + ), + ); + } + + Future _fetch() async { + final key = _key; + setState(() => loading = true); + try { + final p = here ? await _here() : places[at]; + if (here && p.name == 'Current location') _townOf(p.lat, p.lon); + final q = 'latitude=${p.lat}&longitude=${p.lon}&timezone=auto'; + final fc = await http + .get(Uri.parse('$_forecast?$q&hourly=$_hourly&daily=$_daily¤t=$_current&forecast_days=16&wind_speed_unit=ms')) + .timeout(const Duration(seconds: 20)); + if (fc.statusCode != 200) throw 'Open-Meteo: ${fc.statusCode}'; + Map? air; + try { + final a = await http.get(Uri.parse('$_airUrl?$q¤t=$_airCurrent')).timeout(const Duration(seconds: 20)); + if (a.statusCode == 200) air = jsonDecode(a.body) as Map; + } catch (_) {} // the air quality is optional (as on the dashboard) + final d = {'fc': jsonDecode(fc.body), 'air': air, 'at': DateTime.now().millisecondsSinceEpoch}; + widget.sync.store.setMetaText(key, jsonEncode(d)); + if (mounted && _key == key) { + setState(() { + data = d; + standIn = null; + error = null; + }); + } + } catch (e) { + debugPrint('weather: $e'); + if (mounted && _key == key) { + setState(() => error = 'offline'); + } + } finally { + if (mounted) setState(() => loading = false); + } + } + + void _select({bool? toHere, int? city}) { + if (city != null) { + at = city; + widget.sync.store.setMeta('wx_place', city); + } + here = toHere ?? false; + widget.sync.store.setMeta('wx_here', here ? 1 : 0); + setState(_show); + } + + /// The location chip → Current location, the dashboard's places (stay), the added ones (✕ removes). + Future _pick() async { + final box = pickKey.currentContext!.findRenderObject() as RenderBox; + final o = box.localToGlobal(Offset(0, box.size.height + 4)); + Widget item(String name, bool on, {IconData? icon, VoidCallback? remove}) => Row( + children: [ + if (icon != null) ...[Icon(icon, size: 18, color: on ? accent : Colors.white), const SizedBox(width: 8)], + Expanded( + child: Text( + name, + style: TextStyle(color: on ? accent : null, fontWeight: on ? FontWeight.bold : null), + ), + ), + if (remove != null) + IconButton( + tooltip: 'Remove', + visualDensity: VisualDensity.compact, + onPressed: remove, + icon: const Icon(Icons.close, size: 18, color: muted), + ), + ], + ); + final pick = await showMenu( + context: context, + color: card2, + position: RelativeRect.fromLTRB(o.dx, o.dy, o.dx + 1, o.dy + 1), + items: [ + PopupMenuItem( + value: -1, + child: item(hereName?.isNotEmpty ?? false ? 'Current location · $hereName' : 'Current location', here, icon: Icons.my_location), + ), + const PopupMenuDivider(), + for (var i = 0; i < places.length; i++) + PopupMenuItem( + value: i, + child: item( + places[i].name, + !here && i == at, + remove: i < fixed + ? null + : () { + Navigator.pop(context); + _remove(i); + }, + ), + ), + const PopupMenuDivider(), + PopupMenuItem(value: -2, child: item('Add a place…', false, icon: Icons.add)), + ], + ); + if (pick == -2) return _add(); + if (pick == -1) return here ? _fetch() : _select(toHere: true); + if (pick != null) _select(city: pick); + } + + /// + → search a place by name (Open-Meteo's geocoding, as the dashboard's Settings) → added and selected. + Future _add() async { + final p = await showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => const _PlaceSearch(), + ); + if (p == null) return; + var i = places.indexWhere((x) => x.name == p.name); + if (i < 0) { + places.add(p); + _savePlaces(); + i = places.length - 1; + } + _select(city: i); + } + + void _remove(int i) { + widget.sync.store.setMetaText('wx:${places[i].name}', null); + places.removeAt(i); + _savePlaces(); + _select(toHere: here || places.isEmpty, city: i == at ? 0 : (i < at ? at - 1 : at)); + } + + @override + Widget build(BuildContext context) { + final title = Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Text('Weather'), + const Text(' · ', style: TextStyle(color: muted)), + Flexible( + child: InkWell( + key: pickKey, + onTap: _pick, + borderRadius: BorderRadius.circular(8), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (here) + const Padding( + padding: EdgeInsets.only(right: 4), + child: Icon(Icons.my_location, size: 18, color: Colors.white), + ), + Flexible( + child: Text( + _placeName, + overflow: TextOverflow.ellipsis, + style: const TextStyle(color: Colors.white), + ), + ), + const Icon(Icons.arrow_drop_down, color: Colors.white), + ], + ), + ), + ), + ], + ); + final shown = data ?? standIn?.$2; + final fc = shown?['fc'] as Map?; + // what the page shows while it's not this place's fresh weather — a slim banner on top + final what = data == null + ? (standIn == null ? null : 'Showing ${standIn!.$1}') + : here + ? 'Showing your last location' + : null; + final offline = error == 'offline'; + final banner = what == null || (!loading && error == null) + ? null + : '$what — ${loading + ? (here ? 'finding where you are…' : 'trying to update…') + : offline + ? 'no connection, pull down to try again' + : error!}'; + return Scaffold( + appBar: AppBar(title: title, actions: [ + IconButton( + tooltip: 'At home (the stations)', + icon: const Icon(Icons.home_outlined, color: accent), + onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (_) => StationsPage(sync: widget.sync))), + ), + ...widget.actions, + ]), + body: RefreshIndicator( + onRefresh: _fetch, + child: ListView( + physics: const AlwaysScrollableScrollPhysics(), + padding: const EdgeInsets.only(top: 4, bottom: 24), + children: [ + if (here && noFix != null) _noFixBanner(noFix!), + if (banner != null) + Padding( + padding: const EdgeInsets.fromLTRB(12, 6, 12, 0), + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration(color: card2, borderRadius: BorderRadius.circular(10)), + child: Row( + children: [ + if (loading) + const SizedBox(width: 14, height: 14, child: CircularProgressIndicator(strokeWidth: 2)) + else + const Icon(Icons.info_outline, size: 16, color: muted), + const SizedBox(width: 10), + Expanded(child: Text(banner, style: const TextStyle(fontSize: 13))), + ], + ), + ), + ), + if (fc == null && loading) + const Padding( + padding: EdgeInsets.all(40), + child: Center(child: CircularProgressIndicator()), + ), + if (fc == null && !loading && error != null) + Padding( + padding: const EdgeInsets.all(24), + child: Text( + offline ? 'No weather saved for this place yet — no connection. Pull down to try again.' : error!, + style: const TextStyle(color: muted), + ), + ), + if (fc != null) ..._page(fc, shown!['air'] as Map?, DateTime.fromMillisecondsSinceEpoch(shown['at'] as int)), + ], + ), + ), + ); + } + + List _page(Map fc, Map? air, DateTime fetched) { + final cur = (fc['current'] as Map).cast(), d = (fc['daily'] as Map).cast(); + num n(Map m, String k, [int? i]) => ((i == null ? m[k] : (m[k] as List)[i]) as num?) ?? 0; + final uv = n(cur, 'uv_index'), vis = cur['visibility'] as num?, deg = n(cur, 'wind_direction_10m'); + final t = '${fetched.hour.toString().padLeft(2, '0')}:${fetched.minute.toString().padLeft(2, '0')}'; + final a = (air?['current'] as Map?)?.cast(); + final rows = [ + [ + _Stat( + CustomPaint(size: const Size(16, 16), painter: _Arrow(deg.toDouble())), + '${n(cur, 'wind_speed_10m').round()} m/s', + 'Wind ${compass(deg)}, gusts ${n(cur, 'wind_gusts_10m').round()} m/s — the arrow points where it blows', + ), + _Stat( + const Icon(Icons.water_drop_outlined, size: 16, color: Color(0xFF5CC8FF)), + '${n(cur, 'relative_humidity_2m').round()}%', + 'Humidity', + ), + _Stat(const Icon(Icons.speed, size: 16, color: muted), '${n(cur, 'pressure_msl').round()}', 'Pressure, hPa'), + _Stat( + const Icon(Icons.wb_sunny_outlined, size: 16, color: accent), + 'UV ${uv.round()}', + 'UV index ${uv.round()} — ${_uvBands.firstWhere((b) => uv < b.$1).$2} (today\'s top ${n(d, 'uv_index_max', 0).round()})', + ), + ], + [ + _Stat(const Icon(Icons.cloud_outlined, size: 16, color: muted), '${n(cur, 'cloud_cover').round()}%', 'Cloud cover'), + _Stat( + const Icon(Icons.visibility_outlined, size: 16, color: muted), + vis == null ? '—' : '${(vis / 1000).round()} km', + 'Visibility', + ), + _Stat( + const Icon(Icons.umbrella_outlined, size: 16, color: Color(0xFF5CC8FF)), + '${n(d, 'precipitation_sum', 0).toStringAsFixed(1)} mm', + 'Rain today · chance ${n(d, 'precipitation_probability_max', 0).round()}%', + ), + _Stat(const Icon(Icons.thermostat, size: 16, color: muted), '${n(cur, 'dew_point_2m').round()}°', 'Dew point'), + ], + ]; + return [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 8, 12, 0), + child: Card( + child: Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + wxIcon(cur['weather_code'] as num?, day: n(cur, 'is_day') == 1, size: 92), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '${n(cur, 'temperature_2m').round()}°', + style: TextStyle( + fontSize: 48, + fontWeight: FontWeight.bold, + height: 1.0, + color: tempColour(n(cur, 'temperature_2m')), + ), + ), + Text(wmoText(cur['weather_code'] as num?), style: const TextStyle(fontSize: 16)), + Text( + 'feels ${n(cur, 'apparent_temperature').round()}° · ' + '↑ ${n(d, 'temperature_2m_max', 0).round()}° ↓ ${n(d, 'temperature_2m_min', 0).round()}°', + style: const TextStyle(color: muted), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 14), + for (final r in rows) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row(children: [for (final st in r) Expanded(child: st)]), + ), + Text( + loading + ? 'updating…' + : error == 'offline' + ? 'saved · $t (offline)' + : 'updated $t', + textAlign: TextAlign.right, + style: const TextStyle(color: muted, fontSize: 11.5), + ), + ], + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 0), + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: _SunCard( + sunrise: (d['sunrise'] as List)[0] as String, + sunset: (d['sunset'] as List)[0] as String, + now: (cur['time'] as String?) ?? '', + daylight: n(d, 'daylight_duration', 0).toDouble(), + ), + ), + if (a?['european_aqi'] != null) ...[const SizedBox(width: 10), Expanded(child: _AirCard(a: a!))], + ], + ), + ), + ), + Padding( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 0), + child: Card( + child: Padding( + padding: const EdgeInsets.fromLTRB(0, 12, 0, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Padding( + padding: EdgeInsets.only(left: 14, bottom: 4), + child: Text('Next 48 hours', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + ), + _Hours(fc: fc), + ], + ), + ), + ), + ), + Padding(padding: const EdgeInsets.fromLTRB(12, 10, 12, 0), child: _days(d)), + ]; + } + + Widget _days(Map d) { + final count = min(14, (d['time'] as List).length); + List col(String k) => [for (var i = 0; i < count; i++) ((d[k] as List)[i] as num?) ?? 0]; + final hi = col('temperature_2m_max'), lo = col('temperature_2m_min'); + final dmin = lo.reduce(min) - 1, dmax = hi.reduce(max) + 1; + return Card( + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 6), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + const Text('14 days', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)), + const SizedBox(height: 4), + for (var i = 0; i < count; i++) + Builder( + builder: (context) { + final day = DateTime.parse((d['time'] as List)[i] as String); + final weekend = day.weekday >= 6; + return Tooltip( + triggerMode: TooltipTriggerMode.tap, + message: + '${wmoText(col('weather_code')[i])} · rain ${col('precipitation_sum')[i].toStringAsFixed(1)} mm · ' + 'wind ${col('wind_speed_10m_max')[i].round()} m/s ${compass(col('wind_direction_10m_dominant')[i])} · ' + 'UV ${col('uv_index_max')[i].round()}', + child: Padding( + padding: const EdgeInsets.symmetric(vertical: 3), + child: Row( + children: [ + SizedBox( + width: 62, + child: Text( + i == 0 ? 'Today' : '${_dows[day.weekday - 1]} ${_ordinal(day.day)}', + style: TextStyle(color: weekend ? accent : null, fontWeight: i == 0 ? FontWeight.bold : null), + ), + ), + wxIcon(col('weather_code')[i], size: 34), + SizedBox( + width: 44, + child: Text( + '${col('precipitation_probability_max')[i].round()}%', + textAlign: TextAlign.right, + style: TextStyle( + color: col('precipitation_probability_max')[i] >= 50 ? const Color(0xFF5CC8FF) : muted, + fontSize: 13, + ), + ), + ), + const SizedBox(width: 10), + SizedBox( + width: 30, + child: Text( + '${lo[i].round()}°', + textAlign: TextAlign.right, + style: TextStyle(color: tempColour(lo[i])), + ), + ), + Expanded( + child: LayoutBuilder( + builder: (context, box) { + final w = box.maxWidth - 16; + final a = (lo[i] - dmin) / (dmax - dmin) * w, b = (hi[i] - dmin) / (dmax - dmin) * w; + return Container( + height: 6, + margin: const EdgeInsets.symmetric(horizontal: 8), + decoration: BoxDecoration(color: card2, borderRadius: BorderRadius.circular(3)), + child: Stack( + children: [ + Positioned( + left: a, + width: max(4, b - a), + top: 0, + bottom: 0, + child: Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(3), + gradient: LinearGradient(colors: [tempColour(lo[i]), tempColour(hi[i])]), + ), + ), + ), + ], + ), + ); + }, + ), + ), + SizedBox( + width: 30, + child: Text( + '${hi[i].round()}°', + style: TextStyle(color: tempColour(hi[i]), fontWeight: FontWeight.bold), + ), + ), + ], + ), + ), + ); + }, + ), + ], + ), + ), + ); + } +} + +/// The next 48 hours from the current hour (the place's own time): temperature (+ feels-like dashed), +/// rain chance bars (darker from 0.1 mm), every 3 hours the hour, icon, temperature and wind — scrolls sideways. +class _Hours extends StatelessWidget { + const _Hours({required this.fc}); + final Map fc; + + @override + Widget build(BuildContext context) { + final h = (fc['hourly'] as Map).cast(); + final cur = (fc['current'] as Map).cast(); + final times = (h['time'] as List).cast(); + final stamp = '${((cur['time'] as String?) ?? times.first).substring(0, 13)}:00'; + final i0 = max(0, times.indexWhere((t) => t.compareTo(stamp) >= 0)); + final idx = [for (var i = i0; i < min(i0 + 48, times.length); i++) i]; + num v(String k, int i) => ((h[k] as List)[i] as num?) ?? 0; + const step = 20.0, ml = 16.0; + final width = ml * 2 + step * (idx.length - 1); + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SizedBox( + width: width, + height: 172, + child: Stack( + children: [ + CustomPaint(size: Size(width, 172), painter: _HoursPainter(h, idx, step, ml)), + for (var k = 0; k < idx.length; k += 3) + Positioned( + left: ml + k * step - 14, + top: 17, + width: 28, + child: wxIcon(v('weather_code', idx[k]), day: v('is_day', idx[k]) == 1, size: 28), + ), + ], + ), + ), + ); + } +} + +class _HoursPainter extends CustomPainter { + _HoursPainter(this.h, this.idx, this.step, this.ml); + final Map h; + final List idx; + final double step, ml; + + @override + void paint(Canvas c, Size size) { + num v(String k, int i) => ((h[k] as List)[i] as num?) ?? 0; + final temps = [for (final i in idx) v('temperature_2m', i).toDouble()]; + final feels = [for (final i in idx) v('apparent_temperature', i).toDouble()]; + final lo = [...temps, ...feels].reduce(min) - 1, hi = [...temps, ...feels].reduce(max) + 1; + const top = 66.0, bottom = 100.0, barTop = 112.0, barH = 24.0; + double x(int k) => ml + k * step; + double y(double t) => top + (hi - t) / (hi - lo) * (bottom - top); + void label(String s, Offset o, {Color color = muted, double size = 11, FontWeight? w}) { + final tp = TextPainter( + text: TextSpan( + text: s, + style: TextStyle(color: color, fontSize: size, fontWeight: w), + ), + textDirection: TextDirection.ltr, + )..layout(); + tp.paint(c, o - Offset(tp.width / 2, 0)); + } + + // day separators + for (var k = 1; k < idx.length; k++) { + final t = (h['time'] as List)[idx[k]] as String; + if (t.substring(11, 13) == '00') { + c.drawLine( + Offset(x(k), 0), + Offset(x(k), size.height), + Paint() + ..color = card2 + ..strokeWidth = 1, + ); + final d = DateTime.parse(t); + final tp = TextPainter( + text: TextSpan( + text: '${_dows[d.weekday - 1]} ${_ordinal(d.day)}', + style: const TextStyle(color: accent, fontSize: 11), + ), + textDirection: TextDirection.ltr, + )..layout(); + tp.paint(c, Offset(x(k) + 3, 46)); + } + } + // rain chance bars + final bw = step * 0.7; + for (var k = 0; k < idx.length; k++) { + final p = v('precipitation_probability', idx[k]).toDouble(), mm = v('precipitation', idx[k]).toDouble(); + final hh = p / 100 * barH; + if (hh > 0) { + c.drawRect( + Rect.fromLTWH(x(k) - bw / 2, barTop + barH - hh, bw, hh), + Paint()..color = const Color(0xFF5CC8FF).withValues(alpha: mm >= 0.1 ? .85 : .35), + ); + } + } + // feels-like (dashed) + temperature + final fp = Paint() + ..color = muted + ..strokeWidth = 1.2 + ..style = PaintingStyle.stroke; + for (var k = 0; k + 1 < idx.length; k++) { + if (k.isEven) c.drawLine(Offset(x(k), y(feels[k])), Offset(x(k + 1), y(feels[k + 1])), fp); + } + final path = Path()..moveTo(x(0), y(temps[0])); + for (var k = 1; k < idx.length; k++) { + path.lineTo(x(k), y(temps[k])); + } + c.drawPath( + path, + Paint() + ..color = accent + ..strokeWidth = 2.2 + ..style = PaintingStyle.stroke + ..strokeJoin = StrokeJoin.round, + ); + // every 3 hours: hour, temperature, rain %, wind + for (var k = 0; k < idx.length; k += 3) { + final i = idx[k]; + label(((h['time'] as List)[i] as String).substring(11, 13), Offset(x(k), 1), color: Colors.white, size: 11.5); + c.drawCircle(Offset(x(k), y(temps[k])), 3, Paint()..color = accent); + label('${temps[k].round()}°', Offset(x(k), y(temps[k]) - 16), color: tempColour(temps[k]), size: 11.5, w: FontWeight.bold); + final p = v('precipitation_probability', i).round(); + if (p > 0) label('$p%', Offset(x(k), barTop + barH - p / 100 * barH - 12), color: const Color(0xFF5CC8FF), size: 9.5); + // wind: an arrow pointing where it blows, + speed + final o = Offset(x(k), barTop + barH + 12); + paintWindArrow(c, o, v('wind_direction_10m', i).toDouble(), 6.5); + label('${v('wind_speed_10m', i).round()}', Offset(x(k), o.dy + 7), size: 10); + } + } + + @override + bool shouldRepaint(covariant _HoursPainter old) => true; +} + +/// One value of the "now" card: a small icon + the value (what it is and more on tap). +class _Stat extends StatelessWidget { + const _Stat(this.icon, this.value, this.tip); + final Widget icon; + final String value, tip; + @override + Widget build(BuildContext context) => Tooltip( + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 6), + message: tip, + child: Row( + children: [ + icon, + const SizedBox(width: 5), + Flexible( + child: Text(value, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 13.5)), + ), + ], + ), + ); +} + +/// Sunrise → sunset as an arc over the horizon, the sun where it is now (the place's own time), +/// the daylight in between. +class _SunCard extends StatelessWidget { + const _SunCard({required this.sunrise, required this.sunset, required this.now, required this.daylight}); + final String sunrise, sunset, now; // ISO, the place's local time + final double daylight; // s + + @override + Widget build(BuildContext context) { + final a = DateTime.parse(sunrise), z = DateTime.parse(sunset), t = DateTime.tryParse(now); + final f = t == null ? null : t.difference(a).inSeconds / max(1, z.difference(a).inSeconds); + String hm(DateTime d) => '${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}'; + final left = f != null && f > 0 && f < 1 ? z.difference(t!) : null; + const small = TextStyle(fontSize: 12.5, fontWeight: FontWeight.bold); + return Card( + child: Tooltip( + triggerMode: TooltipTriggerMode.tap, + message: + 'Daylight today: sunrise → sunset. ' + '${left != null + ? '${left.inHours} h ${(left.inMinutes % 60).toString().padLeft(2, '0')} min of it left' + : f != null && f >= 1 + ? 'The sun has set' + : 'Before sunrise'}', + child: Padding( + padding: const EdgeInsets.fromLTRB(10, 10, 10, 8), + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + SizedBox( + height: 52, + child: Stack( + children: [ + Positioned.fill(top: 7, child: CustomPaint(painter: _SunPainter(f))), + Align( + alignment: Alignment.topCenter, + child: Container( + color: card, + padding: const EdgeInsets.symmetric(horizontal: 6), + child: Text( + '${daylight ~/ 3600} h ${(daylight % 3600 ~/ 60).toString().padLeft(2, '0')} min', + style: const TextStyle(fontSize: 12.5), + ), + ), + ), + ], + ), + ), + const SizedBox(height: 4), + Row( + children: [ + Text('↑ ${hm(a)}', style: small), + const Spacer(), + Text('↓ ${hm(z)}', style: small), + ], + ), + ], + ), + ), + ), + ); + } +} + +/// European air quality index: the number in its band's colour, where it sits on the scale, the parts on tap. +class _AirCard extends StatelessWidget { + const _AirCard({required this.a}); + final Map a; + + @override + Widget build(BuildContext context) { + final aqi = (a['european_aqi'] as num?) ?? 0; + final band = _aqiBands.firstWhere((b) => aqi < b.$1); + final parts = [ + ('pm2_5', 'PM2.5'), + ('pm10', 'PM10'), + ('ozone', 'O₃'), + ('nitrogen_dioxide', 'NO₂'), + ].where((p) => a[p.$1] != null).map((p) => '${p.$2} ${(a[p.$1] as num).round()}'); + return Card( + child: Tooltip( + triggerMode: TooltipTriggerMode.tap, + showDuration: const Duration(seconds: 8), + message: + 'European air quality index: 0–20 good, 20–40 fair, 40–60 moderate, 60–80 poor, 80–100 very poor\n' + '${parts.join(' · ')} µg/m³', + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 10, 12, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + const Text('AIR QUALITY', style: TextStyle(color: muted, fontSize: 10.5)), + Row( + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Text( + '${aqi.round()}', + style: TextStyle(fontSize: 26, fontWeight: FontWeight.bold, color: band.$3), + ), + const SizedBox(width: 6), + Flexible( + child: Text( + band.$2, + overflow: TextOverflow.ellipsis, + style: TextStyle(color: band.$3, fontSize: 13), + ), + ), + ], + ), + SizedBox( + height: 12, + width: double.infinity, + child: CustomPaint(painter: _AqiScale(aqi.toDouble())), + ), + const SizedBox(height: 4), + Text(parts.take(2).join(' · '), style: const TextStyle(color: muted, fontSize: 11.5)), + ], + ), + ), + ), + ); + } +} + +/// The index's bands as one bar (0–100), a marker where it is now. +class _AqiScale extends CustomPainter { + _AqiScale(this.v); + final double v; + @override + void paint(Canvas c, Size size) { + final r = Rect.fromLTWH(0, size.height / 2 - 2.5, size.width, 5); + c.drawRRect( + RRect.fromRectAndRadius(r, const Radius.circular(3)), + Paint()..shader = LinearGradient(colors: [for (final b in _aqiBands.take(5)) b.$3]).createShader(r), + ); + final x = (min(v, 100) / 100 * size.width).clamp(4.0, size.width - 4); + c.drawRRect( + RRect.fromRectAndRadius(Rect.fromCenter(center: Offset(x, size.height / 2), width: 8, height: 12), const Radius.circular(3)), + Paint()..color = card, + ); + c.drawRRect( + RRect.fromRectAndRadius(Rect.fromCenter(center: Offset(x, size.height / 2), width: 5, height: 9), const Radius.circular(2)), + Paint()..color = Colors.white, + ); + } + + @override + bool shouldRepaint(covariant _AqiScale old) => old.v != v; +} + +class _SunPainter extends CustomPainter { + _SunPainter(this.f); + final double? f; // 0 = sunrise … 1 = sunset (outside = night) + + @override + void paint(Canvas c, Size size) { + final w = size.width, h = size.height - 6; + final rect = Rect.fromLTRB(6, 6, w - 6, 6 + (h - 6) * 2); // the top half of this oval = the sun's path + Offset at(double x) { + final a = pi + pi * x.clamp(0, 1); + return Offset(rect.center.dx + rect.width / 2 * cos(a), rect.center.dy + rect.height / 2 * sin(a)); + } + + // the horizon + c.drawLine( + Offset(0, h), + Offset(w, h), + Paint() + ..color = card2 + ..strokeWidth = 1.5, + ); + // the whole path, dashed + final track = Paint() + ..color = muted.withValues(alpha: .45) + ..strokeWidth = 1.5 + ..style = PaintingStyle.stroke; + for (var x = 0.0; x < 1; x += 0.04) { + c.drawArc(rect, pi + pi * x, pi * 0.022, false, track); + } + final day = f != null && f! > 0 && f! < 1; + if (day) { + // the part of the day gone: a warm glow under the path + a solid line + final path = Path()..moveTo(rect.left, h); + for (var x = 0.0; x <= f!; x += 0.01) { + path.lineTo(at(x).dx, at(x).dy); + } + path.lineTo(at(f!).dx, h); + path.close(); + c.drawPath( + path, + Paint() + ..shader = LinearGradient( + begin: Alignment.topCenter, + end: Alignment.bottomCenter, + colors: [accent.withValues(alpha: .28), accent.withValues(alpha: .02)], + ).createShader(rect), + ); + c.drawArc( + rect, + pi, + pi * f!, + false, + Paint() + ..color = accent + ..strokeWidth = 2.5 + ..style = PaintingStyle.stroke + ..strokeCap = StrokeCap.round, + ); + final s = at(f!); + c.drawCircle(s, 9, Paint()..color = accent.withValues(alpha: .25)); + c.drawCircle(s, 5.5, Paint()..color = accent); + } + // sunrise / sunset marks on the horizon + for (final x in [rect.left, rect.right]) { + c.drawCircle(Offset(x, h), 2.5, Paint()..color = day ? accent : muted); + } + } + + @override + bool shouldRepaint(covariant _SunPainter old) => old.f != f; +} + +/// Search a place by name (Open-Meteo geocoding) → the picked one. +class _PlaceSearch extends StatefulWidget { + const _PlaceSearch(); + @override + State<_PlaceSearch> createState() => _PlaceSearchState(); +} + +class _PlaceSearchState extends State<_PlaceSearch> { + List<(Place, String)> found = []; + String? note; + int _seq = 0; + + Future _search(String q) async { + final mine = ++_seq; + if (q.trim().length < 2) return setState(() => found = []); + try { + final r = await http + .get(Uri.parse('$_geocode?name=${Uri.encodeQueryComponent(q.trim())}&count=8&language=en&format=json')) + .timeout(const Duration(seconds: 15)); + if (mine != _seq) return; + final res = ((jsonDecode(r.body) as Map)['results'] as List?) ?? const []; + setState(() { + note = res.isEmpty ? 'Nothing found' : null; + found = [ + for (final x in res.cast>()) + ( + Place('${x['name']}, ${x['country_code'] ?? ''}', (x['latitude'] as num).toDouble(), (x['longitude'] as num).toDouble()), + [x['admin1'], x['country']].whereType().join(', '), + ), + ]; + }); + } catch (e) { + if (mine == _seq) setState(() => note = 'No connection'); + } + } + + @override + Widget build(BuildContext context) => Padding( + padding: EdgeInsets.fromLTRB(16, 16, 16, 12 + MediaQuery.of(context).viewInsets.bottom), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + TextField( + autofocus: true, + onChanged: _search, + decoration: const InputDecoration(labelText: 'Place', hintText: 'a town or city', prefixIcon: Icon(Icons.search)), + ), + if (note != null) + Padding( + padding: const EdgeInsets.all(12), + child: Text(note!, style: const TextStyle(color: muted)), + ), + ConstrainedBox( + constraints: const BoxConstraints(maxHeight: 360), + child: ListView( + shrinkWrap: true, + children: [ + for (final (p, where) in found) + ListTile( + title: Text(p.name.split(',').first), + subtitle: Text(where, style: const TextStyle(color: muted)), + onTap: () => Navigator.pop(context, p), + ), + ], + ), + ), + ], + ), + ); +} diff --git a/app/lib/widgets/bar_chart.dart b/app/lib/widgets/bar_chart.dart new file mode 100644 index 0000000..f6d8950 --- /dev/null +++ b/app/lib/widgets/bar_chart.dart @@ -0,0 +1,132 @@ +// Bars over dates for the health pages (steps, energy …): one per day, or from [weeklyFrom] days one +// per week = the average day of the days with data (as the web's weekly grouping). Tap or drag = that +// bar's numbers above the chart; [range] = the shared Health period as a chip in the corner. +import 'dart:math'; + +import 'package:flutter/material.dart'; + +import '../app/theme.dart'; +import '../health/cycle_model.dart' show daysBetween, plus; +import '../health/range.dart'; +import 'line_chart.dart' show RangeChip; + +const weeklyFrom = 120; +const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + +class BarChart extends StatefulWidget { + const BarChart({super.key, required this.points, required this.from, required this.to, required this.color, + this.fmt, this.goal, this.height = 160, this.range}); + final List<(DateTime, double)> points; // one per day + final DateTime from, to; + final Color color; + final String Function(double)? fmt; // the tip's value + final double? goal; // a dashed line (per day) + final double height; + final HealthRange? range; + @override + State createState() => _BarChartState(); +} + +class _BarChartState extends State { + int? hit; + + /// [(first day, value or null, label)] + List<(DateTime, double?, String)> _buckets() { + final byDay = {for (final p in widget.points) p.$1: p.$2}; + final n = daysBetween(widget.from, widget.to) + 1; + final out = <(DateTime, double?, String)>[]; + if (n >= weeklyFrom) { + for (var s = plus(widget.from, -(widget.from.weekday - 1)); !s.isAfter(widget.to); s = plus(s, 7)) { + final vs = [for (var i = 0; i < 7; i++) byDay[plus(s, i)]].whereType().toList(); + out.add((s, vs.isEmpty ? null : vs.reduce((a, b) => a + b) / vs.length, + 'Week of ${s.day} ${_mon[s.month - 1]} ${s.year} · a day')); + } + } else { + for (var i = 0; i < n; i++) { + final d = plus(widget.from, i); + out.add((d, byDay[d], '${d.day} ${_mon[d.month - 1]} ${d.year}')); + } + } + return out; + } + + @override + Widget build(BuildContext context) { + final b = _buckets(); + final fmt = widget.fmt ?? (double v) => v.round().toString(); + final h = hit != null && hit! < b.length ? b[hit!] : null; + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + Row(children: [ + Expanded( + child: Text(h == null ? 'Tap a bar for its numbers' : '${h.$3}: ${h.$2 == null ? 'nothing' : fmt(h.$2!)}', + style: TextStyle(color: h == null ? muted : Colors.white, fontSize: 12.5)), + ), + if (widget.range != null) RangeChip(widget.range!), + ]), + const SizedBox(height: 6), + LayoutBuilder(builder: (context, box) { + void pick(Offset o) => + setState(() => hit = ((o.dx - 34) / (box.maxWidth - 34) * b.length).floor().clamp(0, b.length - 1)); + return GestureDetector( + onTapDown: (d) => pick(d.localPosition), + onHorizontalDragUpdate: (d) => pick(d.localPosition), + child: CustomPaint(size: Size(box.maxWidth, widget.height), painter: _Painter(b, widget, hit)), + ); + }), + ]); + } +} + +class _Painter extends CustomPainter { + _Painter(this.b, this.w, this.hit); + final List<(DateTime, double?, String)> b; + final BarChart w; + final int? hit; + + static double _nice(double x) { + final e = pow(10, (log(x) / ln10).floor()).toDouble(), f = x / e; + return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * e; + } + + @override + void paint(Canvas c, Size size) { + const ml = 34.0, mb = 16.0, mt = 4.0; + final h = size.height - mb - mt; + final peak = max(1.0, [w.goal ?? 0, for (final x in b) x.$2 ?? 0].reduce(max)); + final step = _nice(peak / 3), top = (peak / step).ceil() * step; + double y(double v) => mt + h - h * v / top; + final txt = const TextStyle(color: muted, fontSize: 10.5); + void label(String s, Offset o, {bool right = false}) { + final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout(); + tp.paint(c, right ? o - Offset(tp.width, tp.height / 2) : o - Offset(tp.width / 2, 0)); + } + + for (var v = 0.0; v <= top + 0.001; v += step) { + c.drawLine(Offset(ml, y(v)), Offset(size.width, y(v)), Paint()..color = card2); + label(v >= 1000 ? '${(v / 1000).toStringAsFixed(v % 1000 == 0 ? 0 : 1)}k' : v.round().toString(), Offset(ml - 4, y(v)), right: true); + } + final bw = (size.width - ml) / max(1, b.length), pad = bw > 4 ? bw * 0.18 : 0.0; + final weekly = b.length > 1 && b[1].$1.difference(b[0].$1).inDays == 7; + for (var i = 0; i < b.length; i++) { + final (d, v, _) = b[i]; + final x0 = ml + i * bw; + if (v != null && v > 0) { + c.drawRect(Rect.fromLTRB(x0 + pad, y(v), x0 + bw - pad, y(0)), + Paint()..color = hit == i ? Colors.white : w.color.withValues(alpha: hit == null ? 1 : .75)); + } + final l = weekly + ? (d.day <= 7 && (b.length <= 30 || d.month % 3 == 1) ? _mon[d.month - 1] : null) + : b.length > 35 ? (d.day == 1 ? _mon[d.month - 1] : null) : (d.weekday == 1 || b.length <= 8 ? '${d.day} ${_mon[d.month - 1]}' : null); + if (l != null) label(l, Offset(x0 + bw / 2, size.height - mb + 3)); + } + if (w.goal != null) { + final gy = y(w.goal!); + for (var x = ml; x < size.width; x += 8) { + c.drawLine(Offset(x, gy), Offset(min(x + 4, size.width), gy), Paint()..color = accent..strokeWidth = 1.2); + } + } + } + + @override + bool shouldRepaint(covariant _Painter old) => true; +} diff --git a/app/lib/widgets/line_chart.dart b/app/lib/widgets/line_chart.dart new file mode 100644 index 0000000..ea0f4eb --- /dev/null +++ b/app/lib/widgets/line_chart.dart @@ -0,0 +1,212 @@ +// A small time chart for the health pages: lines (or dots) over dates, an optional band (the +// healthy range), hour / day / month ticks to suit the span, a few value ticks; tap or drag shows +// the nearest point. With [range]: the shared Health period as a chip in the corner (tap = change +// it for every Health chart). +import 'dart:math'; + +import 'package:flutter/material.dart'; + +import '../app/theme.dart'; +import '../health/range.dart'; + +class Series { + const Series(this.name, this.points, this.color); + final String name; + final List<(DateTime, double)> points; + final Color color; +} + +class LineChart extends StatefulWidget { + const LineChart({super.key, required this.series, required this.from, required this.to, this.unit = '', + this.band, this.limits, this.height = 190, this.decimals = 1, this.range}); + final List series; + final DateTime from, to; + final String unit; + final (double, double)? band; + final (double, double)? limits; // a fixed scale (stretched if a value falls outside), e.g. 85–100 % for SpO₂ + final double height; + final int decimals; + final HealthRange? range; + @override + State createState() => _LineChartState(); +} + +class _LineChartState extends State { + (Series, (DateTime, double))? hit; + + @override + Widget build(BuildContext context) { + final chart = _chart(context); + if (widget.range == null) return chart; + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [Align(alignment: Alignment.centerRight, child: RangeChip(widget.range!)), const SizedBox(height: 4), chart]); + } + + Widget _chart(BuildContext context) { + final pts = [for (final s in widget.series) for (final p in s.points) if (!p.$1.isBefore(widget.from)) p]; + if (pts.isEmpty) { + return SizedBox(height: 60, child: Center(child: Text('Nothing measured in this period', style: TextStyle(color: muted.withValues(alpha: .8))))); + } + return LayoutBuilder(builder: (context, box) { + final painter = _Painter(widget, hit); + void pick(Offset o) { + (Series, (DateTime, double))? best; + var bd = double.infinity; + for (final s in widget.series) { + for (final p in s.points) { + if (p.$1.isBefore(widget.from)) continue; + final d = (painter.pos(p, box.maxWidth) - o).distance; + if (d < bd) { + bd = d; + best = (s, p); + } + } + } + setState(() => hit = bd < 60 ? best : null); + } + + return Column(crossAxisAlignment: CrossAxisAlignment.stretch, children: [ + GestureDetector( + onTapDown: (d) => pick(d.localPosition), + onHorizontalDragUpdate: (d) => pick(d.localPosition), + child: CustomPaint(size: Size(box.maxWidth, widget.height), painter: painter), + ), + SizedBox( + height: 20, + child: hit == null + ? null + : Text('${hit!.$1.name}: ${hit!.$2.$2.toStringAsFixed(widget.decimals)} ${widget.unit} · ' + '${hit!.$2.$1.day}.${hit!.$2.$1.month}.${hit!.$2.$1.year}' + '${hit!.$2.$1.hour + hit!.$2.$1.minute > 0 ? ' ${hit!.$2.$1.toIso8601String().substring(11, 16)}' : ''}', + textAlign: TextAlign.center, style: TextStyle(color: hit!.$1.color, fontSize: 13)), + ), + ]); + }); + } +} + +class _Painter extends CustomPainter { + _Painter(this.w, this.hit) { + final vs = [for (final s in w.series) for (final p in s.points) if (!p.$1.isBefore(w.from)) p.$2]; + var lo = vs.reduce(min), hi = vs.reduce(max); + if (w.band != null && w.band!.$1 < hi && w.band!.$2 > lo) { // the band only stretches the scale where it meets the data + lo = min(lo, w.band!.$1); + hi = max(hi, w.band!.$2); + } + if (w.limits != null) { + lo = min(lo, w.limits!.$1); + hi = max(hi, w.limits!.$2); + } else { + final pad = max((hi - lo) * 0.1, 0.5); + lo -= pad; + hi += pad; + } + step = _nice((hi - lo) / 4); + this.lo = (lo / step).floorToDouble() * step; + this.hi = (hi / step).ceilToDouble() * step; + } + + final LineChart w; + final (Series, (DateTime, double))? hit; + late final double lo, hi, step; + static const ml = 40.0, mb = 18.0, mt = 6.0; + + static double _nice(double x) { + final e = pow(10, (log(x) / ln10).floor()).toDouble(); + final f = x / e; + return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 5 ? 5 : 10) * e; + } + + double get span => max(1, w.to.difference(w.from).inHours / 24); + + Offset pos((DateTime, double) p, double width) { + final x = ml + (p.$1.difference(w.from).inHours / 24) / span * (width - ml - 8); + final y = mt + (1 - (p.$2 - lo) / (hi - lo)) * (w.height - mt - mb); + return Offset(x, y); + } + + @override + void paint(Canvas c, Size size) { + final grid = Paint()..color = card2..strokeWidth = 1; + final txt = TextStyle(color: muted, fontSize: 10.5); + void label(String s, Offset at, {bool right = false, bool center = false}) { + final tp = TextPainter(text: TextSpan(text: s, style: txt), textDirection: TextDirection.ltr)..layout(); + tp.paint(c, at - Offset(right ? tp.width : center ? tp.width / 2 : 0, tp.height / 2)); + } + + if (w.band != null) { + final top = max(mt, pos((w.from, w.band!.$2), size.width).dy), bottom = min(w.height - mb, pos((w.to, w.band!.$1), size.width).dy); + if (bottom > top) c.drawRect(Rect.fromLTRB(ml, top, size.width - 8, bottom), Paint()..color = good.withValues(alpha: 0.08)); + } + for (var v = lo; v <= hi + step / 2; v += step) { + final y = pos((w.from, v), size.width).dy; + c.drawLine(Offset(ml, y), Offset(size.width - 8, y), grid); + label(v.toStringAsFixed(step < 1 ? 1 : 0), Offset(ml - 6, y), right: true); + } + // x ticks to suit the span: hours (≤ 2 days), days (≤ 45), months + final days = span; + const mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + void tick(DateTime d, String text) { + if (d.isBefore(w.from) || d.isAfter(w.to)) return; + label(text, Offset(pos((d, lo), size.width).dx, w.height - mb / 2 + 2), center: true); + } + if (days <= 2) { + for (var d = DateTime.utc(w.from.year, w.from.month, w.from.day); !d.isAfter(w.to); d = d.add(const Duration(hours: 4))) { + tick(d, d.hour == 0 ? '${d.day} ${mon[d.month - 1]}' : '${d.hour.toString().padLeft(2, '0')}:00'); + } + } else if (days <= 45) { + final every = (days / 7).ceil(); + for (var d = DateTime.utc(w.from.year, w.from.month, w.from.day), i = 0; !d.isAfter(w.to); d = d.add(const Duration(days: 1)), i++) { + if (i % every == 0) tick(d, '${d.day} ${mon[d.month - 1]}'); + } + } else { + final every = days > 800 ? 6 : days > 400 ? 3 : 1; + for (var d = DateTime.utc(w.from.year, w.from.month, 1); !d.isAfter(w.to); d = DateTime.utc(d.year, d.month + 1, 1)) { + if ((d.month - 1) % every == 0) tick(d, d.month == 1 ? '${d.year}' : mon[d.month - 1]); + } + } + for (final s in w.series) { + final ps = [for (final p in s.points) if (!p.$1.isBefore(w.from)) pos(p, size.width)]; + final line = Paint()..color = s.color..strokeWidth = 2..style = PaintingStyle.stroke; + if (ps.length > 1) { + final path = Path()..moveTo(ps.first.dx, ps.first.dy); + for (final p in ps.skip(1)) { + path.lineTo(p.dx, p.dy); + } + c.drawPath(path, line); + } + for (final p in ps) { + c.drawCircle(p, ps.length > 40 ? 1.8 : 3, Paint()..color = s.color); + } + } + if (hit != null) { + final p = pos(hit!.$2, size.width); + c.drawCircle(p, 6, Paint()..color = hit!.$1.color.withValues(alpha: .35)); + c.drawLine(Offset(p.dx, mt), Offset(p.dx, w.height - mb), Paint()..color = muted.withValues(alpha: .4)); + } + } + + @override + bool shouldRepaint(covariant _Painter old) => true; +} + +/// The shared Health period as a small chip (tap = change it for every Health chart). +class RangeChip extends StatelessWidget { + const RangeChip(this.r, {super.key}); + final HealthRange r; + @override + Widget build(BuildContext context) => PopupMenuButton( + tooltip: 'Time period (every Health chart)', + color: card2, + initialValue: r.value, + onSelected: r.set, + itemBuilder: (_) => [for (final (k, l, _) in ranges) PopupMenuItem(value: k, child: Text(l))], + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration(color: card2, borderRadius: BorderRadius.circular(8)), + child: Row(mainAxisSize: MainAxisSize.min, children: [ + Text(r.label, style: const TextStyle(color: accent, fontSize: 13)), + const Icon(Icons.arrow_drop_down, color: accent, size: 18), + ]), + ), + ); +} diff --git a/app/lib/work/customers_page.dart b/app/lib/work/customers_page.dart new file mode 100644 index 0000000..34c6e79 --- /dev/null +++ b/app/lib/work/customers_page.dart @@ -0,0 +1,406 @@ +// Customers (the web's Settings ▸ Work): the tree — customers, sub-customers, projects, tasks — +// with this month's hours and the rate in force today; tap one = its editor: name, where it sits, +// colour (customers always have one; below them "same as above" = inherit), billable (inherit / +// yes / no), currency, the rate history (from a day, or always), notes, archived. Nodes with time +// booked can't be deleted (archive them); a node's + adds a sub-customer / project / task under it. +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'entry_sheet.dart' show NodePicker, hexColor; +import 'work_model.dart'; + +IconData kindIcon(Node n) => n.kind == 'task' + ? Icons.check_box_outline_blank + : n.kind == 'project' + ? Icons.folder_outlined + : Icons.business; + +class CustomersPage extends StatefulWidget { + const CustomersPage({super.key, required this.sync, this.s = const WorkSettings()}); + final SyncService sync; + final WorkSettings s; + @override + State createState() => _CustomersPageState(); +} + +class _CustomersPageState extends State { + bool showArchived = false; + + void _edit({String? id, String kind = 'client', String? parent}) => Navigator.push( + context, + MaterialPageRoute( + builder: (_) => NodeEditor(sync: widget.sync, s: widget.s, nodeId: id, kind: kind, parent: parent), + ), + ); + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: widget.sync, + builder: (context, _) { + final store = widget.sync.store; + final t = Tree(store, widget.s); + final now = DateTime.now(), first = DateTime.utc(now.year, now.month); + final month = {}; + for (final e in entriesBetween(store, first, now.add(const Duration(days: 1)))) { + for (final n in t.chain(e.node)) { + month[n.id] = (month[n.id] ?? 0) + e.minutes; + } + } + final todayIso = fmtDay(now); + final archivedCount = t.nodes.values.where((n) => n.archived).length; + final rows = t.walk(archived: showArchived).toList(); + return Scaffold( + appBar: AppBar( + title: const Text('Customers'), + actions: [ + if (archivedCount > 0) + TextButton( + onPressed: () => setState(() => showArchived = !showArchived), + child: Text(showArchived ? 'Hide archived' : 'Archived ($archivedCount)'), + ), + ], + ), + floatingActionButton: FloatingActionButton.extended( + onPressed: () => _edit(), + icon: const Icon(Icons.add), + label: const Text('Customer'), + ), + body: rows.isEmpty + ? const Center( + child: Text('No customers yet', style: TextStyle(color: muted)), + ) + : ListView( + padding: const EdgeInsets.only(bottom: 90), + children: [ + for (final (n, d) in rows) + ListTile( + contentPadding: EdgeInsets.only(left: 16.0 + d * 20, right: 8), + leading: Icon(kindIcon(n), color: hexColor(t.colour(n.id))), + title: Text(n.name, style: TextStyle(color: t.archived(n.id) ? muted : null)), + subtitle: Text( + [ + Tree.kindLabel(n), + '${num0(t.rate(n.id, todayIso).$1)} ${t.currency(n.id)}/h${t.rates[n.id]?.isNotEmpty == true ? '' : ' (inherited)'}', + if (!t.billable(n.id).$1) 'not billable', + if (month[n.id] != null) '${hm(month[n.id]!)} this month', + if (t.archived(n.id)) 'archived', + ].join(' · '), + style: const TextStyle(color: muted, fontSize: 12.5), + ), + trailing: n.kind == 'task' ? null : _addMenu(n), + onTap: () => _edit(id: n.id), + ), + ], + ), + ); + }, + ); + + Widget _addMenu(Node n) => PopupMenuButton( + icon: const Icon(Icons.add, color: muted), + tooltip: 'Add under ${n.name}', + color: card2, + onSelected: (k) => _edit(kind: k == 'sub' ? 'client' : k, parent: n.id), + itemBuilder: (_) => [ + if (n.kind == 'client') const PopupMenuItem(value: 'sub', child: Text('Sub-customer')), + if (n.kind == 'client') const PopupMenuItem(value: 'project', child: Text('Project')), + const PopupMenuItem(value: 'task', child: Text('Task')), + ], + ); +} + +/// One node's editor (new when [nodeId] is null: a [kind] under [parent]). +class NodeEditor extends StatefulWidget { + const NodeEditor({super.key, required this.sync, this.s = const WorkSettings(), this.nodeId, this.kind = 'client', this.parent}); + final SyncService sync; + final WorkSettings s; + final String? nodeId, kind, parent; + @override + State createState() => _NodeEditorState(); +} + +class _NodeEditorState extends State { + late Tree t = Tree(widget.sync.store, widget.s); + late NodeForm f = widget.nodeId != null && t.nodes.containsKey(widget.nodeId) + ? NodeForm.of(t, t.nodes[widget.nodeId]!) + : NodeForm(kind: widget.kind ?? 'client', parent: widget.parent); + late final name = TextEditingController(text: f.name), + currency = TextEditingController(text: f.currency), + notes = TextEditingController(text: f.notes); + late final rateCtl = [for (final r in f.rates) TextEditingController(text: r.$2)]; + late final sinceList = [for (final r in f.rates) r.$1]; + String? error, errorField; + bool armed = false; + + bool get isNew => f.id == null; + bool get topLevel => f.kind == 'client' && f.parent == null; + + void _save() { + f + ..name = name.text + ..currency = currency.text + ..notes = notes.text + ..rates = [for (var i = 0; i < rateCtl.length; i++) (sinceList[i], rateCtl[i].text)]; + try { + saveNode(widget.sync.store, t, f); + widget.sync.changed(); + Navigator.pop(context); + } on Invalid catch (e) { + setState(() { + error = e.message; + errorField = e.field; + }); + } + } + + void _delete() { + if (!armed) { + setState(() => armed = true); + return; + } + if (!deleteNode(widget.sync.store, t, f.id!)) { + setState(() { + armed = false; + error = 'Time is booked on it — archive it instead.'; + }); + return; + } + widget.sync.changed(); + Navigator.pop(context); + } + + Future _parent() async { + final allowed = parentsOf[f.kind]!; + final mine = f.id == null ? {} : t.subtree(f.id!); + final nid = await showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => + NodePicker(tree: t, recent: const [], current: f.parent, only: (n) => allowed.contains(n.kind) && !mine.contains(n.id)), + ); + if (nid != null) setState(() => f.parent = nid); + } + + Future _since(int i) async { + final cur = DateTime.tryParse(sinceList[i]); + final p = await showDatePicker( + context: context, + initialDate: cur ?? DateTime.now(), + firstDate: DateTime(2000), + lastDate: DateTime(2100), + helpText: 'Rate from this day', + ); + if (p != null) setState(() => sinceList[i] = fmtDay(p)); + } + + @override + Widget build(BuildContext context) { + final todayIso = fmtDay(DateTime.now()); + final parentId = f.parent; + final (pRate, pRsrc) = parentId != null ? t.rate(parentId, todayIso) : (widget.s.defaultRate, null); + final (pBill, pBsrc) = parentId != null ? t.billable(parentId) : (true, null); + final pCur = parentId != null ? t.currency(parentId) : widget.s.currency; + final booked = f.id == null ? 0.0 : t.subtree(f.id!).fold(0.0, (m, i) => m + (bookedMinutes(widget.sync.store)[i] ?? 0)); + final kindName = f.kind == 'client' + ? (topLevel ? 'Customer' : 'Sub-customer') + : f.kind == 'project' + ? 'Project' + : 'Task'; + return Scaffold( + appBar: AppBar( + title: Text(isNew ? 'New ${kindName.toLowerCase()}' : kindName), + actions: [TextButton(onPressed: _save, child: const Text('Save'))], + ), + body: ListView( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 32), + children: [ + TextField( + controller: name, + autofocus: isNew, + textCapitalization: TextCapitalization.sentences, + decoration: InputDecoration( + labelText: 'Name', + border: const OutlineInputBorder(), + errorText: errorField == 'name' ? error : null, + ), + ), + const SizedBox(height: 12), + // where it sits (customers are top level; a sub-customer can move under another customer) + if (!topLevel || !isNew) + ListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Under'), + subtitle: Text( + parentId == null ? '— top level (a customer)' : t.path(parentId), + style: TextStyle(color: errorField == 'parent_id' ? bad : muted), + ), + trailing: f.kind == 'client' && parentId != null + ? TextButton(onPressed: () => setState(() => f.parent = null), child: const Text('Make top level')) + : null, + onTap: _parent, + ), + if (errorField == 'parent_id') Text(error!, style: const TextStyle(color: bad)), + const SizedBox(height: 6), + const Text('Colour', style: TextStyle(color: muted)), + const SizedBox(height: 6), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + if (!topLevel) + ChoiceChip( + label: const Text('Same as above'), + avatar: Icon(Icons.circle, size: 14, color: hexColor(t.colour(parentId))), + selected: f.colour == null, + onSelected: (_) => setState(() => f.colour = null), + ), + for (final c in [ + if (f.colour != null && !palette.contains(f.colour)) f.colour!, + ...palette, + ]) // a custom one (set on the web) first + GestureDetector( + onTap: () => setState(() => f.colour = c), + child: Container( + width: 32, + height: 32, + decoration: BoxDecoration( + color: hexColor(c), + shape: BoxShape.circle, + border: Border.all(color: f.colour == c ? Colors.white : Colors.transparent, width: 2.5), + ), + ), + ), + ], + ), + const SizedBox(height: 16), + const Text('New entries are', style: TextStyle(color: muted)), + const SizedBox(height: 6), + SegmentedButton( + segments: [ + ButtonSegment(value: null, label: Text(pBill ? 'Inherit (billable)' : 'Inherit (not)')), + const ButtonSegment(value: 1, label: Text('Billable')), + const ButtonSegment(value: 0, label: Text('Not billable')), + ], + selected: {f.billable}, + showSelectedIcon: false, + onSelectionChanged: (v) => setState(() => f.billable = v.first), + ), + if (f.billable == null) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Text(pBsrc != null ? 'from ${pBsrc.name}' : 'the default', style: const TextStyle(color: muted, fontSize: 12.5)), + ), + const SizedBox(height: 16), + TextField( + controller: currency, + maxLength: 3, + textCapitalization: TextCapitalization.characters, + decoration: InputDecoration( + labelText: 'Currency', + hintText: '$pCur (inherited)', + border: const OutlineInputBorder(), + errorText: errorField == 'currency' ? error : null, + counterText: '', + ), + ), + const SizedBox(height: 16), + Row( + children: [ + const Expanded( + child: Text('Hourly rate', style: TextStyle(color: muted)), + ), + TextButton.icon( + onPressed: () => setState(() { + rateCtl.add(TextEditingController()); + sinceList.add(rateCtl.length == 1 ? '' : todayIso); + }), + icon: const Icon(Icons.add), + label: Text(rateCtl.isEmpty ? 'Own rate' : 'New rate from a day'), + ), + ], + ), + if (rateCtl.isEmpty) + Text('${num0(pRate)} $pCur/h — ${pRsrc != null ? 'from ${pRsrc.name}' : 'the default'}', style: const TextStyle(color: muted)), + for (var i = 0; i < rateCtl.length; i++) + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: () => _since(i), + onLongPress: () => setState(() => sinceList[i] = ''), + child: Text(sinceList[i].isEmpty ? 'Always' : 'From ${sinceList[i]}'), + ), + ), + const SizedBox(width: 8), + SizedBox( + width: 110, + child: TextField( + controller: rateCtl[i], + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: InputDecoration( + isDense: true, + border: const OutlineInputBorder(), + suffixText: '/h', + errorText: errorField == 'rates.$i.rate' || errorField == 'rates.$i.since' ? '!' : null, + ), + ), + ), + IconButton( + onPressed: () => setState(() { + rateCtl.removeAt(i); + sinceList.removeAt(i); + }), + icon: const Icon(Icons.close, color: muted), + ), + ], + ), + ), + if (errorField?.startsWith('rates.') == true) Text(error!, style: const TextStyle(color: bad)), + if (rateCtl.isNotEmpty) + const Text( + 'A rate counts from its day on; earlier work keeps the rate it had. Long-press a day = always.', + style: TextStyle(color: muted, fontSize: 12), + ), + const SizedBox(height: 16), + TextField( + controller: notes, + minLines: 2, + maxLines: 8, + decoration: const InputDecoration(labelText: 'Notes', border: OutlineInputBorder()), + ), + const SizedBox(height: 8), + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Archived'), + subtitle: const Text('Hidden from the picker; its time stays in reports', style: TextStyle(color: muted)), + value: f.archived, + onChanged: (v) => setState(() => f.archived = v), + ), + if (error != null && errorField == null) Text(error!, style: const TextStyle(color: bad)), + const SizedBox(height: 12), + Row( + children: [ + if (!isNew) + booked > 0 + ? Text('${hm(booked)} booked — archive instead of deleting', style: const TextStyle(color: muted, fontSize: 12.5)) + : TextButton.icon( + onPressed: _delete, + icon: Icon(Icons.delete_outline, color: armed ? bad : muted), + label: Text( + armed ? 'Tap again to delete (with everything under it)' : 'Delete', + style: TextStyle(color: armed ? bad : muted), + ), + ), + const Spacer(), + FilledButton(onPressed: _save, child: const Text('Save')), + ], + ), + ], + ), + ); + } +} diff --git a/app/lib/work/entry_sheet.dart b/app/lib/work/entry_sheet.dart new file mode 100644 index 0000000..0ab87ee --- /dev/null +++ b/app/lib/work/entry_sheet.dart @@ -0,0 +1,432 @@ +// Booking time (the web page's entry form as a bottom sheet): what it was for — one picker for the +// whole tree + the recent ones as chips —, the day, start and end (an end at or before the start +// = the next day), billable (the tree's default + where it comes from), the rate and amount it +// comes to on that day, a note. Delete = tap twice. The last thing booked is remembered. +import 'package:flutter/material.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'work_model.dart'; + +Color hexColor(String hex) => Color(int.parse('ff${hex.substring(1)}', radix: 16)); + +String hhmm(int minutes) => '${two(minutes ~/ 60 % 24)}:${two(minutes % 60)}'; + +const _dow = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; +const _mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; +String dayLabel(DateTime d) => '${_dow[d.weekday - 1]} ${d.day} ${_mon[d.month - 1]}${d.year != DateTime.now().year ? ' ${d.year}' : ''}'; + +/// A new entry at [day] from [startMin] (default: now, rounded down to 15 minutes), or [entry] to edit. +Future openEntry( + BuildContext context, + SyncService sync, { + WorkEntry? entry, + DateTime? day, + int? startMin, + int? endMin, + String? node, + String note = '', + WorkSettings s = const WorkSettings(), +}) => showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => EntrySheet(sync: sync, entry: entry, day: day, startMin: startMin, endMin: endMin, node: node, note: note, s: s), +); + +class EntrySheet extends StatefulWidget { + const EntrySheet({ + super.key, + required this.sync, + this.entry, + this.day, + this.startMin, + this.endMin, + this.node, + this.note = '', + required this.s, + }); + final SyncService sync; + final WorkEntry? entry; + final DateTime? day; + final int? startMin, endMin; + final String? node; // a guess (an Activity block's customer); the last one booked otherwise + final String note; // a calendar event's title, an Activity block's items + final WorkSettings s; + @override + State createState() => _EntrySheetState(); +} + +class _EntrySheetState extends State { + late Tree t = Tree(widget.sync.store, widget.s); + late EntryForm f; + late final note = TextEditingController(text: f.note); + bool billableTouched = false, armed = false; + String? error, errorField; + + @override + void initState() { + super.initState(); + final e = widget.entry; + if (e != null) { + final d0 = dayOf(e.s); + f = EntryForm( + id: e.id, + node: e.node, + day: d0, + startMin: e.s.difference(d0).inMinutes, + endMin: e.e.difference(dayOf(e.e)).inMinutes, + endDay: e.e.difference(d0).inDays > 1 ? dayOf(e.e) : null, + billable: e.billable, + note: e.note, + ); + billableTouched = true; // an entry's own billable stays as it is + } else { + final now = DateTime.now(); + final start = widget.startMin ?? (now.hour * 60 + now.minute) ~/ 15 * 15; + var last = widget.node != null && t.nodes.containsKey(widget.node) ? widget.node : widget.sync.store.metaText('work_last'); + if (last != null && (!t.nodes.containsKey(last) || t.archived(last))) last = null; + last ??= recent(widget.sync.store, t, 1).firstOrNull; + f = EntryForm( + node: last, + day: widget.day ?? dayOf(now), + startMin: start, + endMin: widget.endMin ?? start + widget.s.defaultMinutes, + billable: t.billable(last).$1, + note: widget.note, + ); + } + } + + void _pick(String nid) => setState(() { + f.node = nid; + if (!billableTouched) f.billable = t.billable(nid).$1; + if (errorField == 'node_id') error = errorField = null; + }); + + Future _chooseNode() async { + final nid = await showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: card, + builder: (_) => NodePicker(tree: t, recent: recent(widget.sync.store, t), current: f.node), + ); + if (nid != null) _pick(nid); + } + + Future _time(bool start) async { + final m = start ? f.startMin : f.endMin; + final p = await showTimePicker( + context: context, + initialTime: TimeOfDay(hour: m ~/ 60 % 24, minute: m % 60), + builder: (c, child) => MediaQuery(data: MediaQuery.of(c).copyWith(alwaysUse24HourFormat: true), child: child!), + ); + if (p == null) return; + setState(() { + final v = p.hour * 60 + p.minute; + if (start) { + final dur = f.endMin - f.startMin; // moving the start keeps the length + f.startMin = v; + if (f.endDay == null) f.endMin = v + (dur > 0 ? dur : widget.s.defaultMinutes); + } else { + f.endMin = v; + } + }); + } + + Future _date() async { + final p = await showDatePicker(context: context, initialDate: f.day, firstDate: DateTime(2000), lastDate: DateTime(2100)); + if (p != null) setState(() => f.day = dayOf(p)); + } + + void _save() { + f.note = note.text; // an end past 24:00 (start + length, the + chips) is the next day's time: span() adds it to the day + try { + final id = saveEntry(widget.sync.store, t, f); + widget.sync.store.setMetaText('work_last', f.node); + widget.sync.changed(); + Navigator.pop(context, id); + } on Invalid catch (e) { + setState(() { + error = e.message; + errorField = e.field; + }); + } + } + + void _delete() { + if (!armed) { + setState(() => armed = true); + return; + } + deleteEntry(widget.sync.store, f.id!); + widget.sync.changed(); + Navigator.pop(context); + } + + @override + Widget build(BuildContext context) { + final (a, b) = f.span(); + final dur = b.difference(a).inMinutes; + final nid = f.node; + final (rate, rsrc) = t.rate(nid, fmtDay(f.day)); + final cur = t.currency(nid); + final (defB, bsrc) = t.billable(nid); + final rec = recent(widget.sync.store, t).where((i) => i != nid).take(4).toList(); + return Padding( + padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), + child: SingleChildScrollView( + padding: const EdgeInsets.fromLTRB(16, 14, 16, 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + f.id == null ? 'Book time' : 'Edit entry', + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent), + ), + const SizedBox(height: 10), + if (t.isEmpty) + const Padding( + padding: EdgeInsets.only(bottom: 8), + child: Text('No customers yet — add one under ⋮ ▸ Customers first.', style: TextStyle(color: bad)), + ), + // what for + InkWell( + borderRadius: BorderRadius.circular(10), + onTap: t.isEmpty ? null : _chooseNode, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 12), + decoration: BoxDecoration( + color: card2, + borderRadius: BorderRadius.circular(10), + border: errorField == 'node_id' ? Border.all(color: bad) : null, + ), + child: Row( + children: [ + Icon(Icons.circle, size: 12, color: nid == null ? muted : hexColor(t.colour(nid))), + const SizedBox(width: 10), + Expanded( + child: Text( + nid == null ? 'What did you work on?' : t.path(nid), + style: TextStyle(fontSize: 15.5, color: nid == null ? muted : Colors.white), + ), + ), + const Icon(Icons.unfold_more, color: muted), + ], + ), + ), + ), + if (rec.isNotEmpty) ...[ + const SizedBox(height: 6), + Wrap( + spacing: 6, + runSpacing: 4, + children: [ + for (final r in rec) + ActionChip( + avatar: Icon(Icons.circle, size: 10, color: hexColor(t.colour(r))), + label: Text(t.nodes[r]!.name), + onPressed: () => _pick(r), + ), + ], + ), + ], + const SizedBox(height: 12), + // when + Row( + children: [ + Expanded(flex: 5, child: _field(Icons.event, dayLabel(f.day), _date)), + const SizedBox(width: 6), + Expanded(flex: 3, child: _field(null, hhmm(f.startMin), () => _time(true))), + const Padding( + padding: EdgeInsets.symmetric(horizontal: 4), + child: Text('–', style: TextStyle(color: muted)), + ), + Expanded(flex: 3, child: _field(null, hhmm(f.endMin), () => _time(false), bad: errorField == 'end')), + ], + ), + const SizedBox(height: 4), + Text( + [hm(dur > 0 ? dur : 0), if (!dayOf(b).isAtSameMomentAs(f.day) && dur > 0) 'ends ${dayLabel(dayOf(b))}'].join(' · '), + style: const TextStyle(color: muted), + ), + const SizedBox(height: 4), + Wrap( + spacing: 6, + children: [ + for (final m in const [15, 30, 60, 120]) + ActionChip(label: Text(m < 60 ? '+$m min' : '+${m ~/ 60} h'), onPressed: () => setState(() => f.endMin += m)), + ], + ), + const SizedBox(height: 6), + // billable + money + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Billable'), + subtitle: Text( + nid == null ? '' : 'Default: ${defB ? 'billable' : 'not billable'}${bsrc != null ? ' (from ${bsrc.name})' : ''}', + style: const TextStyle(color: muted), + ), + value: f.billable, + onChanged: (v) => setState(() { + f.billable = v; + billableTouched = true; + }), + ), + if (nid != null && f.billable) + Text( + '${num0(rate)} $cur/h${rsrc != null ? ' from ${rsrc.name}' : ' (default)'} = ${money(dur > 0 ? dur / 60 * rate : 0, cur)}', + style: const TextStyle(color: muted), + ), + const SizedBox(height: 10), + TextField( + controller: note, + minLines: 1, + maxLines: 5, + decoration: const InputDecoration(labelText: 'Note', border: OutlineInputBorder()), + ), + if (error != null) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(error!, style: const TextStyle(color: bad)), + ), + const SizedBox(height: 12), + Row( + children: [ + if (f.id != null) + TextButton.icon( + onPressed: _delete, + icon: Icon(Icons.delete_outline, color: armed ? bad : muted), + label: Text(armed ? 'Tap again to delete' : 'Delete', style: TextStyle(color: armed ? bad : muted)), + ), + const Spacer(), + TextButton(onPressed: () => Navigator.pop(context), child: const Text('Cancel')), + const SizedBox(width: 6), + FilledButton(onPressed: t.isEmpty ? null : _save, child: const Text('Save')), + ], + ), + ], + ), + ), + ); + } + + Widget _field(IconData? icon, String text, VoidCallback onTap, {bool bad = false}) => InkWell( + borderRadius: BorderRadius.circular(10), + onTap: onTap, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 12), + decoration: BoxDecoration( + color: card2, + borderRadius: BorderRadius.circular(10), + border: bad ? Border.all(color: const Color(0xFFFF9A9A)) : null, + ), + child: Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + if (icon != null) ...[Icon(icon, size: 16, color: muted), const SizedBox(width: 6)], + Flexible( + child: Text(text, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 15.5)), + ), + ], + ), + ), + ); +} + +/// The whole tree to pick from (the form's picker): a search box, the recent ones, then every live +/// node indented under its parent. Archived ones only when searching (or the current one). +class NodePicker extends StatefulWidget { + const NodePicker({super.key, required this.tree, required this.recent, this.current, this.only}); + final Tree tree; + final List recent; + final String? current; + final bool Function(Node)? only; // e.g. parents allowed for a kind + @override + State createState() => _NodePickerState(); +} + +class _NodePickerState extends State { + String q = ''; + + @override + Widget build(BuildContext context) { + final t = widget.tree; + final words = q.toLowerCase().split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList(); + final rows = [ + for (final (n, d) in t.walk(archived: true)) + if ((widget.only?.call(n) ?? true) && + (words.isEmpty ? (!t.archived(n.id) || n.id == widget.current) : words.every(t.path(n.id).toLowerCase().contains))) + (n, d), + ]; + return SizedBox( + height: MediaQuery.of(context).size.height * .75, + child: Padding( + padding: EdgeInsets.only(bottom: MediaQuery.of(context).viewInsets.bottom), + child: Column( + children: [ + Padding( + padding: const EdgeInsets.fromLTRB(12, 12, 12, 6), + child: TextField( + autofocus: false, + decoration: const InputDecoration( + prefixIcon: Icon(Icons.search), + hintText: 'Customer, project, task…', + border: OutlineInputBorder(), + ), + onChanged: (v) => setState(() => q = v), + ), + ), + if (words.isEmpty && widget.recent.isNotEmpty && widget.only == null) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: Wrap( + spacing: 6, + children: [ + for (final r in widget.recent) + ActionChip( + avatar: Icon(Icons.history, size: 15, color: hexColor(t.colour(r))), + label: Text(t.nodes[r]!.name), + onPressed: () => Navigator.pop(context, r), + ), + ], + ), + ), + Expanded( + child: rows.isEmpty + ? const Center( + child: Text('Nothing matches', style: TextStyle(color: muted)), + ) + : ListView( + children: [ + for (final (n, d) in rows) + ListTile( + dense: true, + selected: n.id == widget.current, + contentPadding: EdgeInsets.only(left: 16.0 + (words.isEmpty ? d * 18 : 0), right: 12), + leading: Icon( + n.kind == 'task' + ? Icons.check_box_outline_blank + : n.kind == 'project' + ? Icons.folder_outlined + : Icons.business, + size: 18, + color: hexColor(t.colour(n.id)), + ), + title: Text( + words.isEmpty ? n.name : t.path(n.id), + style: TextStyle(fontSize: 15, color: t.archived(n.id) ? muted : null), + ), + subtitle: t.archived(n.id) ? const Text('archived', style: TextStyle(color: muted)) : null, + onTap: () => Navigator.pop(context, n.id), + ), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/app/lib/work/report_page.dart b/app/lib/work/report_page.dart new file mode 100644 index 0000000..5bc2036 --- /dev/null +++ b/app/lib/work/report_page.dart @@ -0,0 +1,239 @@ +// Report (the web's /work/report): a range — this / last week, month, year, or any days — and +// optionally one customer; the totals, the tree with hours / billable / money per node, and every +// entry (tap = edit). "Copy CSV" puts the entries on the clipboard in the Pi's CSV columns. +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'entry_sheet.dart'; +import 'work_model.dart'; + +class ReportPage extends StatefulWidget { + const ReportPage({super.key, required this.sync, this.s = const WorkSettings()}); + final SyncService sync; + final WorkSettings s; + @override + State createState() => _ReportPageState(); +} + +class _ReportPageState extends State { + String preset = 'month'; + late (DateTime, DateTime) range = presetRange('month')!; + String? client; + + String _amounts(Agg a) => + (a.amounts.entries.toList()..sort((x, y) => x.key.compareTo(y.key))).map((e) => money(e.value, e.key)).join(' · '); + + Future _custom() async { + final p = await showDateRangePicker( + context: context, + firstDate: DateTime(2000), + lastDate: DateTime(2100), + initialDateRange: DateTimeRange(start: range.$1, end: range.$2), + ); + if (p != null) { + setState(() { + preset = 'custom'; + range = (dayOf(p.start), dayOf(p.end)); + }); + } + } + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: widget.sync, + builder: (context, _) { + final store = widget.sync.store; + final t = Tree(store, widget.s); + final r = report(store, t, range.$1, range.$2, client: client); + final clients = [ + for (final (n, d) in t.walk(archived: true)) + if (n.kind == 'client') (n, d), + ]; + return Scaffold( + appBar: AppBar( + title: const Text('Report'), + actions: [ + IconButton( + tooltip: 'Copy as CSV', + icon: const Icon(Icons.copy_all), + onPressed: r.items.isEmpty + ? null + : () async { + await Clipboard.setData(ClipboardData(text: reportCsv(r, t))); + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('${r.items.length} entries copied as CSV'))); + } + }, + ), + ], + ), + body: ListView( + padding: const EdgeInsets.fromLTRB(12, 6, 12, 24), + children: [ + Wrap( + spacing: 6, + runSpacing: 4, + children: [ + for (final (k, label) in presets) + ChoiceChip( + label: Text(label), + selected: preset == k, + onSelected: (_) => setState(() { + preset = k; + range = presetRange(k)!; + }), + ), + ChoiceChip( + label: Text(preset == 'custom' ? '${dayLabel(range.$1)} – ${dayLabel(range.$2)}' : 'Days…'), + selected: preset == 'custom', + onSelected: (_) => _custom(), + ), + ], + ), + const SizedBox(height: 8), + DropdownButtonFormField( + initialValue: client, + isExpanded: true, + decoration: const InputDecoration(labelText: 'Customer', border: OutlineInputBorder(), isDense: true), + items: [ + const DropdownMenuItem(value: null, child: Text('Everyone')), + for (final (n, d) in clients) DropdownMenuItem(value: n.id, child: Text('${' ' * d}${n.name}')), + ], + onChanged: (v) => setState(() => client = v), + ), + const SizedBox(height: 10), + Card( + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('${dayLabel(range.$1)} – ${dayLabel(range.$2)}', style: const TextStyle(color: muted)), + const SizedBox(height: 4), + Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text(hm(r.total.m), style: const TextStyle(fontSize: 26, fontWeight: FontWeight.bold)), + const SizedBox(width: 8), + Text('${(r.total.m / 60).toStringAsFixed(2)} h', style: const TextStyle(color: muted)), + const Spacer(), + Text(_amounts(r.total), style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w600)), + ], + ), + Text.rich( + TextSpan( + children: [ + TextSpan( + text: '${hm(r.total.bm)} billable', + style: const TextStyle(color: good), + ), + TextSpan( + text: ' · ${hm(r.total.m - r.total.bm)} not billable', + style: const TextStyle(color: muted), + ), + ], + ), + ), + ], + ), + ), + ), + if (r.rows.isEmpty) + const Padding( + padding: EdgeInsets.all(24), + child: Center( + child: Text('Nothing booked in this range', style: TextStyle(color: muted)), + ), + ), + if (r.rows.isNotEmpty) ...[ + const SizedBox(height: 10), + Card( + child: Column( + children: [ + for (final row in r.rows) + ListTile( + dense: true, + contentPadding: EdgeInsets.only(left: 12.0 + row.depth * 18, right: 12), + leading: Icon(Icons.circle, size: 11, color: hexColor(t.colour(row.node.id))), + minLeadingWidth: 10, + title: Text(row.node.name, style: TextStyle(fontWeight: row.depth == 0 ? FontWeight.bold : null)), + subtitle: Text( + '${hm(row.agg.bm)} billable${row.agg.m > row.agg.bm ? ' · ${hm(row.agg.m - row.agg.bm)} not' : ''}', + style: const TextStyle(color: muted, fontSize: 12), + ), + trailing: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text(hm(row.agg.m), style: const TextStyle(fontWeight: FontWeight.w600)), + if (row.agg.amounts.isNotEmpty) Text(_amounts(row.agg), style: const TextStyle(fontSize: 12, color: muted)), + ], + ), + onTap: row.node.kind == 'client' ? () => setState(() => client = row.node.id) : null, + ), + ], + ), + ), + const SizedBox(height: 14), + Text( + 'Entries (${r.items.length})', + style: const TextStyle(color: muted, fontWeight: FontWeight.w600), + ), + const SizedBox(height: 4), + ..._entries(t, r), + ], + ], + ), + ); + }, + ); + + List _entries(Tree t, Report r) { + final out = []; + String? lastDay; + for (final i in r.items) { + final e = i.e, d = e.start.substring(0, 10); + if (d != lastDay) { + out.add( + Padding( + padding: const EdgeInsets.fromLTRB(4, 10, 4, 2), + child: Text( + dayLabel(dayOf(e.s)), + style: const TextStyle(color: accent, fontWeight: FontWeight.w600), + ), + ), + ); + lastDay = d; + } + out.add( + Card( + margin: const EdgeInsets.only(bottom: 4), + child: ListTile( + dense: true, + leading: Container(width: 4, height: 36, color: hexColor(t.colour(e.node))), + minLeadingWidth: 4, + title: Text(t.path(e.node)), + subtitle: Text( + ['${e.start.substring(11)}–${e.end.substring(11)}', if (e.note.isNotEmpty) e.note.split('\n').first].join(' · '), + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle(color: muted), + ), + trailing: Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text(hm(e.minutes), style: const TextStyle(fontWeight: FontWeight.w600)), + Text(e.billable ? money(i.amount, i.currency) : 'not billable', style: const TextStyle(fontSize: 12, color: muted)), + ], + ), + onTap: () => openEntry(context, widget.sync, entry: e, s: widget.s), + ), + ), + ); + } + return out; + } +} diff --git a/app/lib/work/work_model.dart b/app/lib/work/work_model.dart new file mode 100644 index 0000000..8e0f75a --- /dev/null +++ b/app/lib/work/work_model.dart @@ -0,0 +1,799 @@ +// The workload tracker — a port of the dashboard's plugins/workload: db.py (the tree, inheritance, +// rate history, what an entry is) and views.py (week totals, the report). Keep them in step. +// +// Synced rows (workload.db, ids = the Pi's _uid; references are those ids): +// "workload.node" {kind client|project|task, parent_id, name, colour, billable 0/1/null, currency, +// notes, archived 0/1, created} +// "workload.rate" {node_id, since 'YYYY-MM-DD' | '0000-01-01' = always, rate} id = ':' +// "workload.entry" {node_id, start, end 'YYYY-MM-DD HH:MM' local, billable 0/1, note, created, updated} +import 'dart:convert'; + +import '../sync/store.dart'; + +const kinds = ['client', 'project', 'task']; +const parentsOf = { + 'client': [null, 'client'], + 'project': ['client'], + 'task': ['client', 'project'], +}; +const palette = ['#ffb33a', '#5cc8ff', '#7fd6a3', '#ff6b7a', '#c792ea', '#ff9d5c', '#82aaff', '#f78c6c', '#c3e88d', '#89ddff']; +const epoch = '0000-01-01'; // a rate "since" this applies to all work +const tNode = 'workload.node', tRate = 'workload.rate', tEntry = 'workload.entry'; + +/// Until settings sync: the dashboard's Settings ▸ Work defaults. +class WorkSettings { + const WorkSettings({ + this.currency = 'EUR', + this.defaultRate = 0, + this.dayStart = 7, + this.dayEnd = 19, + this.defaultMinutes = 60, + this.weekTarget = 40, + }); + final String currency; + final double defaultRate; + final int dayStart, dayEnd, defaultMinutes; + final double weekTarget; +} + +class Invalid implements Exception { + Invalid(this.field, this.message); + final String field, message; + @override + String toString() => message; +} + +// ---- times ------------------------------------------------------------------------------- + +String two(int n) => n.toString().padLeft(2, '0'); +String fmtDay(DateTime d) => '${d.year}-${two(d.month)}-${two(d.day)}'; +String fmtMin(DateTime d) => '${fmtDay(d)} ${two(d.hour)}:${two(d.minute)}'; +String fmtSec(DateTime d) => '${fmtMin(d)}:${two(d.second)}'; +// Wall-clock time, like the Pi (naive datetimes): every date here is a UTC DateTime holding the local +// fields, so a day is always 24 h and a week 7 × 24 h — summer time never shifts a block or a week number. +DateTime parseMin(String s) => DateTime.parse('${s.replaceFirst(' ', 'T')}Z'); +DateTime dayOf(DateTime d) => DateTime.utc(d.year, d.month, d.day); + +/// Monday 00:00 of the week [offset] weeks from this one (views.week_start). +DateTime weekStart(int offset, [DateTime? now]) { + final t = dayOf(now ?? DateTime.now()); + return DateTime.utc(t.year, t.month, t.day - (t.weekday - 1) + 7 * offset); +} + +/// The ISO week number of a week's Monday (Python's isocalendar()[1]). +int isoWeek(DateTime monday) { + final thu = DateTime.utc(monday.year, monday.month, monday.day + 3); + return thu.difference(DateTime.utc(thu.year, 1, 1)).inDays ~/ 7 + 1; +} + +/// 90 → '1:30' (views.hm). +String hm(num minutes) { + final m = minutes.round(); + return '${m ~/ 60}:${two(m % 60)}'; +} + +/// 1234.5 → '1 234.50 EUR' (views.money). +String money(double amount, String currency) { + final s = amount.toStringAsFixed(2), dot = s.indexOf('.'); + final neg = s.startsWith('-'); + final digits = s.substring(neg ? 1 : 0, dot); + final b = StringBuffer(neg ? '-' : ''); + for (var i = 0; i < digits.length; i++) { + if (i > 0 && (digits.length - i) % 3 == 0) b.write(' '); + b.write(digits[i]); + } + return '$b${s.substring(dot)} $currency'; +} + +/// A rate as the Pi's f"{rate:g}" would print it (20.0 → '20', 22.5 → '22.5'). +String num0(double v) => v == v.roundToDouble() ? v.round().toString() : v.toString(); + +// ---- rows -------------------------------------------------------------------------------- + +class Node { + Node(this.r); + final Map r; + String get id => r['_u'] as String; + String get kind => r['kind'] as String; + String? get parent => r['parent_id'] as String?; + String get name => r['name'] as String? ?? '?'; + String? get colour => r['colour'] as String?; + int? get billable => (r['billable'] as num?)?.toInt(); + String? get currency => r['currency'] as String?; + String get notes => r['notes'] as String? ?? ''; + bool get archived => (r['archived'] as num? ?? 0) != 0; + bool get isSub => kind == 'client' && parent != null; +} + +class Rate { + Rate(this.since, this.rate); + final String since; + final double rate; +} + +class WorkEntry { + WorkEntry(this.r) : s = parseMin(r['start'] as String), e = parseMin(r['end'] as String); + final Map r; + final DateTime s, e; + String get id => r['_u'] as String; + String get node => r['node_id'] as String; + String get start => r['start'] as String; + String get end => r['end'] as String; + bool get billable => (r['billable'] as num? ?? 0) != 0; + String get note => r['note'] as String? ?? ''; + double get minutes => e.difference(s).inSeconds / 60; +} + +// ---- the tree ---------------------------------------------------------------------------- + +/// All nodes + rates in memory (db.Tree): inheritance, paths, the picker list. +class Tree { + Tree(SyncStore store, [this.s = const WorkSettings()]) { + final ns = store.rows(tNode).map(Node.new).toList()..sort((a, b) => a.name.toLowerCase().compareTo(b.name.toLowerCase())); + for (final n in ns) { + nodes[n.id] = n; + } + for (final r in store.rows(tRate)) { + final nid = r['node_id'] as String?; + if (nid == null) continue; + rates.putIfAbsent(nid, () => []).add(Rate(r['since'] as String, (r['rate'] as num).toDouble())); + } + for (final l in rates.values) { + l.sort((a, b) => a.since.compareTo(b.since)); + } + for (final n in nodes.values) { + // a parent that isn't here (yet) → shown at the top until it arrives + children.putIfAbsent(nodes.containsKey(n.parent) ? n.parent : null, () => []).add(n.id); + } + } + + final WorkSettings s; + final nodes = {}; + final rates = >{}; + final children = >{}; + + bool get isEmpty => nodes.isEmpty; + + /// The node and its ancestors, nearest first. + List chain(String? nid) { + final out = [], seen = {}; + while (nid != null && nodes.containsKey(nid) && seen.add(nid)) { + out.add(nodes[nid]!); + nid = nodes[nid]!.parent; + } + return out; + } + + String path(String nid, [String sep = ' › ']) => chain(nid).reversed.map((n) => n.name).join(sep); + + /// The top-level customer a node belongs to. + Node? clientOf(String nid) { + final c = chain(nid); + return c.isEmpty ? null : c.last; + } + + (T, Node?) _inherit(String? nid, T? Function(Node) key, T def) { + for (final n in chain(nid)) { + final v = key(n); + if (v != null) return (v, n); + } + return (def, null); + } + + String colour(String? nid) => _inherit(nid, (n) => n.colour, palette[0]).$1; + String currency(String? nid) => _inherit(nid, (n) => n.currency, s.currency).$1; + + /// (default billable for new entries, the node it comes from or null = default yes). + (bool, Node?) billable(String? nid) { + final (v, src) = _inherit(nid, (n) => n.billable, 1); + return (v != 0, src); + } + + /// (hourly rate on [day] 'YYYY-MM-DD', the node it comes from or null = the default rate): + /// the nearest node with a rate in force that day wins. + (double, Node?) rate(String? nid, String day) { + for (final n in chain(nid)) { + Rate? best; + for (final r in rates[n.id] ?? const []) { + if (r.since.compareTo(day) <= 0) best = r; + } + if (best != null) return (best.rate, n); + } + return (s.defaultRate, null); + } + + bool archived(String nid) => chain(nid).any((n) => n.archived); + + /// Depth-first (node, depth): under each node its sub-customers, then projects, then tasks. + Iterable<(Node, int)> walk({String? parent, int depth = 0, bool archived = false}) sync* { + const order = {'client': 0, 'project': 1, 'task': 2}; + final kids = [...?children[parent]] + ..sort((a, b) { + final x = nodes[a]!, y = nodes[b]!; + final k = order[x.kind]!.compareTo(order[y.kind]!); + return k != 0 ? k : x.name.toLowerCase().compareTo(y.name.toLowerCase()); + }); + for (final i in kids) { + final n = nodes[i]!; + if (n.archived && !archived) continue; + yield (n, depth); + yield* walk(parent: i, depth: depth + 1, archived: archived); + } + } + + Set subtree(String nid) { + final out = {}, todo = [nid]; + while (todo.isNotEmpty) { + final i = todo.removeLast(); + if (out.add(i)) todo.addAll(children[i] ?? const []); + } + return out; + } + + /// One entry → (minutes, amount, currency); unbillable work is worth 0 (views._amount). + (double, double, String) amount(WorkEntry e) { + final cur = currency(e.node); + if (!e.billable) return (e.minutes, 0, cur); + return (e.minutes, e.minutes / 60 * rate(e.node, e.start.substring(0, 10)).$1, cur); + } + + /// "A sub-customer" / "A project" … for labels. + static String kindLabel(Node n) => n.isSub ? 'Sub-customer' : const {'client': 'Customer', 'project': 'Project', 'task': 'Task'}[n.kind]!; +} + +// ---- entries ----------------------------------------------------------------------------- + +/// Entries overlapping [start, end) (entries_between); [keep] = node ids to keep. +List entriesBetween(SyncStore store, DateTime start, DateTime end, {Set? keep}) { + final out = [ + for (final r in store.rows( + tEntry, + where: "json_extract(data, '\$.start') < ? AND json_extract(data, '\$.end') > ?", + args: [fmtMin(end), fmtMin(start)], + )) + WorkEntry(r), + ]..sort((a, b) => a.start.compareTo(b.start)); + return keep == null ? out : out.where((e) => keep.contains(e.node)).toList(); +} + +/// The last few distinct nodes worked on (the form's chips), live ones only (db.recent). +List recent(SyncStore store, Tree t, [int n = 5]) { + final last = {}; + for (final r in store.rows(tEntry)) { + final nid = r['node_id'] as String?, u = r['updated'] as String? ?? ''; + if (nid != null && u.compareTo(last[nid] ?? '') > 0) last[nid] = u; + } + final ids = last.keys.toList()..sort((a, b) => last[b]!.compareTo(last[a]!)); + return ids.where((i) => t.nodes.containsKey(i) && !t.archived(i)).take(n).toList(); +} + +/// What the entry form submits (db.clean_entry): times as picked; an end at or before the start +/// on the same day means it ends the next day (23:00 – 01:00). +class EntryForm { + EntryForm({ + this.id, + this.node, + required this.day, + required this.startMin, + required this.endMin, + this.endDay, + required this.billable, + this.note = '', + }); + String? id, node; + DateTime day; // the start's day + int startMin, endMin; // minutes after midnight + DateTime? endDay; // only when it was set on purpose (else: same day, or the next one) + bool billable; + String note; + + (DateTime, DateTime) span() { + final a = day.add(Duration(minutes: startMin)); + var b = (endDay ?? day).add(Duration(minutes: endMin)); + if (!b.isAfter(a) && endDay == null) b = b.add(const Duration(days: 1)); + return (a, b); + } +} + +Map cleanEntry(EntryForm f, Tree t) { + if (f.node == null || !t.nodes.containsKey(f.node)) throw Invalid('node_id', 'Choose what you worked on.'); + final (a, b) = f.span(); + if (!b.isAfter(a)) throw Invalid('end', 'The end must be after the start.'); + if (b.difference(a).inSeconds > 24 * 3600) throw Invalid('end', 'At most 24 hours in one entry.'); + final note = f.note.trim(); + return { + 'node_id': f.node, + 'start': fmtMin(a), + 'end': fmtMin(b), + 'billable': f.billable ? 1 : 0, + 'note': note.length > 2000 ? note.substring(0, 2000) : note, + }; +} + +/// Create or update an entry → its id. +String saveEntry(SyncStore store, Tree t, EntryForm f) { + final v = cleanEntry(f, t), now = fmtSec(DateTime.now()); + if (f.id == null) { + final id = SyncStore.randomId(); + store.put(tEntry, id, {...v, 'created': now, 'updated': now}); + return id; + } + final old = store.row(tEntry, f.id!); + if (old == null) throw Invalid('node_id', 'This entry was deleted meanwhile.'); + store.put(tEntry, f.id!, {...old, ...v, 'updated': now}); + return f.id!; +} + +void deleteEntry(SyncStore store, String id) => store.delete(tEntry, id); + +// ---- nodes ------------------------------------------------------------------------------- + +class NodeForm { + NodeForm({ + this.id, + required this.kind, + this.parent, + this.name = '', + this.colour, + this.billable, + this.currency = '', + this.notes = '', + this.archived = false, + List<(String, String)>? rates, + }) : rates = rates ?? []; + String? id, parent, colour; + String kind, name, currency, notes; + int? billable; // null = inherit + bool archived; + List<(String, String)> rates; // (since '' = always, rate as typed) + + factory NodeForm.of(Tree t, Node n) => NodeForm( + id: n.id, + kind: n.kind, + parent: n.parent, + name: n.name, + colour: n.colour, + billable: n.billable, + currency: n.currency ?? '', + notes: n.notes, + archived: n.archived, + rates: [for (final r in t.rates[n.id] ?? const []) (r.since == epoch ? '' : r.since, num0(r.rate))], + ); +} + +/// db._clean_node + _save_rates → (row, rates {since: rate}). +(Map, Map) cleanNode(NodeForm f, Tree t) { + final name = f.name.trim(); + if (name.isEmpty) throw Invalid('name', 'Give it a name.'); + if (name.length > 80) throw Invalid('name', 'At most 80 characters.'); + final kind = f.id == null ? f.kind : t.nodes[f.id]!.kind; + if (!kinds.contains(kind)) throw Invalid('kind', 'Unknown kind.'); + final parent = f.parent; + if (parent != null && !t.nodes.containsKey(parent)) throw Invalid('parent_id', 'That parent no longer exists.'); + final pkind = parent == null ? null : t.nodes[parent]!.kind; + if (!parentsOf[kind]!.contains(pkind)) { + throw Invalid( + 'parent_id', + const { + 'client': 'A sub-customer goes under a customer.', + 'project': 'A project goes under a customer.', + 'task': 'A task goes under a customer or a project.', + }[kind]!, + ); + } + if (f.id != null && parent != null && t.subtree(f.id!).contains(parent)) throw Invalid('parent_id', "It can't go under itself."); + var colour = f.colour; + if (colour != null && !RegExp(r'^#[0-9a-fA-F]{6}$').hasMatch(colour)) throw Invalid('colour', 'A colour like #ffb33a.'); + if (kind == 'client' && parent == null && colour == null) { + // customers always have one + final used = { + for (final n in t.nodes.values) + if (n.parent == null && n.id != f.id) n.colour, + }; + colour = palette.firstWhere((c) => !used.contains(c), orElse: () => palette[used.length % palette.length]); + } + final currency = f.currency.trim().toUpperCase(); + if (currency.isNotEmpty && !RegExp(r'^[A-Z]{3}$').hasMatch(currency)) throw Invalid('currency', 'A 3-letter code like EUR or RON.'); + final rates = {}; + for (var i = 0; i < f.rates.length; i++) { + final (sinceRaw, rateRaw) = f.rates[i]; + final raw = rateRaw.trim().replaceAll(',', '.'); + if (raw.isEmpty) continue; + final rate = double.tryParse(raw); + if (rate == null) throw Invalid('rates.$i.rate', 'The rate must be a number.'); + if (rate < 0 || rate > 100000) throw Invalid('rates.$i.rate', 'Between 0 and 100000.'); + final since = sinceRaw.trim().isEmpty ? epoch : sinceRaw.trim(); + if (since != epoch && (DateTime.tryParse(since) == null || !RegExp(r'^\d{4}-\d\d-\d\d$').hasMatch(since))) { + throw Invalid('rates.$i.since', 'A date, or empty for always.'); + } + if (rates.containsKey(since)) throw Invalid('rates.$i.since', 'Two rates from the same day.'); + rates[since] = rate; + } + final notes = f.notes.length > 4000 ? f.notes.substring(0, 4000) : f.notes; + return ( + { + 'kind': kind, + 'parent_id': parent, + 'name': name, + 'colour': colour, + 'billable': f.billable, + 'currency': currency.isEmpty ? null : currency, + 'notes': notes, + 'archived': f.archived ? 1 : 0, + }, + rates, + ); +} + +/// Create (no id) or update a node and replace its rate history → its id. +String saveNode(SyncStore store, Tree t, NodeForm f) { + final (v, rates) = cleanNode(f, t); + final String id; + if (f.id == null) { + id = SyncStore.randomId(); + store.put(tNode, id, {...v, 'created': fmtSec(DateTime.now())}); + } else { + id = f.id!; + final old = store.row(tNode, id); + if (old == null) throw Invalid('name', 'It was deleted meanwhile.'); + store.put(tNode, id, {...old, ...v}); + } + // rates: ids are ':' (the Pi's key) — unchanged rows aren't touched + final have = {for (final r in t.rates[id] ?? const []) r.since: r.rate}; + for (final since in have.keys) { + if (!rates.containsKey(since)) store.delete(tRate, '$id:$since'); + } + for (final MapEntry(key: since, value: rate) in rates.entries) { + if (have[since] != rate) store.put(tRate, '$id:$since', {'node_id': id, 'since': since, 'rate': rate}); + } + return id; +} + +/// Delete a node and everything under it — only when no time is booked there (archive it +/// instead). → false when refused. +bool deleteNode(SyncStore store, Tree t, String nid) { + final ids = t.subtree(nid); + if (store.rows(tEntry).any((r) => ids.contains(r['node_id']))) return false; + final order = ids.toList()..sort((a, b) => t.chain(b).length.compareTo(t.chain(a).length)); // leaves first + for (final i in order) { + for (final r in t.rates[i] ?? const []) { + store.delete(tRate, '$i:${r.since}'); + } + store.delete(tNode, i); + } + return true; +} + +/// node id → minutes ever booked directly on it. +Map bookedMinutes(SyncStore store) { + final out = {}; + for (final r in store.rows(tEntry)) { + final e = WorkEntry(r); + out[e.node] = (out[e.node] ?? 0) + e.minutes; + } + return out; +} + +// ---- the week ---------------------------------------------------------------------------- + +class Block { + Block(this.e, this.a, this.b, this.contBefore, this.contAfter); + final WorkEntry e; + final double a, b; // minutes after the day's midnight + final bool contBefore, contAfter; + int lane = 0, lanes = 1; +} + +class DayCol { + DayCol(this.day, this.blocks, this.minutes, this.billableMinutes); + final DateTime day; + final List blocks; + final double minutes, billableMinutes; +} + +class CustomerWeek { + CustomerWeek(this.node, this.minutes, this.amounts, this.rate); + final Node node; + final double minutes; + final Map amounts; + final String rate; +} + +class WeekView { + WeekView(this.monday, this.days, this.minutes, this.billableMinutes, this.amounts, this.customers); + final DateTime monday; + final List days; + final double minutes, billableMinutes; + final Map amounts; + final List customers; +} + +/// Overlap layout: lane + lanes per cluster of overlapping blocks (views._lanes). +void lanes(List items) { + final cluster = []; + double? end; + void flush() { + final n = cluster.fold(0, (m, i) => i.lane > m ? i.lane : m) + 1; + for (final i in cluster) { + i.lanes = n; + } + } + + items.sort((x, y) => x.a != y.a ? x.a.compareTo(y.a) : y.b.compareTo(x.b)); + for (final it in items) { + if (cluster.isNotEmpty && it.a >= end!) { + flush(); + cluster.clear(); + end = null; + } + final used = { + for (final c in cluster) + if (c.b > it.a) c.lane, + }; + var l = 0; + while (used.contains(l)) { + l++; + } + it.lane = l; + cluster.add(it); + end = end == null ? it.b : (it.b > end ? it.b : end); + } + if (cluster.isNotEmpty) flush(); +} + +WeekView week(SyncStore store, Tree t, int offset, [DateTime? now]) { + final ws = weekStart(offset, now), we = DateTime.utc(ws.year, ws.month, ws.day + 7); + final entries = entriesBetween(store, ws, we); + final days = []; + var tot = 0.0, totB = 0.0; + for (var d = 0; d < 7; d++) { + final d0 = DateTime.utc(ws.year, ws.month, ws.day + d), d1 = DateTime.utc(ws.year, ws.month, ws.day + d + 1); + final blocks = []; + var m = 0.0, bm = 0.0; + for (final e in entries) { + final a = e.s.isAfter(d0) ? e.s : d0, b = e.e.isBefore(d1) ? e.e : d1; + if (!b.isAfter(a)) continue; + final am = a.difference(d0).inSeconds / 60, bmin = b.difference(d0).inSeconds / 60; + m += bmin - am; + if (e.billable) bm += bmin - am; + blocks.add(Block(e, am, bmin, e.s.isBefore(d0), e.e.isAfter(d1))); + } + lanes(blocks); + days.add(DayCol(d0, blocks, m, bm)); + tot += m; + totB += bm; + } + final amounts = {}; + final per = )>{}; + for (final e in entries) { + // money by the entry's own date + rate + final (minutes, amt, cur) = t.amount(e); + if (e.billable) amounts[cur] = (amounts[cur] ?? 0) + amt; + final top = t.clientOf(e.node); + if (top != null) { + final p = per[top.id] ?? (0.0, {}); + if (e.billable) p.$2[cur] = (p.$2[cur] ?? 0) + amt; + per[top.id] = (p.$1 + minutes, p.$2); + } + } + final todayIso = fmtDay(now ?? DateTime.now()); + final customers = [ + for (final (n, _) in t.walk()) + if (n.parent == null) + CustomerWeek(n, per[n.id]?.$1 ?? 0, per[n.id]?.$2 ?? {}, '${num0(t.rate(n.id, todayIso).$1)} ${t.currency(n.id)}/h'), + ]..sort((a, b) => b.minutes.compareTo(a.minutes)); + return WeekView(ws, days, tot, totB, amounts, customers); +} + +// ---- the report -------------------------------------------------------------------------- + +const presets = [ + ('week', 'This week'), + ('lastweek', 'Last week'), + ('month', 'This month'), + ('lastmonth', 'Last month'), + ('year', 'This year'), + ('lastyear', 'Last year'), +]; + +/// (from, to) inclusive days of a preset (views.preset_range), or null. +(DateTime, DateTime)? presetRange(String name, [DateTime? now]) { + final t = dayOf(now ?? DateTime.now()); + final mon = DateTime.utc(t.year, t.month, t.day - (t.weekday - 1)); + switch (name) { + case 'week': + return (mon, DateTime.utc(mon.year, mon.month, mon.day + 6)); + case 'lastweek': + return (DateTime.utc(mon.year, mon.month, mon.day - 7), DateTime.utc(mon.year, mon.month, mon.day - 1)); + case 'month': + return (DateTime.utc(t.year, t.month, 1), DateTime.utc(t.year, t.month + 1, 0)); + case 'lastmonth': + return (DateTime.utc(t.year, t.month - 1, 1), DateTime.utc(t.year, t.month, 0)); + case 'year': + return (DateTime.utc(t.year, 1, 1), DateTime.utc(t.year, 12, 31)); + case 'lastyear': + return (DateTime.utc(t.year - 1, 1, 1), DateTime.utc(t.year - 1, 12, 31)); + } + return null; +} + +class Agg { + double m = 0, bm = 0; + final amounts = {}; + void add(double minutes, bool billable, double amt, String cur) { + m += minutes; + if (billable) { + bm += minutes; + amounts[cur] = (amounts[cur] ?? 0) + amt; + } + } +} + +class ReportRow { + ReportRow(this.node, this.depth, this.agg); + final Node node; + final int depth; + final Agg agg; +} + +class ReportItem { + ReportItem(this.e, this.rate, this.amount, this.currency); + final WorkEntry e; + final double rate, amount; + final String currency; +} + +class Report { + Report(this.rows, this.items, this.total); + final List rows; + final List items; + final Agg total; +} + +/// Hours + money in [from, to] (inclusive days) as a tree; [client] limits it to one node's +/// subtree. Entries count on the day they start (views.report). +Report report(SyncStore store, Tree t, DateTime from, DateTime to, {String? client}) { + final keep = client != null && t.nodes.containsKey(client) ? t.subtree(client) : null; + final start = dayOf(from), end = DateTime.utc(to.year, to.month, to.day + 1); + final rows = entriesBetween( + store, + start.subtract(const Duration(days: 1)), + end, + keep: keep, + ).where((e) => !e.s.isBefore(start) && e.s.isBefore(end)).toList(); + final agg = {}, total = Agg(), items = []; + for (final e in rows) { + final (minutes, amt, cur) = t.amount(e); + for (final n in t.chain(e.node)) { + agg.putIfAbsent(n.id, Agg.new).add(minutes, e.billable, amt, cur); + } + total.add(minutes, e.billable, amt, cur); + items.add(ReportItem(e, e.billable ? t.rate(e.node, e.start.substring(0, 10)).$1 : 0, amt, cur)); + } + return Report( + [ + for (final (n, d) in t.walk(archived: true)) + if (agg[n.id] != null) ReportRow(n, d, agg[n.id]!), + ], + items, + total, + ); +} + +/// The report's entries as CSV (the Pi's /work/report.csv). +String reportCsv(Report r, Tree t) { + String q(String s) => RegExp(r'[",\n\r]').hasMatch(s) ? '"${s.replaceAll('"', '""')}"' : s; + final b = StringBuffer('date,start,end,hours,customer / project / task,billable,rate,amount,currency,note\r\n'); + for (final i in r.items) { + final e = i.e; + b.write( + [ + e.start.substring(0, 10), + e.start.substring(11), + e.end.substring(11), + (e.minutes / 60).toStringAsFixed(2), + q(t.path(e.node)), + e.billable ? 'yes' : 'no', + e.billable ? num0(i.rate) : '', + e.billable ? i.amount.toStringAsFixed(2) : '', + i.currency, + q(e.note), + ].join(','), + ); + b.write('\r\n'); + } + return b.toString(); +} + +// ---- what the Pi adds to the week (plugins/workload/phone.py) ----------------------------- +// "workload.cal" — the calendar's timed events (drawn faintly behind; tap = book them); +// "workload.act" — Activity's blocks for the lane beside the bookings (tap = book with the customer guessed). +const tCal = 'workload.cal', tAct = 'workload.act'; + +class Ghost { + Ghost(this.title, this.calendar, this.colour, this.a, this.b, this.s, this.e); + final String title, calendar, colour; + final double a, b; // minutes after the day's midnight + final DateTime s, e; // the part inside this day +} + +class ActBlock { + ActBlock(this.r) : a = (r['a'] as num).toDouble(), b = (r['b'] as num).toDouble(); + final Map r; + final double a, b; + String get day => r['day'] as String; + String get start => r['start'] as String; + String get end => r['end'] as String; + String get colour => r['colour'] as String? ?? '#8b929e'; + String get path => r['path'] as String? ?? ''; + String get name => r['name'] as String? ?? ''; + String get what => r['what'] as String? ?? ''; + String get dur => r['dur'] as String? ?? ''; + List get names => ((jsonDecodeSafe(r['names'] as String?) as List?) ?? const []).cast(); +} + +Object? jsonDecodeSafe(String? s) { + if (s == null || s.isEmpty) return null; + try { + return jsonDecode(s); + } catch (_) { + return null; + } +} + +/// The calendar events inside each day of the week from [monday] (all-day ones aren't sent). +List> ghosts(SyncStore store, DateTime monday) { + final end = DateTime.utc(monday.year, monday.month, monday.day + 7); + final rows = store.rows( + tCal, + where: "json_extract(data, '\$.start') < ? AND json_extract(data, '\$.end') > ?", + args: [fmtMin(end), fmtMin(monday)], + ); + return [ + for (var d = 0; d < 7; d++) + () { + final d0 = DateTime.utc(monday.year, monday.month, monday.day + d), + d1 = DateTime.utc(monday.year, monday.month, monday.day + d + 1); + final out = []; + for (final r in rows) { + final s = parseMin(r['start'] as String), e = parseMin(r['end'] as String); + final a = s.isAfter(d0) ? s : d0, b = e.isBefore(d1) ? e : d1; + if (!b.isAfter(a)) continue; + out.add( + Ghost( + r['title'] as String? ?? '', + r['calendar'] as String? ?? '', + r['colour'] as String? ?? '#8b929e', + a.difference(d0).inSeconds / 60, + b.difference(d0).inSeconds / 60, + a, + b, + ), + ); + } + out.sort((x, y) => x.a.compareTo(y.a)); + return out; + }(), + ]; +} + +/// Activity's blocks per day of the week from [monday]. +List> actBlocks(SyncStore store, DateTime monday) { + final days = [for (var d = 0; d < 7; d++) fmtDay(DateTime.utc(monday.year, monday.month, monday.day + d))]; + final rows = store.rows(tAct, where: "json_extract(data, '\$.day') BETWEEN ? AND ?", args: [days.first, days.last]); + return [for (final d in days) (rows.where((r) => r['day'] == d).map(ActBlock.new).toList()..sort((x, y) => x.a.compareTo(y.a)))]; +} + +/// The customer / project an Activity block is probably for: the first of its category names +/// (nearest first: "Rocket", "Acme", "Customer", "Work") that's a live node's name (views._guess). +String? guessNode(Tree t, List names) { + final byName = {}; + for (final (n, _) in t.walk()) { + byName.putIfAbsent(n.name.trim().toLowerCase(), () => n.id); + } + for (final x in names) { + final id = byName[x.trim().toLowerCase()]; + if (id != null) return id; + } + return null; +} diff --git a/app/lib/work/work_page.dart b/app/lib/work/work_page.dart new file mode 100644 index 0000000..a5a2235 --- /dev/null +++ b/app/lib/work/work_page.dart @@ -0,0 +1,1054 @@ +// Work: one week of booked time (the web page's /work). ‹ CW nn › on top (tap = this week), the +// totals (hours, billable / not, money, the weekly target), the customers' hours this week, then +// the days: on a phone a strip of the 7 days + the chosen day as a timeline; on a wide screen all +// seven side by side. Tap an empty spot = book from there (15-minute snap); hold an empty spot and drag +// up / down = book that span; tap a block = edit, +// hold a block and drag = move it (15-minute snap; sideways = another day: a column on a wide +// screen, a cell of the day strip on a phone); hold its top / bottom grip and drag = an earlier / later +// start / end. Holds start after holdDelay (shorter than Flutter's long press). Dragging near the top / bottom +// edge scrolls the day (the span / block follows), so spans longer than the screen can be drawn. The + books from now. From the Pi (when sent, switchable): +// the calendar's events faintly behind (tap = book that time), Activity's blocks in a lane (tap = book it). +import 'dart:async'; +import 'dart:math'; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../app/sync_service.dart'; +import '../app/theme.dart'; +import 'customers_page.dart'; +import 'entry_sheet.dart'; +import 'work_model.dart'; + +const hourH = 52.0; // px per hour in the timeline +const holdDelay = Duration(milliseconds: 250); // hold before a move / resize / new span starts (Flutter's long press: 500 ms) + +/// [child] with a tap and a hold-and-drag that starts after [holdDelay]. +Widget _hold({ + required Widget child, + GestureTapUpCallback? onTapUp, + GestureLongPressStartCallback? onStart, + GestureLongPressMoveUpdateCallback? onMove, + GestureLongPressEndCallback? onEnd, + VoidCallback? onCancel, + HitTestBehavior? behavior, +}) => RawGestureDetector( + behavior: behavior, + gestures: { + if (onTapUp != null) + TapGestureRecognizer: GestureRecognizerFactoryWithHandlers( + TapGestureRecognizer.new, + (g) => g.onTapUp = onTapUp, + ), + LongPressGestureRecognizer: GestureRecognizerFactoryWithHandlers( + () => LongPressGestureRecognizer(duration: holdDelay), + (g) => g + ..onLongPressStart = onStart + ..onLongPressMoveUpdate = onMove + ..onLongPressEnd = onEnd + ..onLongPressCancel = onCancel, + ), + }, + child: child, +); + +class WorkPage extends StatefulWidget { + const WorkPage({super.key, required this.sync, this.s = const WorkSettings(), this.actions = const []}); + final SyncService sync; + final WorkSettings s; + final List actions; // the shell's (sync icon, ⋮) — Work has its own bar: in landscape the week's ‹ CW › sits in it + @override + State createState() => _WorkPageState(); +} + +class _WorkPageState extends State { + int offset = 0; + int sel = DateTime.now().weekday - 1; // the day shown on a phone + final scroll = ScrollController(initialScrollOffset: 0); + Timer? tick; + + // the calendar's events behind the week / Activity's lane (the web's "Activity" box), kept per device + bool get showCal => widget.sync.store.metaText('work_cal') != '0'; + bool get showAct => widget.sync.store.metaText('work_act') == '1'; + bool get showSum => widget.sync.store.metaText('work_sum') != '0'; // landscape: the totals line + void _toggle(String k, bool on) => setState(() => widget.sync.store.setMetaText(k, on ? '1' : '0')); + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => _toFocus()); + tick = Timer.periodic(const Duration(minutes: 1), (_) => mounted ? setState(() {}) : null); // the now line + } + + @override + void dispose() { + tick?.cancel(); + scroll.dispose(); + super.dispose(); + } + + /// Scroll to the focus hours (or just above now, when that's later). + void _toFocus() { + if (!scroll.hasClients) return; + final now = DateTime.now(); + final h = offset == 0 && now.hour > widget.s.dayEnd - 2 ? now.hour - 3.0 : widget.s.dayStart.toDouble(); + scroll.jumpTo(min(scroll.position.maxScrollExtent, max(0, h * hourH - 8))); + } + + void _go(int o) => setState(() { + offset = o; + if (o == 0) sel = DateTime.now().weekday - 1; + }); + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: widget.sync, + builder: (context, _) { + final store = widget.sync.store; + final t = Tree(store, widget.s); + final v = week(store, t, offset); + final mq = MediaQuery.of(context); + // landscape / wide: all 7 days; the week's nav goes into the bar and the totals into one thin line, + // so the height is for the calendar + final wide = mq.size.width >= 700 || mq.orientation == Orientation.landscape; + return Scaffold( + appBar: AppBar( + title: const Text('Work'), + // landscape: ‹ CW / dates › centred on the whole bar, its arrows fixed (a fixed-width middle) + flexibleSpace: wide ? SafeArea(child: Center(child: _head(v, compact: true))) : null, + actions: [..._switches(), ...widget.actions], + ), + body: LayoutBuilder( + builder: (context, box) { + final idx = wide ? [0, 1, 2, 3, 4, 5, 6] : [sel]; + // sideways drag per day: a column (wide) or a cell of the day strip (phone) + final dayW = wide ? (box.maxWidth - 24 - _Timeline.gutter) / 7 : (box.maxWidth - 20) / 7; + return Stack( + children: [ + Column( + children: [ + if (!wide) _head(v), + if (t.isEmpty) + _empty() + else ...[ + if (wide) ...[if (showSum) _line(v)] else ...[_totals(v), if (v.customers.isNotEmpty) _customers(v), _strip(v)], + if (wide) _dayHeads(v), + Expanded(child: _timeline(t, v, idx, dayW)), + ], + ], + ), + if (!t.isEmpty) + Positioned( + right: 16, + bottom: 16, + child: FloatingActionButton( + // the chosen day (phone) / today or the week's Monday (wide), from now rounded to 15 min + onPressed: () => + openEntry(context, widget.sync, s: widget.s, day: !wide ? v.days[sel].day : (offset == 0 ? null : v.days[0].day)), + child: const Icon(Icons.add), + ), + ), + ], + ); + }, + ), + ); + }, + ); + + /// Landscape: the totals, the switches and the customers in one line, the target as a hairline under it. + Widget _line(WeekView v) { + final target = widget.s.weekTarget; + final p = target > 0 ? min(1.0, v.minutes / 60 / target) : null; + final amounts = (v.amounts.entries.toList()..sort((a, b) => a.key.compareTo(b.key))) + .where((e) => e.value != 0) + .map((e) => money(e.value, e.key)) + .join(' · '); + return Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 0), + child: Column( + children: [ + SizedBox( + height: 40, + child: Row( + children: [ + Text(hm(v.minutes), style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold)), + const SizedBox(width: 8), + Text('${hm(v.billableMinutes)} billable', style: const TextStyle(color: good, fontSize: 13)), + if (v.minutes - v.billableMinutes > 0) + Text(' + ${hm(v.minutes - v.billableMinutes)} not', style: const TextStyle(color: muted, fontSize: 13)), + if (amounts.isNotEmpty) ...[ + const SizedBox(width: 12), + Text(amounts, style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 13)), + ], + const SizedBox(width: 8), + Expanded( + child: ListView( + scrollDirection: Axis.horizontal, + reverse: true, // right-aligned, scrolls when there are many + children: [ + for (final c in v.customers.reversed) + Padding( + padding: const EdgeInsets.only(left: 6), + child: Center( + child: ActionChip( + visualDensity: VisualDensity.compact, + avatar: Icon(Icons.circle, size: 10, color: hexColor(c.node.colour ?? palette[0])), + label: Text( + [c.node.name, if (c.minutes > 0) hm(c.minutes)].join(' '), + style: const TextStyle(fontSize: 12.5), + ), + onPressed: () => Navigator.push( + context, + MaterialPageRoute( + builder: (_) => NodeEditor(sync: widget.sync, s: widget.s, nodeId: c.node.id), + ), + ), + ), + ), + ), + ], + ), + ), + ], + ), + ), + if (p != null) + Tooltip( + message: '${hm(v.minutes)} of ${num0(target)} h this week', + child: LinearProgressIndicator(value: p, minHeight: 2, backgroundColor: card2, color: p >= 1 ? good : accent), + ), + ], + ), + ); + } + + Widget _head(WeekView v, {bool compact = false}) { + final sun = v.monday.add(const Duration(days: 6)); + final cw = isoWeek(v.monday); + const mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; + final range = v.monday.month == sun.month + ? '${v.monday.day}. – ${sun.day}. ${mon[sun.month - 1]} ${sun.year}' + : '${v.monday.day}. ${mon[v.monday.month - 1]} – ${sun.day}. ${mon[sun.month - 1]} ${sun.year}'; + if (compact) { + // in the bar: ‹ CW 42 / 19. – 25. Oct 2026 › — a fixed-width middle, so the arrows never move + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton(visualDensity: VisualDensity.compact, onPressed: () => _go(offset - 1), icon: const Icon(Icons.chevron_left)), + SizedBox( + width: 170, + child: GestureDetector( + onTap: () => _go(0), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + 'CW $cw', + style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold, color: accent, height: 1.15), + ), + Text(range, style: const TextStyle(fontSize: 11.5, color: muted, height: 1.15)), + ], + ), + ), + ), + IconButton(visualDensity: VisualDensity.compact, onPressed: () => _go(offset + 1), icon: const Icon(Icons.chevron_right)), + ], + ); + } + return Padding( + padding: const EdgeInsets.fromLTRB(4, 4, 4, 0), + child: Row( + children: [ + IconButton(onPressed: () => _go(offset - 1), icon: const Icon(Icons.chevron_left)), + Expanded( + child: GestureDetector( + onTap: () => _go(0), + child: Column( + children: [ + Text( + 'CW $cw', + style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold, color: accent), + ), + Text(range, style: const TextStyle(color: muted, fontSize: 12.5)), + ], + ), + ), + ), + IconButton(onPressed: () => _go(offset + 1), icon: const Icon(Icons.chevron_right)), + ], + ), + ); + } + + Widget _empty() => Expanded( + child: Center( + child: Padding( + padding: const EdgeInsets.all(24), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + const Text( + 'No customers yet. Add the first one — then book time on it here.', + textAlign: TextAlign.center, + style: TextStyle(color: muted), + ), + const SizedBox(height: 12), + FilledButton.icon( + onPressed: () => Navigator.push( + context, + MaterialPageRoute( + builder: (_) => CustomersPage(sync: widget.sync, s: widget.s), + ), + ), + icon: const Icon(Icons.add), + label: const Text('Customer'), + ), + ], + ), + ), + ), + ); + + Widget _totals(WeekView v) { + final target = widget.s.weekTarget; + final p = target > 0 ? min(1.0, v.minutes / 60 / target) : null; + final amounts = (v.amounts.entries.toList()..sort((a, b) => a.key.compareTo(b.key))) + .where((e) => e.value != 0) + .map((e) => money(e.value, e.key)) + .join(' · '); + return Padding( + padding: const EdgeInsets.fromLTRB(12, 6, 12, 0), + child: Card( + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 10, 14, 10), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Text(hm(v.minutes), style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold)), + const SizedBox(width: 10), + Expanded( + child: Text.rich( + TextSpan( + children: [ + TextSpan( + text: '${hm(v.billableMinutes)} billable', + style: const TextStyle(color: good), + ), + if (v.minutes - v.billableMinutes > 0) + TextSpan( + text: ' + ${hm(v.minutes - v.billableMinutes)} not', + style: const TextStyle(color: muted), + ), + ], + ), + ), + ), + if (amounts.isNotEmpty) Text(amounts, style: const TextStyle(fontWeight: FontWeight.w600)), + ], + ), + if (p != null) ...[ + const SizedBox(height: 8), + Tooltip( + message: '${hm(v.minutes)} of ${num0(target)} h this week', + child: ClipRRect( + borderRadius: BorderRadius.circular(4), + child: LinearProgressIndicator(value: p, minHeight: 6, backgroundColor: card2, color: p >= 1 ? good : accent), + ), + ), + ], + ], + ), + ), + ), + ); + } + + /// Calendar / Activity switches as icons in the bar (amber = shown) — only once the Pi has sent any. + List _switches() { + final store = widget.sync.store; + bool has(String t) => store.db.select('SELECT 1 FROM rec WHERE t = ? LIMIT 1', [t]).isNotEmpty; + Widget icon(String tip, IconData i, bool on, String k) => IconButton( + tooltip: '$tip: ${on ? 'shown' : 'hidden'}', + visualDensity: VisualDensity.compact, + onPressed: () => _toggle(k, !on), + icon: Icon(i, size: 21, color: on ? accent : muted), + ); + return [ + if (has(tCal)) icon('Calendar events', Icons.event_note, showCal, 'work_cal'), + if (has(tAct)) icon('Activity', Icons.insights, showAct, 'work_act'), + ]; + } + + Widget _customers(WeekView v) => SizedBox( + height: 44, + child: ListView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.fromLTRB(12, 6, 12, 0), + children: [ + for (final c in v.customers) + Padding( + padding: const EdgeInsets.only(right: 6), + child: Tooltip( + message: [c.rate, if (c.node.notes.trim().isNotEmpty) c.node.notes.trim().split('\n').first].join(' · '), + child: ActionChip( + avatar: Icon(Icons.circle, size: 11, color: hexColor(c.node.colour ?? palette[0])), + label: Text( + [ + c.node.name, + if (c.minutes > 0) hm(c.minutes), + ...c.amounts.entries.where((e) => e.value != 0).map((e) => money(e.value, e.key)), + ].join(' '), + ), + onPressed: () => Navigator.push( + context, + MaterialPageRoute( + builder: (_) => NodeEditor(sync: widget.sync, s: widget.s, nodeId: c.node.id), + ), + ), + ), + ), + ), + ], + ), + ); + + Widget _strip(WeekView v) { + final most = v.days.fold(0.0, (m, d) => max(m, d.minutes)); + final today = dayOf(DateTime.now()); + return Padding( + padding: const EdgeInsets.fromLTRB(10, 8, 10, 4), + child: Row( + children: [ + for (var i = 0; i < 7; i++) + () { + final d = v.days[i]; + final isToday = d.day.isAtSameMomentAs(today); + return Expanded( + child: GestureDetector( + onTap: () => setState(() => sel = i), + child: Container( + margin: const EdgeInsets.symmetric(horizontal: 2), + padding: const EdgeInsets.symmetric(vertical: 5), + decoration: BoxDecoration(color: i == sel ? card2 : null, borderRadius: BorderRadius.circular(8)), + child: Column( + children: [ + Text( + '${const ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'][i]} ${d.day.day}', + style: TextStyle(fontSize: 11.5, color: isToday ? accent : muted, fontWeight: isToday ? FontWeight.bold : null), + ), + const SizedBox(height: 4), + SizedBox( + height: 26, + child: Align( + alignment: Alignment.bottomCenter, + child: FractionallySizedBox( + heightFactor: most > 0 ? max(0.04, d.minutes / most) : 0.04, + widthFactor: .5, + child: Column( + children: [ + if (d.minutes > d.billableMinutes) + Expanded( + flex: (d.minutes - d.billableMinutes).round(), + child: Container(color: muted.withValues(alpha: .6)), + ), + Expanded( + flex: max(1, d.billableMinutes.round()), + child: Container(color: d.minutes > 0 && d.billableMinutes > 0 ? good : card2), + ), + ], + ), + ), + ), + ), + const SizedBox(height: 3), + Text(d.minutes > 0 ? hm(d.minutes) : '', style: const TextStyle(fontSize: 11)), + ], + ), + ), + ), + ); + }(), + ], + ), + ); + } + + /// Landscape: one line per day ("Mon 19 9:00"); the corner above the hours shows / hides the totals line. + Widget _dayHeads(WeekView v) { + final today = dayOf(DateTime.now()); + return Padding( + padding: const EdgeInsets.fromLTRB(12, 0, 12, 2), + child: Row( + children: [ + SizedBox( + width: _Timeline.gutter, + height: 24, + child: IconButton( + padding: EdgeInsets.zero, + iconSize: 18, + tooltip: showSum ? 'Hide the totals' : 'Show the totals', + onPressed: () => _toggle('work_sum', !showSum), + icon: Icon(showSum ? Icons.expand_less : Icons.expand_more, color: muted), + ), + ), + for (final d in v.days) + Expanded( + child: Text.rich( + TextSpan( + children: [ + TextSpan( + text: '${const ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][d.day.weekday - 1]} ${d.day.day}', + style: TextStyle(fontWeight: FontWeight.bold, color: d.day.isAtSameMomentAs(today) ? accent : null), + ), + if (d.minutes > 0) + TextSpan( + text: ' ${hm(d.minutes)}', + style: const TextStyle(fontSize: 11.5, color: muted), + ), + ], + ), + textAlign: TextAlign.center, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + ); + } + + Widget _timeline(Tree t, WeekView v, List idx, double dayW) { + final store = widget.sync.store; + final gh = showCal ? ghosts(store, v.monday) : null; + var ab = showAct ? actBlocks(store, v.monday) : null; + if (ab != null && ab.every((d) => d.isEmpty)) ab = null; // no lane in a week Activity has nothing for + return SingleChildScrollView( + controller: scroll, + padding: const EdgeInsets.fromLTRB(12, 4, 12, 80), + child: _Timeline( + tree: t, + days: [for (final i in idx) v.days[i]], + ghosts: [for (final i in idx) gh?[i] ?? const []], + acts: ab == null ? null : [for (final i in idx) ab[i]], + dayW: dayW, + focus: (widget.s.dayStart, widget.s.dayEnd), + onEmpty: (day, minute, [end]) => openEntry(context, widget.sync, s: widget.s, day: day, startMin: minute, endMin: end), + onBlock: (e) => openEntry(context, widget.sync, s: widget.s, entry: e), + onGhost: (g) => + openEntry(context, widget.sync, s: widget.s, day: dayOf(g.s), startMin: g.a.round(), endMin: g.b.round(), note: g.title), + onAct: (a, day) => openEntry( + context, + widget.sync, + s: widget.s, + day: day, + startMin: (a.a / 5).round() * 5, + endMin: (a.b / 5).round() * 5, + note: a.what, + node: guessNode(t, a.names), + ), + onMove: (e, minutes, days) => _move(t, e, minutes, days, v), + onResize: _resize, + ), + ); + } + + /// A block's grip dragged: its start ([top]) or end [minutes] earlier / later (snapped to 15, at least 15 minutes long). + void _resize(WorkEntry e, bool top, int minutes) { + if (minutes == 0) return; + final old = widget.sync.store.row(tEntry, e.id); + if (old == null) return; + DateTime sh(DateTime x) => DateTime.utc(x.year, x.month, x.day, x.hour, x.minute + minutes); + final s = top ? sh(e.s) : e.s, end = top ? e.e : sh(e.e); + widget.sync.store.put(tEntry, e.id, {...old, 'start': fmtMin(s), 'end': fmtMin(end), 'updated': fmtSec(DateTime.now())}); + widget.sync.changed(); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('${two(s.hour)}:${two(s.minute)}–${two(end.hour)}:${two(end.minute)} · ${hm(end.difference(s).inMinutes)}'), + persist: false, // with an action Flutter keeps it up until tapped + action: SnackBarAction( + label: 'Undo', + onPressed: () { + widget.sync.store.put(tEntry, e.id, old); + widget.sync.changed(); + }, + ), + ), + ); + } + + /// A dragged block: the same length, [days] later / earlier and shifted by [minutes] (snapped to 15). + void _move(Tree t, WorkEntry e, int minutes, int days, WeekView v) { + if (minutes == 0 && days == 0) return; + DateTime sh(DateTime x) => DateTime.utc(x.year, x.month, x.day + days, x.hour, x.minute + minutes); + final s = sh(e.s), end = sh(e.e); + final old = widget.sync.store.row(tEntry, e.id); + if (old == null) return; + widget.sync.store.put(tEntry, e.id, {...old, 'start': fmtMin(s), 'end': fmtMin(end), 'updated': fmtSec(DateTime.now())}); + widget.sync.changed(); + if (days != 0) { + // follow it: its day (and week) on a phone + final w = dayOf(s).difference(v.monday).inDays; + setState(() { + offset += (w / 7).floor(); + sel = w % 7; + }); + } + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + 'Moved to ${days != 0 ? '${dayLabel(dayOf(s))} ' : ''}${two(s.hour)}:${two(s.minute)}–${two(end.hour)}:${two(end.minute)}', + ), + persist: false, // with an action Flutter keeps it up until tapped + action: SnackBarAction( + label: 'Undo', + onPressed: () { + widget.sync.store.put(tEntry, e.id, old); + widget.sync.changed(); + }, + ), + ), + ); + } +} + +/// The hours + the days' blocks, side by side (one day on a phone, seven on a wide screen): the +/// calendar's events faintly behind, Activity's blocks in a lane on the right (when shown). +class _Timeline extends StatefulWidget { + const _Timeline({ + required this.tree, + required this.days, + required this.ghosts, + required this.acts, + required this.dayW, + required this.focus, + required this.onEmpty, + required this.onBlock, + required this.onGhost, + required this.onAct, + required this.onMove, + required this.onResize, + }); + static const gutter = 34.0; + static const lane = .72; // the bookings' share of a day while Activity's lane is shown (the web's --bw) + final Tree tree; + final List days; + final List> ghosts; + final List>? acts; + final double dayW; // px of sideways drag = one day (a strip cell on a phone, a column on a wide screen) + final (int, int) focus; + final void Function(DateTime day, int minute, [int? end]) onEmpty; // end: a held-and-dragged span + final void Function(WorkEntry e) onBlock; + final void Function(Ghost g) onGhost; + final void Function(ActBlock a, DateTime day) onAct; + final void Function(WorkEntry e, int minutes, int days) onMove; + final void Function(WorkEntry e, bool top, int minutes) onResize; + @override + State<_Timeline> createState() => _TimelineState(); +} + +class _TimelineState extends State<_Timeline> { + String? dragging, resizing; // the block being moved / resized ("id@start"); drag = the finger's offset since the hold + bool sizeTop = false; // resizing its start (else its end) + Offset drag = Offset.zero; + int? spanDay; // a new booking being drawn (held on an empty spot, dragged): its day column, the held slot, the finger + int spanFrom = 0, spanTo = 0; + + static int _snap(double minutes) => (minutes / 15).round() * 15; + static int _at(double dy) => min(24 * 60 - 15, max(0, _snap(dy / hourH * 60 - 7.5))); // the slot under a finger + // the span drawn: the held slot always in it, out to the finger either way + (int, int) get _span => spanTo >= spanFrom ? (spanFrom, max(spanTo, spanFrom + 15)) : (spanTo, spanFrom + 15); + int get _days => widget.dayW > 0 ? (drag.dx / widget.dayW).round() : 0; + + // scrolling while a drag is near the timeline's top / bottom edge — the span / block / grip follows the finger + Timer? _edge; + double _speed = 0, _scroll0 = 0, _spanY = 0, _spanScroll = 0; // px per tick; where a move / span started + Offset _finger = Offset.zero; // a move's / resize's finger offset since the hold + ScrollPosition? get _pos => Scrollable.maybeOf(context)?.position; + double get _px => _pos?.pixels ?? 0; + + void _follow() => setState(() { + if (spanDay != null) spanTo = min(24 * 60, max(0, _snap((_spanY + _px - _spanScroll) / hourH * 60))); + if (dragging != null || resizing != null) drag = _finger + Offset(0, _px - _scroll0); + }); + + /// The finger at [global]: within [zone] of the visible top / bottom = scroll that way, faster nearer the edge. + void _edgeAt(Offset global) { + const zone = 64.0; + final box = Scrollable.maybeOf(context)?.context.findRenderObject(); + if (box is! RenderBox) return; + final top = box.localToGlobal(Offset.zero).dy, bottom = top + box.size.height; + final v = global.dy < top + zone ? global.dy - top - zone : global.dy > bottom - zone ? global.dy - bottom + zone : 0.0; + _speed = (v / zone * 14).clamp(-22.0, 22.0); + if (_speed == 0) return _stopEdge(); + _edge ??= Timer.periodic(const Duration(milliseconds: 16), (_) { + final p = _pos; + if (p == null || !mounted) return _stopEdge(); + final next = (p.pixels + _speed).clamp(p.minScrollExtent, p.maxScrollExtent); + if (next != p.pixels) { + p.jumpTo(next); + _follow(); + } + }); + } + + void _stopEdge() { + _edge?.cancel(); + _edge = null; + _speed = 0; + } + + @override + void dispose() { + _stopEdge(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + const h = 24 * hourH; + final now = DateTime.now(), today = dayOf(now); + return SizedBox( + height: h, + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SizedBox( + width: _Timeline.gutter, + height: h, + child: Stack( + children: [ + for (var i = 1; i < 24; i++) + Positioned( + top: i * hourH - 7, + left: 0, + child: Text(two(i), style: const TextStyle(fontSize: 11, color: muted)), + ), + ], + ), + ), + for (var di = 0; di < widget.days.length; di++) + Expanded( + child: LayoutBuilder( + builder: (context, box) { + final d = widget.days[di]; + final w = box.maxWidth, bw = widget.acts == null ? w : w * _Timeline.lane; + final isToday = d.day.isAtSameMomentAs(today); + return _hold( + behavior: HitTestBehavior.opaque, + onTapUp: (u) => widget.onEmpty(d.day, _at(u.localPosition.dy)), + onStart: (u) { + HapticFeedback.mediumImpact(); + setState(() { + spanDay = di; + spanFrom = spanTo = _at(u.localPosition.dy); + _spanY = u.localPosition.dy; + _spanScroll = _px; + }); + }, + onMove: (u) { + _spanY = u.localPosition.dy; + _spanScroll = _px; + _follow(); + _edgeAt(u.globalPosition); + }, + onEnd: (_) { + _stopEdge(); + final (a, b) = _span; + setState(() => spanDay = null); + widget.onEmpty(d.day, a, b); + }, + onCancel: () { + _stopEdge(); + setState(() => spanDay = null); + }, + child: Stack( + clipBehavior: Clip.none, + children: [ + // the focus hours a shade lighter, hour lines + Positioned( + top: widget.focus.$1 * hourH, + height: (widget.focus.$2 - widget.focus.$1) * hourH, + left: 0, + right: 0, + child: Container(color: card.withValues(alpha: .55)), + ), + for (var i = 0; i <= 24; i++) + Positioned( + top: i * hourH, + left: 0, + right: 0, + child: Container(height: 1, color: card2.withValues(alpha: .7)), + ), + Positioned(top: 0, bottom: 0, left: 0, child: Container(width: 1, color: card2.withValues(alpha: .7))), + for (final g in widget.ghosts[di]) _ghost(g, bw), + if (widget.acts != null) ...[ + Positioned( + top: 0, + bottom: 0, + left: bw + 1, + child: Container(width: 1, color: card2), + ), + for (final a in widget.acts![di]) _act(a, d.day, bw + 3, w - bw - 4), + ], + for (final b in d.blocks) _block(b, bw), + if (spanDay == di) _newSpan(bw), + if (isToday) + Positioned( + top: (now.hour * 60 + now.minute) / 60 * hourH - 1, + left: 0, + right: 0, + child: IgnorePointer(child: Container(height: 2, color: accent)), + ), + ], + ), + ); + }, + ), + ), + ], + ), + ); + } + + /// The booking being drawn: from the held slot to the finger, its times on it. + Widget _newSpan(double w) { + final (a, b) = _span; + return Positioned( + top: a / 60 * hourH + 1, + left: 2, + width: w - 4, + height: max(14.0, (b - a) / 60 * hourH - 2), + child: IgnorePointer( + child: Container( + padding: const EdgeInsets.fromLTRB(5, 2, 4, 2), + decoration: BoxDecoration( + color: accent.withValues(alpha: .25), + borderRadius: BorderRadius.circular(6), + border: Border.all(color: accent, width: 1.5), + boxShadow: const [BoxShadow(blurRadius: 8, color: Colors.black54)], + ), + child: Text( + '${hhmm(a)}–${b == 24 * 60 ? '24:00' : hhmm(b)} · ${hm(b - a)}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 12, color: Colors.white, fontWeight: FontWeight.w600), + ), + ), + ), + ); + } + + /// A calendar event: a faint band with its title; tap = book its time. + Widget _ghost(Ghost g, double w) { + final c = hexColor(g.colour); + final height = max(12.0, (g.b - g.a) / 60 * hourH - 1); + return Positioned( + top: g.a / 60 * hourH + 1, + left: 1, + width: w - 2, + height: height, + child: GestureDetector( + onTap: () => widget.onGhost(g), + child: Tooltip( + message: + '${g.title}\n${g.calendar} · ${hhmm(g.s.hour * 60 + g.s.minute)}–${g.b >= 1440 ? '24:00' : hhmm(g.e.hour * 60 + g.e.minute)}', + child: Container( + padding: const EdgeInsets.only(left: 5, top: 1, right: 2), + decoration: BoxDecoration( + color: c.withValues(alpha: .13), + border: Border(left: BorderSide(color: c.withValues(alpha: .7), width: 3)), + ), + child: Text( + g.title, + maxLines: height > 30 ? 2 : 1, + overflow: TextOverflow.ellipsis, + style: TextStyle(fontSize: 11, color: c.withValues(alpha: .9), height: 1.1), + ), + ), + ), + ), + ); + } + + /// One of Activity's blocks in its lane; tap = book it (the customer guessed from its category). + Widget _act(ActBlock a, DateTime day, double x, double w) { + final c = hexColor(a.colour); + final height = max(6.0, (a.b - a.a) / 60 * hourH - 1); + return Positioned( + top: a.a / 60 * hourH + 1, + left: x, + width: w, + height: height, + child: GestureDetector( + onTap: () => widget.onAct(a, day), + child: Tooltip( + message: '${a.start}–${a.end} · ${a.dur}\n${a.path}${a.what.isNotEmpty ? '\n${a.what}' : ''}', + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 1), + decoration: BoxDecoration(color: c.withValues(alpha: .55), borderRadius: BorderRadius.circular(3)), + child: height > 16 && w > 30 + ? Text( + a.name, + maxLines: max(1, (height / 13).floor()), + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontSize: 10, color: Colors.white, height: 1.15), + ) + : null, + ), + ), + ), + ); + } + + Widget _block(Block b, double w) { + final t = widget.tree, e = b.e; + final n = t.nodes[e.node], top = t.clientOf(e.node); + final c = hexColor(t.colour(e.node)); + final lw = (w - 4) / b.lanes; + final key = '${e.id}@${b.a}'; + final moving = dragging == key, sizing = resizing == key; + final shift = moving ? _snap(drag.dy / hourH * 60) : 0, days = moving ? _days : 0; + final grow = sizing ? _grow(e) : 0; // minutes the grabbed edge moved + final a = b.a + (sizing && sizeTop ? grow : 0), z = b.b + (sizing && !sizeTop ? grow : 0); + final y = a / 60 * hourH + (moving ? drag.dy : 0); + final height = max(14.0, (z - a) / 60 * hourH - 2); + final short = height < 34; + final sm = e.s.hour * 60 + e.s.minute + shift + (sizing && sizeTop ? grow : 0), + em = e.e.difference(dayOf(e.s)).inMinutes + shift + (sizing && !sizeTop ? grow : 0); + // a block ending at midnight: 24:00; dragged sideways: the day it lands on + final time = + '${days != 0 ? '→ ${dayLabel(DateTime.utc(e.s.year, e.s.month, e.s.day + days)).split(' ').take(2).join(' ')} ' : ''}' + '${hhmm(sm)}–${em == 24 * 60 ? '24:00' : hhmm(em)}'; + // on a wide screen the block follows the finger into the other day's column; on a phone the label says where + final dx = moving && widget.days.length > 1 ? days * widget.dayW : 0.0; + return Positioned( + top: y + 1, + left: 2 + b.lane * lw + dx, + width: lw - 2, + height: height, + child: Stack( + fit: StackFit.expand, + children: [ + _hold( + onTapUp: (_) => widget.onBlock(e), + onStart: (_) { + HapticFeedback.mediumImpact(); + setState(() { + dragging = key; + drag = _finger = Offset.zero; + _scroll0 = _px; + }); + }, + onMove: (u) { + _finger = u.offsetFromOrigin; + _follow(); + _edgeAt(u.globalPosition); + }, + onEnd: (_) { + _stopEdge(); + final m = _snap(drag.dy / hourH * 60), dd = _days; + setState(() => dragging = null); + widget.onMove(e, m, dd); + }, + onCancel: () { + _stopEdge(); + setState(() => dragging = null); + }, + child: Container( + padding: const EdgeInsets.fromLTRB(5, 2, 4, 2), + decoration: BoxDecoration( + color: Color.alphaBlend(c.withValues(alpha: e.billable ? .9 : .3), bg), // opaque: the calendar's titles don't show through + borderRadius: BorderRadius.vertical( + top: Radius.circular(b.contBefore ? 0 : 6), + bottom: Radius.circular(b.contAfter ? 0 : 6), + ), + border: e.billable ? null : Border.all(color: c, width: 1.2), + boxShadow: moving || sizing ? const [BoxShadow(blurRadius: 8, color: Colors.black54)] : null, + ), + child: DefaultTextStyle.merge( + style: TextStyle(fontSize: 12, color: e.billable ? const Color(0xFF0D1017) : Colors.white, height: 1.15), + overflow: TextOverflow.ellipsis, + child: short + ? Text('${n?.name ?? '?'} · $time', maxLines: 1, style: const TextStyle(fontWeight: FontWeight.w600)) + : Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(n?.name ?? '?', maxLines: 1, style: const TextStyle(fontWeight: FontWeight.bold)), + if (top != null && n != null && top.id != n.id && height > 48) Text(top.name, maxLines: 1), + Text('$time · ${hm(em - sm)}', maxLines: 1), + if (e.note.isNotEmpty && height > 64) Text(e.note.split('\n').first, maxLines: 2), + ], + ), + ), + ), + ), + // grips: the start's on top (not on a piece continued from the day before), the end's at the bottom + // the grabbed one stays while held, however short the block gets (gone, it would cancel the drag) + if (!b.contBefore && (sizing ? sizeTop : height >= 40)) _grip(e, key, true, e.billable), + if (!b.contAfter && (sizing ? !sizeTop : height >= 22)) _grip(e, key, false, e.billable), + ], + ), + ); + } + + /// Minutes the grabbed edge of [e] moved: snapped to 15, the entry staying at least 15 minutes long. + int _grow(WorkEntry e) { + final g = _snap(drag.dy / hourH * 60), len = e.e.difference(e.s).inMinutes; + return sizeTop ? min(g, len - 15) : max(g, 15 - len); + } + + /// A block's top / bottom edge: hold and drag = an earlier / later start ([top]) or end; a tap edits like the block. + Widget _grip(WorkEntry e, String key, bool top, bool dark) => Positioned( + key: ValueKey(top), // the top and bottom grips keep their own state when the other one comes or goes + top: top ? 0 : null, + bottom: top ? null : 0, + left: 0, + right: 0, + height: 14, + child: _hold( + behavior: HitTestBehavior.opaque, + onTapUp: (_) => widget.onBlock(e), + onStart: (_) { + HapticFeedback.selectionClick(); + setState(() { + resizing = key; + sizeTop = top; + drag = _finger = Offset.zero; + _scroll0 = _px; + }); + }, + onMove: (u) { + _finger = u.offsetFromOrigin; + _follow(); + _edgeAt(u.globalPosition); + }, + onEnd: (_) { + _stopEdge(); + final m = _grow(e); + setState(() => resizing = null); + widget.onResize(e, top, m); + }, + onCancel: () { + _stopEdge(); + setState(() => resizing = null); + }, + child: Align( + alignment: top ? Alignment.topCenter : Alignment.bottomCenter, + child: Container( + margin: const EdgeInsets.symmetric(vertical: 3), + width: 22, + height: 3, + decoration: BoxDecoration( + color: (dark ? const Color(0xFF0D1017) : Colors.white).withValues(alpha: resizing == key ? .9 : .45), + borderRadius: BorderRadius.circular(2), + ), + ), + ), + ), + ); +} diff --git a/app/packages/gb_export/.gitignore b/app/packages/gb_export/.gitignore new file mode 100644 index 0000000..b9d7f25 --- /dev/null +++ b/app/packages/gb_export/.gitignore @@ -0,0 +1,33 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.build/ +.buildlog/ +.history +.svn/ +.swiftpm/ +migrate_working_dir/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock. +/pubspec.lock +**/doc/api/ +.dart_tool/ +.flutter-plugins-dependencies +/build/ +/coverage/ diff --git a/app/packages/gb_export/.metadata b/app/packages/gb_export/.metadata new file mode 100644 index 0000000..a9b7281 --- /dev/null +++ b/app/packages/gb_export/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled and should not be manually edited. + +version: + revision: "6b182d2c7585eba26d4edce0f97630effd256c33" + channel: "stable" + +project_type: plugin + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: 6b182d2c7585eba26d4edce0f97630effd256c33 + base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33 + - platform: android + create_revision: 6b182d2c7585eba26d4edce0f97630effd256c33 + base_revision: 6b182d2c7585eba26d4edce0f97630effd256c33 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/app/packages/gb_export/android/.gitignore b/app/packages/gb_export/android/.gitignore new file mode 100644 index 0000000..161bdcd --- /dev/null +++ b/app/packages/gb_export/android/.gitignore @@ -0,0 +1,9 @@ +*.iml +.gradle +/local.properties +/.idea/workspace.xml +/.idea/libraries +.DS_Store +/build +/captures +.cxx diff --git a/app/packages/gb_export/android/build.gradle.kts b/app/packages/gb_export/android/build.gradle.kts new file mode 100644 index 0000000..ae5b310 --- /dev/null +++ b/app/packages/gb_export/android/build.gradle.kts @@ -0,0 +1,75 @@ +group = "dev.bashynx.gb_export" +version = "1.0-SNAPSHOT" + +buildscript { + val kotlinVersion = "2.3.20" + repositories { + google() + mavenCentral() + } + + dependencies { + classpath("com.android.tools.build:gradle:9.0.1") + classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion") + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +plugins { + id("com.android.library") +} + +android { + namespace = "dev.bashynx.gb_export" + + compileSdk = 36 + + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + + sourceSets { + getByName("main") { + java.srcDirs("src/main/kotlin") + } + getByName("test") { + java.srcDirs("src/test/kotlin") + } + } + + defaultConfig { + minSdk = 24 + } + + testOptions { + unitTests { + isIncludeAndroidResources = true + all { + it.useJUnitPlatform() + + it.outputs.upToDateWhen { false } + + it.testLogging { + events("passed", "skipped", "failed", "standardOut", "standardError") + showStandardStreams = true + } + } + } + } +} + +kotlin { + compilerOptions { + jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17 + } +} + +dependencies { +} diff --git a/app/packages/gb_export/android/settings.gradle.kts b/app/packages/gb_export/android/settings.gradle.kts new file mode 100644 index 0000000..fd63f79 --- /dev/null +++ b/app/packages/gb_export/android/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "gb_export" diff --git a/app/packages/gb_export/android/src/main/AndroidManifest.xml b/app/packages/gb_export/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..1b572a5 --- /dev/null +++ b/app/packages/gb_export/android/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + diff --git a/app/packages/gb_export/android/src/main/kotlin/dev/bashynx/gb_export/GbExportPlugin.kt b/app/packages/gb_export/android/src/main/kotlin/dev/bashynx/gb_export/GbExportPlugin.kt new file mode 100644 index 0000000..fb8ba21 --- /dev/null +++ b/app/packages/gb_export/android/src/main/kotlin/dev/bashynx/gb_export/GbExportPlugin.kt @@ -0,0 +1,92 @@ +package dev.bashynx.gb_export + +import android.app.Activity +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.provider.DocumentsContract +import io.flutter.embedding.engine.plugins.FlutterPlugin +import io.flutter.embedding.engine.plugins.activity.ActivityAware +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding +import io.flutter.plugin.common.MethodChannel +import io.flutter.plugin.common.PluginRegistry +import java.io.File + +// "dash/gbexport": pick() → uri or null (needs the activity) · info(uri) → {size, modified} or null · +// copy(uri, path) → true when copied · timeZone() → the phone's zone ("Europe/Bucharest"). +// info / copy / timeZone work without an activity (background tasks). +class GbExportPlugin : FlutterPlugin, ActivityAware, PluginRegistry.ActivityResultListener { + private val pickCode = 4711 + private lateinit var channel: MethodChannel + private lateinit var context: Context + private var activity: ActivityPluginBinding? = null + private var pending: MethodChannel.Result? = null + + override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) { + context = binding.applicationContext + channel = MethodChannel(binding.binaryMessenger, "dash/gbexport") + channel.setMethodCallHandler { call, result -> + when (call.method) { + "pick" -> { + val a = activity?.activity + if (a == null) { + result.error("no_activity", "the picker needs the app on screen", null) + } else { + pending = result + val i = Intent(Intent.ACTION_OPEN_DOCUMENT).addCategory(Intent.CATEGORY_OPENABLE).setType("*/*") + .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) + a.startActivityForResult(i, pickCode) + } + } + "info" -> result.success(info(Uri.parse(call.argument("uri")))) + "timeZone" -> result.success(java.util.TimeZone.getDefault().id) + "copy" -> result.success(try { + context.contentResolver.openInputStream(Uri.parse(call.argument("uri")))!!.use { inp -> + File(call.argument("path")!!).outputStream().use { inp.copyTo(it) } + } + true + } catch (e: Exception) { + false + }) + else -> result.notImplemented() + } + } + } + + override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) = channel.setMethodCallHandler(null) + + private fun info(uri: Uri): Map? = try { + context.contentResolver.query(uri, arrayOf(DocumentsContract.Document.COLUMN_SIZE, + DocumentsContract.Document.COLUMN_LAST_MODIFIED), null, null, null)?.use { c -> + if (c.moveToFirst()) mapOf("size" to c.getLong(0), "modified" to (if (c.isNull(1)) 0L else c.getLong(1))) else null + } + } catch (e: Exception) { + null + } + + override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?): Boolean { + if (requestCode != pickCode) return false + val uri = if (resultCode == Activity.RESULT_OK) data?.data else null + if (uri != null) { + try { + context.contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) + } catch (e: SecurityException) { + } + } + pending?.success(uri?.toString()) + pending = null + return true + } + + override fun onAttachedToActivity(binding: ActivityPluginBinding) { + activity = binding + binding.addActivityResultListener(this) + } + + override fun onDetachedFromActivityForConfigChanges() = onDetachedFromActivity() + override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) = onAttachedToActivity(binding) + override fun onDetachedFromActivity() { + activity?.removeActivityResultListener(this) + activity = null + } +} diff --git a/app/packages/gb_export/lib/gb_export.dart b/app/packages/gb_export/lib/gb_export.dart new file mode 100644 index 0000000..64064b7 --- /dev/null +++ b/app/packages/gb_export/lib/gb_export.dart @@ -0,0 +1,25 @@ +// Gadgetbridge's database export on this phone, through Android's file picker: picked once (the read +// permission is kept), then read again after every new export — from the app and from background tasks +// (a plugin, so WorkManager's engine has it too). Android: GbExportPlugin.kt. +import 'package:flutter/services.dart'; + +const _channel = MethodChannel('dash/gbexport'); + +/// The system file picker → the file's uri (null = cancelled). Needs the app on screen. +Future pickExport() => _channel.invokeMethod('pick'); + +/// {size, modified (ms)} — null when the file is gone or no longer readable. +Future?> exportInfo(String uri) => _channel.invokeMapMethod('info', {'uri': uri}); + +/// The phone's time zone ("Europe/Bucharest"); null where there's no Android (tests). +Future timeZone() async { + try { + return await _channel.invokeMethod('timeZone'); + } on MissingPluginException { + return null; + } +} + +/// Copy the file to [path] → true when copied. +Future copyExport(String uri, String path) async => + await _channel.invokeMethod('copy', {'uri': uri, 'path': path}) ?? false; diff --git a/app/packages/gb_export/pubspec.yaml b/app/packages/gb_export/pubspec.yaml new file mode 100644 index 0000000..679237d --- /dev/null +++ b/app/packages/gb_export/pubspec.yaml @@ -0,0 +1,19 @@ +name: gb_export +description: "dashPi app: read Gadgetbridge's database export through Android's file picker (kept permission) — also from a background task." +version: 0.0.1 +publish_to: none + +environment: + sdk: ^3.12.2 + flutter: '>=3.3.0' + +dependencies: + flutter: + sdk: flutter + +flutter: + plugin: + platforms: + android: + package: dev.bashynx.gb_export + pluginClass: GbExportPlugin diff --git a/app/pubspec.lock b/app/pubspec.lock new file mode 100644 index 0000000..5d39291 --- /dev/null +++ b/app/pubspec.lock @@ -0,0 +1,825 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + archive: + dependency: transitive + description: + name: archive + sha256: "0d58d1fa1fddf6588251ccf2819f3fb3b6d0452c1b2813ac7413a05592bfbefe" + url: "https://pub.dev" + source: hosted + version: "4.5.2" + args: + dependency: transitive + description: + name: args + sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04 + url: "https://pub.dev" + source: hosted + version: "2.7.0" + async: + dependency: transitive + description: + name: async + sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37 + url: "https://pub.dev" + source: hosted + version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + camera: + dependency: transitive + description: + name: camera + sha256: "3f30ca0ff376f91534f23afa2a7aea06ebb6c889fd9e260642437b37e3d9f753" + url: "https://pub.dev" + source: hosted + version: "0.12.1" + camera_android_camerax: + dependency: transitive + description: + name: camera_android_camerax + sha256: faf885ca8140f22df8dc05d1839afc702d0329dd9b0b2f0bc6f9b05f3f20e10c + url: "https://pub.dev" + source: hosted + version: "0.7.6" + camera_avfoundation: + dependency: transitive + description: + name: camera_avfoundation + sha256: e409a731fad3fca10daa9567cf981720398659e6390f871a4e0f576058ff8940 + url: "https://pub.dev" + source: hosted + version: "0.10.3+1" + camera_platform_interface: + dependency: transitive + description: + name: camera_platform_interface + sha256: b3083b183ef1daa408d5f0c98c8c7ac0325b490695fb4557ff4210fcf04c5984 + url: "https://pub.dev" + source: hosted + version: "2.15.0" + camera_web: + dependency: transitive + description: + name: camera_web + sha256: "5aecf1ac4dd4a949c5a7820e590020acb2bc35425384ab87a030e1739bfe12e2" + url: "https://pub.dev" + source: hosted + version: "0.3.5+6" + characters: + dependency: transitive + description: + name: characters + sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b + url: "https://pub.dev" + source: hosted + version: "1.4.1" + clock: + dependency: transitive + description: + name: clock + sha256: fddb70d9b5277016c77a80201021d40a2247104d9f4aa7bab7157b7e3f05b84b + url: "https://pub.dev" + source: hosted + version: "1.1.2" + code_assets: + dependency: transitive + description: + name: code_assets + sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + collection: + dependency: transitive + description: + name: collection + sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76" + url: "https://pub.dev" + source: hosted + version: "1.19.1" + cross_file: + dependency: transitive + description: + name: cross_file + sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6 + url: "https://pub.dev" + source: hosted + version: "0.3.5+5" + crypto: + dependency: transitive + description: + name: crypto + sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf + url: "https://pub.dev" + source: hosted + version: "3.0.7" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd" + url: "https://pub.dev" + source: hosted + version: "1.0.9" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" + url: "https://pub.dev" + source: hosted + version: "1.3.3" + ffi: + dependency: transitive + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + file_selector_linux: + dependency: transitive + description: + name: file_selector_linux + sha256: da76400e7872ce7637ffdce12749ec24169c25f6195c28372208e65a24bcd2ab + url: "https://pub.dev" + source: hosted + version: "0.9.4+1" + file_selector_macos: + dependency: transitive + description: + name: file_selector_macos + sha256: d57c62362766b5e7ae739448650b66c6aab7a68ba7ecc65e04018652645ae0f4 + url: "https://pub.dev" + source: hosted + version: "0.9.5+1" + file_selector_platform_interface: + dependency: transitive + description: + name: file_selector_platform_interface + sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85" + url: "https://pub.dev" + source: hosted + version: "2.7.0" + file_selector_windows: + dependency: transitive + description: + name: file_selector_windows + sha256: fbefc5fb92c6d3cbe8d284a2cd971b593bb07d2cd6da8557b81a862250b4acec + url: "https://pub.dev" + source: hosted + version: "0.9.3+6" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1" + url: "https://pub.dev" + source: hosted + version: "6.0.0" + flutter_plugin_android_lifecycle: + dependency: transitive + description: + name: flutter_plugin_android_lifecycle + sha256: "3854fe5e3bff0b113c658f260b90c95dea17c92db0f2addeac2e343dd9969785" + url: "https://pub.dev" + source: hosted + version: "2.0.35" + flutter_secure_storage: + dependency: "direct main" + description: + name: flutter_secure_storage + sha256: d4e1fb6b2cb524868929e78dc0282fa000554b22060fb53789dc481c9fc95bb8 + url: "https://pub.dev" + source: hosted + version: "11.2.0" + flutter_secure_storage_darwin: + dependency: transitive + description: + name: flutter_secure_storage_darwin + sha256: a031ceac9b070e62ef183cd7f7d1a8798ebde402d5049f0fe6eb3a51bd797a21 + url: "https://pub.dev" + source: hosted + version: "0.4.3" + flutter_secure_storage_linux: + dependency: transitive + description: + name: flutter_secure_storage_linux + sha256: caa75bd78f017422912e3a904933113b2428eb79f981ac37acd2dd2a700458ea + url: "https://pub.dev" + source: hosted + version: "3.0.3" + flutter_secure_storage_platform_interface: + dependency: transitive + description: + name: flutter_secure_storage_platform_interface + sha256: "64951127f001f546891c86f414972bf49ef2c4c8a4c92c65f5790cc0c9100045" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + flutter_secure_storage_web: + dependency: transitive + description: + name: flutter_secure_storage_web + sha256: "073a62b3aeb866ab4ce795f960413948e51e5a42a9b0c8333b6daf5bb3208a1c" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + flutter_secure_storage_windows: + dependency: transitive + description: + name: flutter_secure_storage_windows + sha256: "471951813a97006d899db4948acc654a4f28c440083ea08178935ce20b173ec1" + url: "https://pub.dev" + source: hosted + version: "4.2.2" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + flutter_zxing: + dependency: "direct main" + description: + name: flutter_zxing + sha256: ee2b97bf69b01385b91497501c060f4e3b53686709892e005de10f3ad30eee98 + url: "https://pub.dev" + source: hosted + version: "3.1.0" + freezed_annotation: + dependency: transitive + description: + name: freezed_annotation + sha256: "7294967ff0a6d98638e7acb774aac3af2550777accd8149c90af5b014e6d44d8" + url: "https://pub.dev" + source: hosted + version: "3.1.0" + gb_export: + dependency: "direct main" + description: + path: "packages/gb_export" + relative: true + source: path + version: "0.0.1" + glob: + dependency: transitive + description: + name: glob + sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + hooks: + dependency: transitive + description: + name: hooks + sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + html: + dependency: transitive + description: + name: html + sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" + url: "https://pub.dev" + source: hosted + version: "0.15.7" + http: + dependency: "direct main" + description: + name: http + sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412" + url: "https://pub.dev" + source: hosted + version: "1.6.0" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: "89ed75b2f8231fe676808c5564f9590d728024ded7ac782a7ed8474f1c95b72a" + url: "https://pub.dev" + source: hosted + version: "4.12.0" + image_picker: + dependency: transitive + description: + name: image_picker + sha256: e71b1bd9e40124041128d60fc3034c7b1598e1bba4e570bba0c70301c817013a + url: "https://pub.dev" + source: hosted + version: "1.2.4" + image_picker_android: + dependency: transitive + description: + name: image_picker_android + sha256: "8a7823d5d3e884f7780829d85d92110d072bdcd9ed48e2be158d2abe91a912d4" + url: "https://pub.dev" + source: hosted + version: "0.8.13+25" + image_picker_for_web: + dependency: transitive + description: + name: image_picker_for_web + sha256: "66257a3191ab360d23a55c8241c91a6e329d31e94efa7be9cf7a212e65850214" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + image_picker_ios: + dependency: transitive + description: + name: image_picker_ios + sha256: "4fb88d4350ffc208c2a09fc321db1f80282688716b8cfe10c8c80acc5ae8934a" + url: "https://pub.dev" + source: hosted + version: "0.8.13+10" + image_picker_linux: + dependency: transitive + description: + name: image_picker_linux + sha256: "1f81c5f2046b9ab724f85523e4af65be1d47b038160a8c8deed909762c308ed4" + url: "https://pub.dev" + source: hosted + version: "0.2.2" + image_picker_macos: + dependency: transitive + description: + name: image_picker_macos + sha256: "86f0f15a309de7e1a552c12df9ce5b59fe927e71385329355aec4776c6a8ec91" + url: "https://pub.dev" + source: hosted + version: "0.2.2+1" + image_picker_platform_interface: + dependency: transitive + description: + name: image_picker_platform_interface + sha256: "2dee4b4e3be429db71472c9c559c981498070a61af1ba82e0e4986fc5dadc042" + url: "https://pub.dev" + source: hosted + version: "2.11.2" + image_picker_windows: + dependency: transitive + description: + name: image_picker_windows + sha256: d248c86554a72b5495a31c56f060cf73a41c7ff541689327b1a7dbccc33adfae + url: "https://pub.dev" + source: hosted + version: "0.2.2" + jni: + dependency: transitive + description: + name: jni + sha256: "6b9ca0602fef0230e83149afbe3f9f8227e94f2bbe84a1da4f14d699742f402d" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + jni_flutter: + dependency: transitive + description: + name: jni_flutter + sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191" + url: "https://pub.dev" + source: hosted + version: "1.0.4+1" + jni_util: + dependency: transitive + description: + name: jni_util + sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f" + url: "https://pub.dev" + source: hosted + version: "1.0.0" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "2a743920d81b7910627f68ee2c9ac1fc0bfee32b9fc3403587d7c6791ca12f80" + url: "https://pub.dev" + source: hosted + version: "4.12.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de" + url: "https://pub.dev" + source: hosted + version: "11.0.2" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1" + url: "https://pub.dev" + source: hosted + version: "3.0.10" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + lints: + dependency: transitive + description: + name: lints + sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df" + url: "https://pub.dev" + source: hosted + version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: dc0b7dc7651697ea4ff3e69ef44b0407ea32c487a39fff6a4004fa585e901861 + url: "https://pub.dev" + source: hosted + version: "0.12.19" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b" + url: "https://pub.dev" + source: hosted + version: "0.13.0" + meta: + dependency: transitive + description: + name: meta + sha256: "1741988757a65eb6b36abe716829688cf01910bbf91c34354ff7ec1c3de2b349" + url: "https://pub.dev" + source: hosted + version: "1.18.0" + mime: + dependency: transitive + description: + name: mime + sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6 + url: "https://pub.dev" + source: hosted + version: "2.1.0" + native_toolchain_c: + dependency: transitive + description: + name: native_toolchain_c + sha256: f9c168717100ae6d9fee9ffb0be379bf1f8b26b0f6bcbd4fdddcd931993a6a72 + url: "https://pub.dev" + source: hosted + version: "0.19.2" + objective_c: + dependency: transitive + description: + name: objective_c + sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e + url: "https://pub.dev" + source: hosted + version: "9.5.0" + package_config: + dependency: transitive + description: + name: package_config + sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d + url: "https://pub.dev" + source: hosted + version: "3.0.0" + path: + dependency: transitive + description: + name: path + sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5" + url: "https://pub.dev" + source: hosted + version: "1.9.1" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825 + url: "https://pub.dev" + source: hosted + version: "2.1.6" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd" + url: "https://pub.dev" + source: hosted + version: "2.3.1" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699" + url: "https://pub.dev" + source: hosted + version: "2.6.0" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16" + url: "https://pub.dev" + source: hosted + version: "2.2.2" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec + url: "https://pub.dev" + source: hosted + version: "3.2.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + posix: + dependency: transitive + description: + name: posix + sha256: bc1bad54ad2b735816e31f8d4600cfde6c7839975085ddfbca48b6c9f7c4044e + url: "https://pub.dev" + source: hosted + version: "6.5.2" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" + url: "https://pub.dev" + source: hosted + version: "2.2.1" + record_use: + dependency: transitive + description: + name: record_use + sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed" + url: "https://pub.dev" + source: hosted + version: "0.6.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + sodium: + dependency: "direct main" + description: + name: sodium + sha256: "3d8bec7acb3bd958309e431a840f1eded82f508d57461ecd2920d399b802b38a" + url: "https://pub.dev" + source: hosted + version: "4.0.4" + source_span: + dependency: transitive + description: + name: source_span + sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab" + url: "https://pub.dev" + source: hosted + version: "1.10.2" + sqlite3: + dependency: "direct main" + description: + name: sqlite3 + sha256: "4c7fe79840389aaeaf05fd093f795b631b5a98e2bd28d54e555c100f4a9c7a1c" + url: "https://pub.dev" + source: hosted + version: "3.5.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "8b27215b45d22309b5cddda1aa2b19bdfec9df0e765f2de506401c071d38d1b1" + url: "https://pub.dev" + source: hosted + version: "1.12.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + stream_transform: + dependency: transitive + description: + name: stream_transform + sha256: a00e5f18bffc764f923e7dec1038527f7fe7a1791361a7117f0358193f13d53a + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43" + url: "https://pub.dev" + source: hosted + version: "1.4.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e" + url: "https://pub.dev" + source: hosted + version: "1.2.2" + test_api: + dependency: transitive + description: + name: test_api + sha256: "949a932224383300f01be9221c39180316445ecb8e7547f70a41a35bf421fb9e" + url: "https://pub.dev" + source: hosted + version: "0.7.11" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: d530bd74fea330e6e364cda7a85019c434070188383e1cd8d9777ee586914c5b + url: "https://pub.dev" + source: hosted + version: "2.2.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78" + url: "https://pub.dev" + source: hosted + version: "15.4.0" + web: + dependency: transitive + description: + name: web + sha256: "868d88a33d8a87b18ffc05f9f030ba328ffefba92d6c127917a2ba740f9cfe4a" + url: "https://pub.dev" + source: hosted + version: "1.1.1" + win32: + dependency: transitive + description: + name: win32 + sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d + url: "https://pub.dev" + source: hosted + version: "6.4.0" + workmanager: + dependency: "direct main" + description: + name: workmanager + sha256: "96b09a4a852ec487d29371f27031dab80ce2e260911e2dbe0f904951e22a3956" + url: "https://pub.dev" + source: hosted + version: "0.10.10" + workmanager_android: + dependency: transitive + description: + name: workmanager_android + sha256: ffe8aa061885370c9363f7ae2d2196d31855217c58e7b15899d915d36c768c4a + url: "https://pub.dev" + source: hosted + version: "0.10.9" + workmanager_apple: + dependency: transitive + description: + name: workmanager_apple + sha256: "9e0ca0b857df986b37ca964ffa3b21990e1bc0f7935356a9706b47e5b71a7524" + url: "https://pub.dev" + source: hosted + version: "0.9.11" + workmanager_linux: + dependency: transitive + description: + name: workmanager_linux + sha256: "7d8520e1103b910a43d8bafe37ec2415f4c7c148afcb1eee0ec73ae67b4cdd22" + url: "https://pub.dev" + source: hosted + version: "0.1.1+1" + workmanager_platform_interface: + dependency: transitive + description: + name: workmanager_platform_interface + sha256: a1022dca1284d64ba8bbe046edc9089cc5158b3d0e2cf9f68c7cde2fbf89746c + url: "https://pub.dev" + source: hosted + version: "0.10.5" + workmanager_web: + dependency: transitive + description: + name: workmanager_web + sha256: "2ac481ade599bdd957ee2891be09a0c34be87923a2c3ca4dfe36add6fc735ffd" + url: "https://pub.dev" + source: hosted + version: "0.2.0" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + yaml: + dependency: transitive + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" +sdks: + dart: ">=3.12.2 <4.0.0" + flutter: ">=3.44.0" diff --git a/app/pubspec.yaml b/app/pubspec.yaml new file mode 100644 index 0000000..8278fb3 --- /dev/null +++ b/app/pubspec.yaml @@ -0,0 +1,100 @@ +name: dash_app +description: "dashPi companion: health, work, weather — offline, synced end-to-end encrypted through your own server" +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.1.2+5 + +environment: + sdk: ^3.12.2 + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + cupertino_icons: ^1.0.8 + sqlite3: ">=3.0.0 <3.6.0" + flutter_secure_storage: ^11.2.0 + http: ^1.6.0 + path_provider: ^2.1.6 + sodium: ^4.0.4 + workmanager: ^0.10.10 + gb_export: + path: packages/gb_export # Gadgetbridge's export through the file picker (also in background tasks) + flutter_zxing: ^3.1.0 +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^6.0.0 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + assets: + - assets/weather/ # the weather icons: Meteocons (MIT), the dashboard's same files (tools/weather-icons.py) + - assets/foods.db # the dashboard's food database (USDA + Open Food Facts) — the same file as on the Pi + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/to/resolution-aware-images + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/to/asset-from-package + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/to/font-from-package diff --git a/app/test/food_product_test.dart b/app/test/food_product_test.dart new file mode 100644 index 0000000..c94739e --- /dev/null +++ b/app/test/food_product_test.dart @@ -0,0 +1,45 @@ +// Products kept from the archive ("food.product", food_model.dart): stored as the dashboard's db.save_product +// does (uid "p:"), found again by id / barcode / name (folded), and their added sugar. +import 'dart:io'; + +import 'package:dash_app/health/food_model.dart'; +import 'package:dash_app/health/sugar.dart'; +import 'package:dash_app/sync/store.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final store = SyncStore('${Directory.systemTemp.createTempSync('product').path}/d.db', 'test00000000'); + final item = { + 'id': 24032663211215, 'name': 'Zarte Haferflocken', 'brand': 'Kölln', 'barcode': '4032663211215', 'countries': 'germany', + 'category': 'Kölln · Rolled oats', 'nutriscore': 'a', 'nova': 1, 'labels': null, 'sugars_in': '', 'dairy': 0, 'added_sugar': null, + 'per100': {'kcal': 372, 'protein': 13.5, 'carbs': 58.7, 'sugar': 0.7, 'fat': 7}, + 'portions': [{'label': 'serving (40 g)', 'grams': 40}], + }; + + test('kept, found again, synced under p:', () { + final f = keepProduct(store, item)!; + expect(f.foodId, 24032663211215); + expect(f.portions.single.grams, 40); + expect(store.row(tProduct, 'p:24032663211215')!['food_id'], 24032663211215); + expect(keptProduct(store, 24032663211215)!.name, 'Zarte Haferflocken'); + expect(keptByBarcode(store, '4032663211215').single.brand, 'Kölln'); + expect(keptProducts(store, 'kolln hafer', fold: fold).single.foodId, 24032663211215); + expect(keptProducts(store, 'muesli', fold: fold), isEmpty); + }); + + test('not a product: refused', () { + expect(keepProduct(store, {...item, 'id': 123}), isNull); + expect(keepProduct(store, {...item, 'name': ' '}), isNull); + }); + + test('added sugar: the label figure first, else its ingredients', () { + final oats = keepProduct(store, item)!; + expect(foodPart(oats, 0.7, 100), 0); // sugars_in "" → natural + final cereal = keepProduct(store, {...item, 'id': 20000000000017, 'name': 'Choco cereal', 'sugars_in': 'sugar', + 'added_sugar': 20, 'per100': {'kcal': 390, 'sugar': 25}})!; + expect(foodPart(cereal, 25, 100), 20); // the label's 20 of 25 g + final zero = keepProduct(store, {...item, 'id': 20000000000018, 'name': 'Wafer', 'nova': 4, 'sugars_in': 'sugar', 'added_sugar': 0, + 'per100': {'kcal': 500, 'sugar': 30}})!; + expect(foodPart(zero, 30, 100), 30); // "0 added" yet sugar in the ingredients: the 0 is ignored + }); +} diff --git a/app/test/location_test.dart b/app/test/location_test.dart new file mode 100644 index 0000000..108cfbd --- /dev/null +++ b/app/test/location_test.dart @@ -0,0 +1,35 @@ +// app/location.dart against a stand-in for MainActivity's "dash/location": a fix, or why there's none. +import 'package:dash_app/app/location.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const ch = MethodChannel('dash/location'); + + Future<(({double lat, double lon})?, String)> run(Map answers) async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(ch, (c) async => answers[c.method]); + var why = ''; + final at = await whereAmI(none: (w) => why = w); + return (at, why); + } + + test('not allowed, refused again', () async { + expect(await run({'status': {'allowed': false, 'enabled': true}, 'ask': false}), (null, 'location not allowed')); + }); + test('switched off', () async { + expect(await run({'status': {'allowed': true, 'enabled': false}}), (null, 'location off')); + }); + test('the last fix', () async { + final (at, _) = await run({'status': {'allowed': true, 'enabled': true}, 'last': {'lat': 47.17, 'lon': 24.06}}); + expect((at!.lat, at.lon), (47.17, 24.06)); + }); + test('allowed now, a new fix', () async { + final (at, _) = await run({'status': {'allowed': false, 'enabled': true}, 'ask': true, 'last': null, 'current': {'lat': 46.77, 'lon': 23.6}}); + expect(at!.lat, 46.77); + }); + test('nothing found', () async { + expect(await run({'status': {'allowed': true, 'enabled': true}, 'last': null, 'current': null}), (null, 'no location found')); + }); +} diff --git a/app/test/notes_test.dart b/app/test/notes_test.dart new file mode 100644 index 0000000..eb4669d --- /dev/null +++ b/app/test/notes_test.dart @@ -0,0 +1,107 @@ +// Notes: the sync's "keep both copies" (SyncStore.forks — the same cases as the dashboard's syncdb +// "fork"), saving on an old version, and ticking checkboxes. flutter test test/notes_test.dart +import 'dart:io'; + +import 'package:dash_app/notes/markdown.dart'; +import 'package:dash_app/notes/notes_model.dart'; +import 'package:dash_app/sync/store.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final dir = Directory.systemTemp.createTempSync('notes_test'); + var k = 0; + SyncStore dev(String name) => SyncStore('${dir.path}/${k++}.db', name); + + /// Everything [from] hasn't sent yet → the others. + void send(SyncStore from, List to) { + final (changes, mark) = from.changes(); + from.markPushed(mark); + for (final s in to) { + s.apply(changes); + } + } + + List show(SyncStore s) => + [for (final n in allNotes(s)) '${n.body}${n.origin != null ? ' (copy)' : ''}${n.pinned ? ' (pinned)' : ''}']..sort(); + String main(SyncStore s) => allNotes(s).firstWhere((n) => n.origin == null).id; + void edit(SyncStore s, String body) { + final n = getNote(s, main(s))!; + saveNote(s, id: n.id, body: body, base: n.rev); + sleep(const Duration(milliseconds: 3)); + } + + test('two devices editing one note keep both texts, and all agree', () { + final a = dev('aaaaaaaaaaaa'), b = dev('bbbbbbbbbbbb'), c = dev('cccccccccccc'); + saveNote(a, body: 'v0'); + send(a, [b, c]); + edit(a, 'v1'); + edit(a, 'v2'); + send(a, [b, c]); + expect(show(b), ['v2'], reason: 'one after the other: no copy'); + + edit(a, 'A-text'); + edit(b, 'B-text'); + send(a, [b, c]); + send(b, [a, c]); + expect(show(a), ['A-text (copy)', 'B-text']); + expect(show(b), show(a)); + expect(show(c), show(a)); + + // b edits the text, then a (older text) pins: b's text + a's pin, everywhere + edit(b, 'B2'); + send(b, [c]); + setNote(a, main(a), {'pinned': 1}); + send(a, [b, c]); + send(b, [a, c]); + send(c, [a, b]); + expect(show(a), ['A-text (copy)', 'B2 (pinned)']); + expect(show(b), show(a)); + expect(show(c), show(a)); + + // a copy deleted on one device is gone everywhere and not made again + a.delete(noteTable, allNotes(a).firstWhere((n) => n.origin != null).id); + send(a, [b, c]); + expect(show(b), ['B2 (pinned)']); + expect(show(c), ['B2 (pinned)']); + }); + + test('typing goes on in one version until it has been sent', () { + final a = dev('aaaaaaaaaaaa'); + final (id, _) = saveNote(a, body: 'x'); + final r0 = getNote(a, id)!.rev; + saveNote(a, id: id, body: 'xy', base: r0); + expect(getNote(a, id)!.rev, r0); + a.markPushed(a.changes().$2); + saveNote(a, id: id, body: 'xyz', base: r0); + final n = getNote(a, id)!; + expect(n.rev, isNot(r0)); + expect(n.r['revs'], '$r0 ${n.rev}'); + }); + + test('a save on an old version becomes a copy', () { + final a = dev('aaaaaaaaaaaa'), b = dev('bbbbbbbbbbbb'); + final (id, _) = saveNote(a, body: 'start'); + send(a, [b]); + final seen = getNote(b, id)!.rev; // b opens it … + edit(a, 'changed on a'); + send(a, [b]); // … a's change arrives while b types + final (nid, conflict) = saveNote(b, id: id, body: 'typed on b', base: seen); + expect(conflict, isTrue); + expect(nid, isNot(id)); + expect(show(b), ['changed on a', 'typed on b (copy)']); + }); + + test('checkboxes tick by their number, outside code blocks', () { + const src = '- [ ] one\n```\n- [ ] not this\n```\n> - [x] two\n1. [ ] three'; + expect(toggleTask(src, 0), contains('- [x] one')); + expect(toggleTask(src, 1), contains('> - [ ] two')); + expect(toggleTask(src, 2), contains('1. [x] three')); + expect(toggleTask(src, 2), contains('- [ ] not this')); + }); + + test('title, tags, folders', () { + expect(noteTitle('\n\n## Shopping list\n- milk'), 'Shopping list'); + expect(noteTags('#home and #Work/acme, not a#b, `#code`, # heading'), ['home', 'work/acme']); + expect(cleanFolder(' Work / Acme/ '), 'Work/Acme'); + }); +} diff --git a/app/test/sugar_test.dart b/app/test/sugar_test.dart new file mode 100644 index 0000000..7c991d7 --- /dev/null +++ b/app/test/sugar_test.dart @@ -0,0 +1,51 @@ +// sugar.dart against the dashboard's plugins/food/sugar.py: the same kinds for the same foods (the table +// below is sugar.kind's output — regenerate it there when the rules change) and the same folding. +import 'package:dash_app/health/sugar.dart'; +import 'package:flutter_test/flutter_test.dart'; + +// name, category, source, nova, labels, sugarsIn, dairy → kind +const cases = <(String, String, String, int?, String, String?, int?, String)>[ + ('Figs, dried, uncooked', 'Fruits and Fruit Juices', 'sr_legacy', null, '', null, null, 'natural'), + ('Orange juice, raw', 'Fruits and Fruit Juices', 'sr_legacy', null, '', null, null, 'added'), + ('Beverages, carbonated, cola, regular', 'Beverages', 'sr_legacy', null, '', null, null, 'added'), + ('Alcoholic beverage, wine, table, red', 'Beverages', 'sr_legacy', null, '', null, null, 'added'), + ('Yogurt, plain, whole milk', 'Dairy and Egg Products', 'sr_legacy', null, '', null, null, 'dairy'), + ('Yogurt, fruit, low fat', 'Dairy and Egg Products', 'sr_legacy', null, '', null, null, 'dairy'), + ('Zahăr brun', '', '', null, '', null, null, 'added'), + ('Smântână 20%', '', '', null, '', null, null, 'dairy'), + ('Sušienky s čokoládou', '', '', null, '', null, null, 'added'), + ('Túró Rudi', '', '', null, '', null, null, 'dairy'), + ('Apfelsaft naturtrüb', '', '', null, '', null, null, 'added'), + ('Mandelmilch ungesüßt', '', '', null, '', null, null, 'natural'), + ('Lapte de migdale', '', '', null, '', null, null, 'natural'), + ('Iaurt grecesc', '', '', null, '', null, null, 'dairy'), + ('Gemüsebrühe', '', '', null, '', null, null, 'natural'), + ('Ciocolată neagră 70%', '', '', null, '', null, null, 'added'), + ('Tomates pelées', 'Tomatoes', 'off', 3, '', '', 0, 'natural'), + ('Biscuiți cu unt', 'Biscuits', 'off', 4, '', 'sugar, glucose syrup', 0, 'added'), + ('Jogurt jahodový', 'Yogurts', 'off', 3, '', 'sugar', 1, 'dairy'), + ('Jogurt biely', 'Yogurts', 'off', 3, '', '', 1, 'dairy'), + ('Müsli ohne Zuckerzusatz', 'Cereals', 'off', 3, 'no added sugar', null, 0, 'natural'), + ('Bio Haferflocken', '', 'off', 1, '', null, null, 'natural'), + ('Sardine fillets', '', 'off', null, '', null, null, 'added'), + ('Kefír', '', 'off', null, '', null, null, 'dairy'), + ('Plant drink, oat', '', 'off', 4, '', '', 0, 'natural'), + ('Cereals, oats, regular and quick, not fortified, dry', 'Breakfast Cereals', 'sr_legacy', null, '', null, null, 'natural'), + ('Cereals ready-to-eat, POST, HONEY BUNCHES OF OATS, honey roasted', 'Breakfast Cereals', 'sr_legacy', null, '', null, null, 'added'), + ('Wine, table, red', 'Wine', 'survey', null, '', null, null, 'added'), +]; + +void main() { + test('kinds match sugar.py', () { + for (final (name, category, source, nova, labels, sugarsIn, dairy, want) in cases) { + expect(sugarKind(name, category: category, source: source, nova: nova, labels: labels, sugarsIn: sugarsIn, dairy: dairy), + want, reason: name); + } + }); + + test('folding matches sugar.fold', () { + const want = {'Zahăr': 'zahar', 'ŠŤAVA': 'stava', 'Groß': 'gross', 'Łódź': 'lodz', 'smântână': 'smantana', + 'Crème brûlée': 'creme brulee', 'tvaroh': 'tvaroh'}; + want.forEach((w, f) => expect(fold(w), f, reason: w)); + }); +} diff --git a/app/test/weather_location_test.dart b/app/test/weather_location_test.dart new file mode 100644 index 0000000..305c1d4 --- /dev/null +++ b/app/test/weather_location_test.dart @@ -0,0 +1,74 @@ +// Weather ▸ Current location when the phone can't tell where it is: the error banner on top, home (the first place) shown; +// no place at all: the banner, no crash. +import 'dart:io'; + +import 'package:dash_app/app/sync_service.dart'; +import 'package:dash_app/sync/client.dart'; +import 'package:dash_app/sync/store.dart'; +import 'package:dash_app/weather/weather_page.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('no location → the banner, home shown', (tester) async { + tester.view.physicalSize = const Size(1200, 2700); + tester.view.devicePixelRatio = 3; + addTearDown(tester.view.reset); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(const MethodChannel('dash/location'), (c) async => + {'status': {'allowed': false, 'enabled': true}, 'ask': false}[c.method]); + final store = SyncStore('${Directory.systemTemp.createTempSync('wx').path}/d.db', 'test00000000'); + store.setMeta('wx_here', 1); // Current location picked + store.setMetaText('wx_places', '[{"name": "Hometown, XX", "lat": 47.1, "lon": 24.0}]'); + final sync = SyncService(SyncSettings(server: 'http://x.invalid', token: 't', account: 'a', name: 'n', device: 'test00000000', + key: Uint8List(32)), store); + await tester.pumpWidget(MaterialApp(home: WeatherPage(sync: sync))); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(find.text('Location isn\'t allowed for this app'), findsOneWidget); + expect(find.text('Showing Hometown (home) instead.'), findsOneWidget); + expect(find.text('Hometown'), findsOneWidget); // the title: home, not "Hometown (location not allowed)" + sync.dispose(); + }); + + testWidgets('no location and no place → the banner, no crash', (tester) async { + tester.view.physicalSize = const Size(1200, 2700); + tester.view.devicePixelRatio = 3; + addTearDown(tester.view.reset); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(const MethodChannel('dash/location'), (c) async => + {'status': {'allowed': false, 'enabled': true}, 'ask': false}[c.method]); + final store = SyncStore('${Directory.systemTemp.createTempSync('wx').path}/d.db', 'test00000000'); + final sync = SyncService(SyncSettings(server: 'http://x.invalid', token: 't', account: 'a', name: 'n', device: 'test00000000', + key: Uint8List(32)), store); + await tester.pumpWidget(MaterialApp(home: WeatherPage(sync: sync))); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(find.text('Location isn\'t allowed for this app'), findsOneWidget); + expect(tester.takeException(), isNull); + sync.dispose(); + }); + + testWidgets("the dashboard's places (synced weather.place) come first: home from there", (tester) async { + tester.view.physicalSize = const Size(1200, 2700); + tester.view.devicePixelRatio = 3; + addTearDown(tester.view.reset); + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(const MethodChannel('dash/location'), (c) async => + {'status': {'allowed': false, 'enabled': true}, 'ask': false}[c.method]); + final store = SyncStore('${Directory.systemTemp.createTempSync('wx').path}/d.db', 'test00000000'); + store.apply([ + {'t': 'weather.place', 'u': 'place:Townsville, XX', 'h': 5, 'd': 'pi0000000000', + 'row': {'k': 'Townsville, XX', 'name': 'Townsville, XX', 'lat': 45.0, 'lon': 10.0, 'ord': 0}}, + ]); + store.setMeta('wx_here', 1); + final sync = SyncService(SyncSettings(server: 'http://x.invalid', token: 't', account: 'a', name: 'n', device: 'test00000000', + key: Uint8List(32)), store); + await tester.pumpWidget(MaterialApp(home: WeatherPage(sync: sync))); + for (var i = 0; i < 10; i++) { + await tester.pump(const Duration(milliseconds: 100)); + } + expect(find.text('Showing Townsville (home) instead.'), findsOneWidget); + sync.dispose(); + }); +} diff --git a/app/test/work_model_test.dart b/app/test/work_model_test.dart new file mode 100644 index 0000000..12ffc58 --- /dev/null +++ b/app/test/work_model_test.dart @@ -0,0 +1,112 @@ +// work_model.dart against the dashboard's own numbers (plugins/workload views.week / report) on the +// same rows. The fixture is real data, so it isn't in the repo: make it on the Pi (rows in wire +// format + the Pi's results) and run WORK_FIXTURE= flutter test test/work_model_test.dart +import 'dart:convert'; +import 'dart:io'; + +import 'package:dash_app/sync/store.dart'; +import 'package:dash_app/work/work_model.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final path = Platform.environment['WORK_FIXTURE']; + final skip = path == null ? 'WORK_FIXTURE not set' : null; + late SyncStore store; + late Map exp; + late DateTime now; + + setUpAll(() { + if (path == null) return; + final fx = jsonDecode(File(path).readAsStringSync()) as Map; + exp = fx['expect'] as Map; + now = DateTime.parse(exp['today'] as String).add(const Duration(hours: 12)); + final dir = Directory.systemTemp.createTempSync('work_test'); + store = SyncStore('${dir.path}/data.db', 'test00000000'); + for (final r in (fx['rows'] as List).cast()) { + store.put(r[0] as String, r[1] as String, (r[2] as Map).cast()); + } + }); + + test('weeks match the Pi', () { + final t = Tree(store); + for (final MapEntry(key: off, value: w) in (exp['weeks'] as Map).entries) { + final v = week(store, t, int.parse(off), now); + expect(hm(v.minutes), w['total'], reason: 'week $off total'); + expect(hm(v.billableMinutes), w['billable'], reason: 'week $off billable'); + expect([for (final e in (v.amounts.entries.toList()..sort((a, b) => a.key.compareTo(b.key)))) money(e.value, e.key)], + w['amounts'], reason: 'week $off amounts'); + expect([for (final d in v.days) [d.billableMinutes > 0 ? hm(d.billableMinutes) : '', + d.minutes - d.billableMinutes > 0 ? hm(d.minutes - d.billableMinutes) : '']], w['days'], reason: 'week $off days'); + expect([for (final c in v.customers) [c.node.name, c.minutes > 0 ? hm(c.minutes) : '', + [for (final e in (c.amounts.entries.toList()..sort((a, b) => a.key.compareTo(b.key)))) if (e.value != 0) money(e.value, e.key)].join(' · '), + c.rate]], w['customers'], reason: 'week $off customers'); + } + }, skip: skip); + + test('reports match the Pi', () { + final t = Tree(store); + for (final MapEntry(key: p, value: r) in (exp['reports'] as Map).entries) { + final (from, to) = presetRange(p, now)!; + final v = report(store, t, from, to); + String ams(Agg a) => [for (final e in (a.amounts.entries.toList()..sort((a, b) => a.key.compareTo(b.key)))) money(e.value, e.key)].join('|'); + expect(hm(v.total.m), r['total'], reason: '$p total'); + expect(hm(v.total.bm), r['billable'], reason: '$p billable'); + expect(ams(v.total), (r['amounts'] as List).join('|'), reason: '$p amounts'); + expect(v.items.length, r['n'], reason: '$p entries'); + expect([for (final x in v.rows) [x.node.name, x.depth, hm(x.agg.m), hm(x.agg.bm), ams(x.agg)]], + [for (final x in (r['rows'] as List).cast()) [x[0], x[1], x[2], x[3], (x[4] as List).join('|')]], reason: '$p rows'); + } + }, skip: skip); + + test('saving round-trips and validates', () { + final t = Tree(store); + final leaf = t.walk().last.$1; + final f = EntryForm(node: leaf.id, day: DateTime(2030, 1, 1), startMin: 23 * 60, endMin: 60, billable: true, note: ' x '); + final id = saveEntry(store, t, f); + final r = store.row(tEntry, id)!; + expect(r['start'], '2030-01-01 23:00'); + expect(r['end'], '2030-01-02 01:00'); // past midnight → the next day + expect(r['note'], 'x'); + expect(() => saveEntry(store, t, EntryForm(node: leaf.id, day: DateTime(2030, 1, 1), startMin: 60, endMin: 60, + endDay: DateTime(2030, 1, 1), billable: true)), throwsA(isA())); + deleteEntry(store, id); + expect(store.row(tEntry, id), isNull); + // a node with booked time can't be deleted; a fresh one can, with its rates + final top = t.walk().first.$1; + expect(deleteNode(store, t, top.id), isFalse); + final nid = saveNode(store, t, NodeForm(kind: 'task', parent: top.id, name: 'Test', rates: [('', '12,5'), ('2031-01-01', '15')])); + final t2 = Tree(store); + expect(t2.rate(nid, '2030-06-01').$1, 12.5); + expect(t2.rate(nid, '2031-02-01').$1, 15); + expect(store.row(tRate, '$nid:$epoch')!['rate'], 12.5); + expect(() => saveNode(store, t2, NodeForm(kind: 'project', parent: nid, name: 'Bad')), throwsA(isA())); + expect(deleteNode(store, t2, nid), isTrue); + expect(store.row(tRate, '$nid:2031-01-01'), isNull); + }, skip: skip); + + test('week numbers and blocks keep to the wall clock across summer time', () { + expect(isoWeek(DateTime.utc(2026, 10, 19)), 43); + expect(isoWeek(DateTime.utc(2026, 10, 26)), 44); // after the clocks went back on the 25th + expect(isoWeek(DateTime.utc(2026, 3, 30)), 14); // after they went forward on the 29th + expect(isoWeek(DateTime.utc(2026, 12, 28)), 53); + expect(isoWeek(DateTime.utc(2027, 1, 4)), 1); + final dir = Directory.systemTemp.createTempSync('dst'); + final st = SyncStore('${dir.path}/d.db', 'dst000000000'); + st.put(tNode, 'n', {'kind': 'client', 'parent_id': null, 'name': 'X', 'colour': '#ffb33a', 'billable': 1, 'currency': 'EUR', + 'notes': '', 'archived': 0, 'created': ''}); + st.put(tEntry, 'e', {'node_id': 'n', 'start': '2026-10-25 10:00', 'end': '2026-10-25 12:30', 'billable': 1, 'note': '', + 'created': '', 'updated': ''}); + final v = week(st, Tree(st), 0, DateTime(2026, 10, 21, 12)); + final b = v.days[6].blocks.single; + expect([b.a, b.b], [600, 750]); + expect(hm(v.minutes), '2:30'); + }); + + test('money and hours format like the Pi', () { + expect(money(1234567.5, 'EUR'), '1 234 567.50 EUR'); + expect(money(0, 'RON'), '0.00 RON'); + expect(hm(90), '1:30'); + expect(num0(20.0), '20'); + expect(num0(22.5), '22.5'); + }); +} diff --git a/app/test/work_timeline_test.dart b/app/test/work_timeline_test.dart new file mode 100644 index 0000000..d38b054 --- /dev/null +++ b/app/test/work_timeline_test.dart @@ -0,0 +1,144 @@ +// The Work timeline's gestures on a phone-sized screen: hold an empty spot and drag = a new span; a block's +// grips = an earlier start / later end (never under 15 minutes); hold the block = move it. Holds start after +// holdDelay (250 ms — Flutter's long press would need 500). The Undo messages time out by themselves. +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:dash_app/app/sync_service.dart'; +import 'package:dash_app/sync/client.dart'; +import 'package:dash_app/sync/store.dart'; +import 'package:dash_app/work/work_model.dart'; +import 'package:dash_app/work/work_page.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + testWidgets('span, resize, move', (tester) async { + tester.view.physicalSize = const Size(1200, 2700); // a 400 × 900 phone at 3× + tester.view.devicePixelRatio = 3; + addTearDown(tester.view.reset); + final dir = Directory.systemTemp.createTempSync('resize'); + final store = SyncStore('${dir.path}/d.db', 'test00000000'); + final node = SyncStore.randomId(), id = SyncStore.randomId(); + store.put(tNode, node, {'kind': 'client', 'name': 'Acme', 'created': '2026-10-01 00:00:00'}); + final now = DateTime.now(), d = DateTime.utc(now.year, now.month, now.day); + store.put(tEntry, id, {'node_id': node, 'start': fmtMin(d.add(const Duration(hours: 10))), + 'end': fmtMin(d.add(const Duration(hours: 11))), 'billable': 1, 'note': '', 'created': '2026-10-01 00:00:00'}); + final sync = SyncService(SyncSettings(server: 'http://x.invalid', token: 't', account: 'a', name: 'n', device: 'test00000000', + key: Uint8List(32)), store); + await tester.pumpWidget(MaterialApp(home: Scaffold(body: WorkPage(sync: sync)))); + await tester.pump(const Duration(milliseconds: 300)); + // hold an empty spot at 14:00 and drag down to 16:00 → the sheet opens with 14:00–16:00 + final two = tester.getTopLeft(find.text('14')); + var s = await tester.startGesture(Offset(two.dx + 200, two.dy + 7 + 10)); + await tester.pump(const Duration(milliseconds: 300)); + await s.moveBy(const Offset(0, 20)); + await tester.pump(); + await s.moveBy(const Offset(0, 2 * hourH - 30)); + await tester.pump(); + expect(find.textContaining('14:00–16:00'), findsOneWidget); + await s.up(); + await tester.pumpAndSettle(); + expect(find.text('14:00'), findsWidgets); + expect(find.text('16:00'), findsWidgets); + Navigator.of(tester.element(find.text('16:00').first)).pop(); + await tester.pumpAndSettle(); + + String end() => (store.row(tEntry, id)!['end'] as String).split(' ').last; + String start() => (store.row(tEntry, id)!['start'] as String).split(' ').last; + + Rect block() => tester.getRect(find.ancestor(of: find.textContaining(RegExp(r'\d\d:\d\d–\d\d:\d\d')), matching: find.byType(Stack)).first); + // bottom grip: hold 300 ms, drag down an hour → ends 12:00 + var g = await tester.startGesture(block().bottomCenter - const Offset(0, 5)); + await tester.pump(const Duration(milliseconds: 300)); + await g.moveBy(const Offset(0, 20)); + await tester.pump(); + await g.moveBy(const Offset(0, hourH - 20)); + await tester.pump(); + expect(find.textContaining('10:00–12:00'), findsOneWidget); + await g.up(); + await tester.pumpAndSettle(); + expect(end(), '12:00'); + await tester.pump(const Duration(seconds: 5)); // the Undo message times out + await tester.pumpAndSettle(); + expect(find.text('Undo'), findsNothing); + // top grip: drag up half an hour → starts 09:30 + g = await tester.startGesture(block().topCenter + const Offset(0, 5)); + await tester.pump(const Duration(milliseconds: 300)); + await g.moveBy(const Offset(0, -20)); + await tester.pump(); + await g.moveBy(const Offset(0, -hourH / 2 + 20)); + await tester.pump(); + await g.up(); + await tester.pumpAndSettle(); + expect(start(), '09:30'); + expect(end(), '12:00'); + await tester.pump(const Duration(seconds: 5)); + await tester.pumpAndSettle(); + // never shorter than 15 minutes: bottom grip dragged far up + g = await tester.startGesture(block().bottomCenter - const Offset(0, 5)); + await tester.pump(const Duration(milliseconds: 300)); + await g.moveBy(const Offset(0, -20)); + await tester.pump(); + await g.moveBy(const Offset(0, -5 * hourH)); + await tester.pump(); + await g.up(); + await tester.pumpAndSettle(); + expect(end(), '09:45'); + await tester.pump(const Duration(seconds: 5)); + await tester.pumpAndSettle(); + // the middle: a 300 ms hold moves it (Flutter's long press would need 500) + g = await tester.startGesture(block().center); + await tester.pump(const Duration(milliseconds: 300)); + await g.moveBy(const Offset(0, 20)); + await g.moveBy(const Offset(0, hourH - 20)); + await tester.pump(); + await g.up(); + await tester.pumpAndSettle(); + expect((start(), end()), ('10:30', '10:45')); + // a tap on the block opens it + await tester.tap(find.text('Acme · 10:30–10:45')); + await tester.pumpAndSettle(); + expect(find.text('10:30'), findsWidgets); + // drawing to the screen's bottom edge and holding there scrolls the day: the span reaches past what was showing + Navigator.of(tester.element(find.text('10:30').first)).pop(); + await tester.pumpAndSettle(); + await tester.pump(const Duration(seconds: 5)); + await tester.pumpAndSettle(); + final h14 = tester.getTopLeft(find.text('14')); + final bottom = tester.view.physicalSize.height / tester.view.devicePixelRatio; + final shown = (14 + (bottom - h14.dy) / hourH).floor(); // the last hour on screen when it starts + s = await tester.startGesture(Offset(h14.dx + 200, h14.dy + 7 + 10)); + await tester.pump(const Duration(milliseconds: 300)); + await s.moveTo(Offset(h14.dx + 200, bottom - 30)); + await tester.pump(); + for (var i = 0; i < 20; i++) { + await tester.pump(const Duration(milliseconds: 16)); + } + final label = tester.widgetList(find.textContaining(RegExp(r'^14:00–'))).first.data!; + final to = int.parse(label.substring(6, 8)); + expect(to, greaterThan(shown), reason: '$label, $shown:00 was the last hour showing'); + await s.up(); + await tester.pumpAndSettle(); + expect(find.text(label.substring(6, 11)), findsWidgets); // the sheet has that end + // a block held at the bottom edge rides along: it lands beyond the last hour that was showing + Navigator.of(tester.element(find.text(label.substring(6, 11)).first)).pop(); + await tester.pumpAndSettle(); + await tester.pump(const Duration(seconds: 5)); + await tester.pumpAndSettle(); + final blk = tester.getCenter(find.text('Acme · 10:30–10:45')); + final lastShown = (10.5 + (bottom - blk.dy) / hourH).floor(); + s = await tester.startGesture(blk); + await tester.pump(const Duration(milliseconds: 300)); + await s.moveTo(Offset(blk.dx, bottom - 30)); + await tester.pump(); + for (var i = 0; i < 20; i++) { + await tester.pump(const Duration(milliseconds: 16)); + } + await s.up(); + await tester.pumpAndSettle(); + expect(int.parse(start().substring(0, 2)), greaterThan(lastShown), reason: 'moved to ${start()}, $lastShown:00 was showing'); + expect(end(), isNot('10:45')); + sync.dispose(); + }); +} diff --git a/app/tool/publish.env.example b/app/tool/publish.env.example new file mode 100644 index 0000000..ddc1016 --- /dev/null +++ b/app/tool/publish.env.example @@ -0,0 +1,16 @@ +# Copy to tool/publish.env (not in git) and fill in. Read by tool/publish.sh. + +# where the APK goes: the sync server's app/ folder, over SSH +DASH_PUBLISH_HOST=you@your-server.example.com +DASH_PUBLISH_DIR=/srv/dash-sync/app + +# optional: the Flutter to build with (default: flutter on the PATH) +#FLUTTER=$HOME/flutter/bin/flutter + +# optional, built into the app (each can also be set in the app itself): +# the server the connect screen starts with +#DEV_SERVER=https://sync.example.com +# the dashboard on your home network, for "sync now" +#PI_URL=http://192.168.1.50:8080 +# weather places, home first: "Name|lat|lon;Name|lat|lon" +#HOME_PLACES=Hometown, XX|47.17|24.06;Big city, XX|46.77|23.60 diff --git a/app/tool/publish.sh b/app/tool/publish.sh new file mode 100755 index 0000000..70a7d73 --- /dev/null +++ b/app/tool/publish.sh @@ -0,0 +1,59 @@ +#!/usr/bin/env bash +# Publish the app: the next build number (pubspec.yaml), a signed release APK, then app.json + the APK to the +# sync server's app/ folder over SSH — every phone sees it at its next check (lib/app/updater.dart) and the +# primary dashboard mirrors it for the home network (http://:8080/app). +# tool/publish.sh [-m "what changed"] [--no-build] +# The update notes: -m, else this version's entry in CHANGELOG.md (its "## x.y.z" section) — refused without one. +# Your settings: tool/publish.env (not in git; copy tool/publish.env.example). +set -euo pipefail +cd "$(dirname "$0")/.." +[ -f tool/publish.env ] && . tool/publish.env +HOST="${DASH_PUBLISH_HOST:?set DASH_PUBLISH_HOST (user@server) in tool/publish.env}" +DIR="${DASH_PUBLISH_DIR:?set DASH_PUBLISH_DIR (the server's app/ folder) in tool/publish.env}" +FLUTTER="${FLUTTER:-flutter}" +DEFINES=() +for v in DEV_SERVER PI_URL HOME_PLACES; do # built into the app: see docs/app.md + [ -n "${!v:-}" ] && DEFINES+=("--dart-define=$v=${!v}") +done +NOTES=""; BUILD=1 +while [ $# -gt 0 ]; do + case "$1" in + -m) NOTES="$2"; shift 2 ;; + --no-build) BUILD=0; shift ;; + *) echo "usage: tool/publish.sh [-m notes] [--no-build]"; exit 2 ;; + esac +done +[ -f android/key.properties ] || { echo "android/key.properties is missing: a debug-signed APK can't update the installed app."; exit 1; } + +# the next build number: above both this checkout's and the server's +ver=$(sed -n 's/^version: *//p' pubspec.yaml); name=${ver%%+*}; mine=${ver##*+} +# the notes: this version's CHANGELOG.md entry (checked before the build, so a missing one costs nothing) +[ -n "$NOTES" ] || NOTES=$(awk -v v="$name" '/^## /{on = ($2 == v); next} on' CHANGELOG.md | sed -e '/./,$!d' | sed -e ':a' -e '/^\n*$/{$d;N;ba' -e '}') +[ -n "$NOTES" ] || { echo "no \"## $name\" entry in CHANGELOG.md — write one (or pass -m)"; exit 1; } +theirs=$(ssh -o BatchMode=yes "$HOST" "cat $DIR/app.json 2>/dev/null || true" | python3 -c "import json,sys +try: print(json.load(sys.stdin)['build']) +except Exception: print(0)") +if [ "$BUILD" = 1 ]; then + next=$(( (mine > theirs ? mine : theirs) + 1 )) + sed -i "s/^version: .*/version: $name+$next/" pubspec.yaml + echo "── building $name ($next) ──" + "$FLUTTER" build apk --release "${DEFINES[@]}" +else + next=$mine + [ "$next" -gt "$theirs" ] || { echo "build $next isn't newer than the server's $theirs"; exit 1; } +fi +APK=build/app/outputs/flutter-apk/app-release.apk +[ -f "$APK" ] || { echo "no $APK"; exit 1; } +size=$(stat -c %s "$APK"); sha=$(sha256sum "$APK" | cut -d' ' -f1) +tmp=$(mktemp); trap 'rm -f "$tmp"' EXIT +NAME="$name" NEXT="$next" SIZE="$size" SHA="$sha" NOTES="$NOTES" python3 -c "import json,os,datetime +print(json.dumps({'version': os.environ['NAME'], 'build': int(os.environ['NEXT']), 'size': int(os.environ['SIZE']), + 'sha256': os.environ['SHA'], 'published': datetime.datetime.now(datetime.timezone.utc).isoformat(timespec='seconds'), + 'notes': os.environ['NOTES']}))" > "$tmp" +echo "── uploading $name ($next), $((size / 1000000)) MB ──" +ssh -o BatchMode=yes "$HOST" "mkdir -p $DIR && chmod 755 $DIR" +# the APK first, under a temporary name; then both renamed in one go (a phone never sees a half-written pair) +rsync -t --chmod=F644 "$APK" "$HOST:$DIR/dash-app.apk.new" +rsync -t --chmod=F644 "$tmp" "$HOST:$DIR/app.json.new" +ssh -o BatchMode=yes "$HOST" "cd $DIR && mv dash-app.apk.new dash-app.apk && mv app.json.new app.json" +echo "published $name ($next) — phones pick it up at their next check (Sync page ▸ App)" diff --git a/dashboard/.gitignore b/dashboard/.gitignore new file mode 100644 index 0000000..8f7f191 --- /dev/null +++ b/dashboard/.gitignore @@ -0,0 +1,22 @@ +# per-host state + secrets (the Pi's real ones live only on the Pi) +dash_config.json +dash_calib.json +dash_history.json +dash_weather.json +dash_local.ics +dash_local.ics.imported +dash_cal_errors.json +dash_data/ +dash_data.before-restore-*/ +*.before-restore-* +restore.zip* +*.upload +# local +__pycache__/ +*.pyc +*.bak +.claude/ + +# Syncthing, if you sync the source between computers +.stignore +.stfolder diff --git a/dashboard/README.md b/dashboard/README.md new file mode 100644 index 0000000..7f24392 --- /dev/null +++ b/dashboard/README.md @@ -0,0 +1,86 @@ +# The dashboard + +One Python process. It draws the 3.5" touch screen of a Raspberry Pi straight to the framebuffer (no +desktop needed) and serves the same data as web pages for a TV, a laptop or a phone. Everything past the +clock is a plugin, and everything is set up in the browser (Settings). + +![Home](../docs/screenshots/home.png) + +## Install + +On Raspberry Pi OS or Debian 12 / 13: + +```bash +git clone https://git.hackman.club/HackmanClub/dashboard.git dashpi && cd dashpi +sudo ./dashboard/install.sh # a Pi with the 3.5" screen (found by itself; else web pages only) +sudo ./dashboard/install.sh --headless # any other computer: web pages only +``` + +It installs the Debian packages and copies this folder to `/opt/dashboard`. It also writes +`dash_config.json` from the example, gives you the bundled food database, and starts the `dashboard` +service. Then: + +1. Open `http://:8080/settings`. +2. Create the admin account. It asks for the setup code from the log: + `journalctl -u dashboard | grep 'setup code'`. +3. Set up the rest in Settings: weather place, calendars, sensors, plugins, users, sync. + +To update, `git pull` and run `install.sh` again. Your `dash_config.json` and `dash_data/` are never +touched. The whole guide (the screen's overlay, the sensors, backups, moving to a new machine) is in +[../docs/dashboard.md](../docs/dashboard.md). + +**Try it without installing** (any Linux with Python 3.11+): + +```bash +pip install -r requirements.txt # or the python3-* packages listed in it +cp dash_config.example.json dash_config.json +python3 dash.py --headless # → http://localhost:8080/ +``` + +Or see it with demo data: `python3 ../docs/screenshots/make.py --keep` (log in as `demo` / +`demo-password-1`). + +## What's in it + +| Plugin | What it does | Its data | +|---|---|---| +| `weather` (built in) | Open-Meteo for your place + up to 6 more: Home, the weather page, the 3.5" screen; the places sync to the app | `dash_data/weather/` | +| `calendar` (built in) | ICS feeds, Nextcloud / CalDAV, the dashboard's own Local calendar; week and month pages, Home's day view, the 3.5" agenda | `dash_data/calendar/local.db` | +| `stations` (built in) | Room sensors from Home Assistant, MQTT, a JSON URL, a DS18B20 or termix; graphs from 24 hours to a year | `dash_data/stations/readings.db` | +| `health` | Body measurements; sleep, heart rate, steps and workouts from a band (Gadgetbridge export or the app's relay, Mi Fitness export) | `dash_data/health/` | +| `food` | A food diary from the bundled food database (USDA + shop products), targets, nutrients | `dash_data/food/` | +| `cycle` | Period tracking: cycle and period lengths, the next periods, optionally the fertile window | `dash_data/cycle/` | +| `workload` | Time per customer / project / task, booked like calendar events; billable, rates, a report | `dash_data/workload/` | +| `activity` | What you did on your computers, from ActivityWatch, sorted into categories by rules | `dash_data/activity/` | +| `notes` | Markdown notes with folders, tags, checklists, search; synced with the app | `dash_data/notes/` | + +The 3.5" screen shows Home, the sensors, the weather and the calendar: + +![Home](../docs/screenshots/screen-home.png) ![Sensors](../docs/screenshots/screen-temp.png) +![Weather](../docs/screenshots/screen-weather.png) ![Calendar](../docs/screenshots/screen-cal.png) + +## Files + +``` +dash.py the main loop: the screen, touch, the workers; starts web.py +web.py the web pages and their API (Flask) +pluginhost.py what a plugin can do (ctx) — read this before writing one +screens.py the 3.5" Home + Settings screens; panel.py draws, touch.py reads the touch screen +settings.py Settings ▸ General / Calendar / Weather (the form) → dash_config.json +system.py web address, screen, backup / restore +auth.py users, logins, the household view +sync.py, syncdb.py the end-to-end encrypted sync (server/PROTOCOL.md) +store.py, config.py the shared state; paths, fonts, the theme +plugins// one folder per plugin: __init__.py (META + register), templates/, static/, its db code +install.sh install / update on Debian; dashboard.service is its template +``` + +How it fits together: [../docs/architecture.md](../docs/architecture.md). Writing a plugin: the +docstring at the top of [pluginhost.py](pluginhost.py) and any plugin in `plugins/` as an example. + +## Configuration + +Everything is in Settings and saved in `dash_config.json` (mode 600, it holds passwords). The data is in +`dash_data/`. Settings ▸ General ▸ Backup downloads both as one file and restores them. Some knobs exist only +for the command-line tools: `FOOD_COUNTRIES` for `plugins/food/off.py`, `DASH_TZ` for +`plugins/health/mi.py`. diff --git a/dashboard/auth.py b/dashboard/auth.py new file mode 100644 index 0000000..44a00da --- /dev/null +++ b/dashboard/auth.py @@ -0,0 +1,369 @@ +"""Who's looking: users, sessions, the household view (dash_data/auth/users.db, chmod 600). + +Three kinds of viewer: + admin everything (the Settings page, every plugin, every calendar), as before users + member a login with its own set: which plugins (`plugins`), which calendars + (`calendars`, by name), and whether they may add events (`can_create`) + household nobody logged in: a read-only view (no writes at all) — set up in Settings ▸ + Users like a member. The 3.5" screen and every request without a login get it. + +Until the first admin account exists (`active()` False) everyone is admin — deploying this +locks nobody out; Settings ▸ Users then offers to create the account. + +Sessions: a random token in the `dash_session` cookie (HttpOnly, SameSite=Lax, a year), +only its SHA-256 kept here — log out / delete the user / change the password drops it. +Passwords: werkzeug's PBKDF2. Wrong passwords: LOCK_AFTER per address in LOCK_FOR seconds, +then that address waits. + +Plugins never import this — pluginhost asks `allows(name)`, the calendar plugin +`calendar_ok(name)` / `can_create()`. +Forgot the password: `python3 auth.py password ` on the Pi (stop nothing; it asks). +""" +import hashlib +import json +import os +import secrets +import sqlite3 +import threading +import time +from contextlib import closing, contextmanager + +from flask import g, has_request_context, request + +from config import HERE + +PATH = os.path.join(HERE, "dash_data", "auth", "users.db") +COOKIE = "dash_session" +SESSION_DAYS = 365 +LOCK_AFTER, LOCK_FOR = 5, 600 +HASH = "pbkdf2:sha256:200000" # ≈ 0.5 s on the Pi 3 +HOUSEHOLD_DEFAULT = {"plugins": ["weather", "stations", "calendar"], "calendars": []} # no calendar until chosen +SCHEMA = """ +CREATE TABLE IF NOT EXISTS user ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL UNIQUE COLLATE NOCASE, + pw TEXT NOT NULL, + role TEXT NOT NULL DEFAULT 'member', -- admin / member + plugins TEXT, -- JSON list of plugin names (members) + calendars TEXT, -- JSON list of calendar names, NULL = all + can_create INTEGER NOT NULL DEFAULT 0, + created INTEGER +); +CREATE TABLE IF NOT EXISTS session ( + token TEXT PRIMARY KEY, -- SHA-256 of the cookie's token + user_id INTEGER NOT NULL, + created INTEGER, seen INTEGER, agent TEXT +); +CREATE TABLE IF NOT EXISTS household ( + id INTEGER PRIMARY KEY CHECK (id = 1), + plugins TEXT, calendars TEXT +); +""" +ADMIN = {"kind": "admin", "name": None, "id": None, "plugins": None, "calendars": None, "can_create": True} +_lock = threading.Lock() +_fails = {} # address -> [times of wrong passwords] +_cache = {"v": None, "active": None, "household": None} +_setup = {"code": None} +SEEN_EVERY = 60 # s: a session's "seen" is written at most this often (SD card) + + +def _db(): + os.makedirs(os.path.dirname(PATH), exist_ok=True) + con = sqlite3.connect(PATH, timeout=10) + con.row_factory = sqlite3.Row + con.executescript(SCHEMA) + os.chmod(PATH, 0o600) + return con + + +def _version(): + try: + st = os.stat(PATH) + return st.st_mtime_ns, st.st_size + except OSError: + return None + + +def _refresh(): + """active() / household() read once per change of the file, not per request.""" + v = _version() + if v != _cache["v"] or v is None: + with closing(_db()) as con: + n = con.execute("SELECT COUNT(*) FROM user WHERE role = 'admin'").fetchone()[0] + h = con.execute("SELECT plugins, calendars FROM household WHERE id = 1").fetchone() + _cache.update(v=_version(), active=n > 0, + household=dict(HOUSEHOLD_DEFAULT, **({"plugins": json.loads(h["plugins"] or "[]"), + "calendars": _loads(h["calendars"])} if h else {}))) + + +def _loads(s): + return json.loads(s) if s else None + + +def active(): + """True once an admin account exists (before that: everyone is admin).""" + _refresh() + return _cache["active"] + + +def household(): + _refresh() + return dict(_cache["household"], kind="household", name=None, id=None, can_create=False) + + +def _user_profile(r): + if r["role"] == "admin": + return dict(ADMIN, name=r["name"], id=r["id"]) + return {"kind": "member", "name": r["name"], "id": r["id"], "plugins": json.loads(r["plugins"] or "[]"), + "calendars": _loads(r["calendars"]), "can_create": bool(r["can_create"])} + + +def from_request(): + """The viewer of this request (web.py's before_request puts it in g.viewer).""" + if not active() or request.environ.get("dash.internal"): # no accounts yet / the warmers + return ADMIN + tok = request.cookies.get(COOKIE) + if tok: + h = hashlib.sha256(tok.encode()).hexdigest() + with closing(_db()) as con: + r = con.execute("SELECT u.* FROM session s JOIN user u ON u.id = s.user_id WHERE s.token = ?", + (h,)).fetchone() + if r: + now = int(time.time()) + if now - (con.execute("SELECT seen FROM session WHERE token = ?", (h,)).fetchone()[0] or 0) > SEEN_EVERY: + con.execute("UPDATE session SET seen = ? WHERE token = ?", (now, h)) + con.commit() + return _user_profile(r) + return household() + + +_owner = threading.local() + + +@contextmanager +def as_owner(): + """Outside a request, answer as the admin for a while — work done for the account's owner + (the phone app's Work week: every calendar, not the household's).""" + _owner.on = True + try: + yield + finally: + _owner.on = False + + +def viewer(): + """In a request: who's looking; elsewhere (the 3.5" screen): the household — or the admin + inside as_owner().""" + if not has_request_context() and getattr(_owner, "on", False): + return ADMIN + if has_request_context(): + v = g.get("viewer") + if v is None: + v = g.viewer = from_request() + return v + return household() if active() else ADMIN + + +def is_admin(): + return viewer()["kind"] == "admin" + + +def read_only(): + return viewer()["kind"] == "household" + + +def allows(plugin): + """May the viewer see this plugin (its pages, nav button, Home parts, 3.5" screens)?""" + v = viewer() + return v["plugins"] is None or plugin in v["plugins"] + + +def calendar_ok(name): + v = viewer() + return v["calendars"] is None or name in v["calendars"] + + +def can_create(): + return bool(viewer()["can_create"]) + + +def cache_key(): + """For cached pages: who they were built for.""" + v = viewer() + return v["kind"], v["id"] + + +# ---- the first account ---------------------------------------------------------------- + +def setup_code(): + """Until the admin exists: a code from the dashboard's log that creating it needs — so the first + person on the network (or a web page) can't make themselves the admin.""" + if not _setup["code"]: + _setup["code"] = "-".join(secrets.token_hex(2) for _ in range(3)) + return _setup["code"] + + +def setup_ok(code, addr): + if addr in ("127.0.0.1", "::1"): # on the machine itself + return True + return bool(code) and secrets.compare_digest(str(code).strip().lower(), setup_code()) + + +# ---- logging in --------------------------------------------------------------------- + +def locked(addr): + now = time.time() + with _lock: + ts = [t for t in _fails.get(addr, []) if now - t < LOCK_FOR] + _fails[addr] = ts + return len(ts) >= LOCK_AFTER + + +def login(name, password, addr, agent=""): + """A new session token for a right name + password, else None (and the miss counted).""" + from werkzeug.security import check_password_hash + with closing(_db()) as con: + r = con.execute("SELECT id, pw FROM user WHERE name = ?", ((name or "").strip(),)).fetchone() + if not r: # the same time as a wrong password: names stay unknown + check_password_hash(_dummy(), password or "") + elif check_password_hash(r["pw"], password or ""): + tok = secrets.token_urlsafe(32) + now = int(time.time()) + con.execute("INSERT INTO session VALUES (?, ?, ?, ?, ?)", + (hashlib.sha256(tok.encode()).hexdigest(), r["id"], now, now, (agent or "")[:200])) + con.execute("DELETE FROM session WHERE seen < ?", (now - SESSION_DAYS * 86400,)) + con.commit() + with _lock: + _fails.pop(addr, None) + return tok + with _lock: + _fails.setdefault(addr, []).append(time.time()) + return None + + +def _dummy(): + from werkzeug.security import generate_password_hash + if not _setup.get("dummy"): + _setup["dummy"] = generate_password_hash(secrets.token_hex(8), HASH) + return _setup["dummy"] + + +def logout(token): + if token: + with closing(_db()) as con: + con.execute("DELETE FROM session WHERE token = ?", (hashlib.sha256(token.encode()).hexdigest(),)) + con.commit() + + +# ---- the admin console (Settings ▸ Users) ---------------------------------------------- + +def users(): + with closing(_db()) as con: + rows = con.execute("SELECT u.*, (SELECT MAX(seen) FROM session s WHERE s.user_id = u.id) AS seen, " + "(SELECT COUNT(*) FROM session s WHERE s.user_id = u.id) AS sessions " + "FROM user u ORDER BY role, name COLLATE NOCASE").fetchall() + return [dict(_user_profile(r), role=r["role"], seen=r["seen"], sessions=r["sessions"]) for r in rows] + + +def _clean_list(xs, allowed=None): + out = [] + for x in xs or []: + x = str(x).strip()[:120] + if x and x not in out and (allowed is None or x in allowed): + out.append(x) + return out + + +def save_user(d, plugin_names, me_id=None, keep_token=None): + """Add (no id) or change a user from the console's JSON. Returns (id, error). A new + password logs that user out everywhere — except the session `keep_token` (yours).""" + from werkzeug.security import generate_password_hash + name = " ".join(str(d.get("name") or "").split())[:40] + role = "admin" if d.get("role") == "admin" else "member" + pw = str(d.get("password") or "") + uid = d.get("id") + if not name: + return None, "Give it a name." + if pw and len(pw) < 8: + return None, "Passwords need at least 8 characters." + if not uid and not pw: + return None, "A new user needs a password." + plugins = json.dumps(_clean_list(d.get("plugins"), plugin_names)) + cals = d.get("calendars") + cals = None if cals is None else json.dumps(_clean_list(cals)) + with closing(_db()) as con: + if uid: + old = con.execute("SELECT role FROM user WHERE id = ?", (uid,)).fetchone() + if not old: + return None, "That user is gone." + if old["role"] == "admin" and role != "admin" and _admins(con) <= 1: + return None, "Keep at least one admin." + if uid == me_id and role != "admin": + return None, "You can't take admin away from yourself." + try: + if uid: + con.execute("UPDATE user SET name = ?, role = ?, plugins = ?, calendars = ?, can_create = ? WHERE id = ?", + (name, role, plugins, cals, int(bool(d.get("can_create"))), uid)) + if pw: + con.execute("UPDATE user SET pw = ? WHERE id = ?", (generate_password_hash(pw, HASH), uid)) + keep = hashlib.sha256(keep_token.encode()).hexdigest() if keep_token else "" + con.execute("DELETE FROM session WHERE user_id = ? AND token != ?", (uid, keep)) + else: + uid = con.execute("INSERT INTO user (name, pw, role, plugins, calendars, can_create, created) " + "VALUES (?, ?, ?, ?, ?, ?, ?)", + (name, generate_password_hash(pw, HASH), role, plugins, cals, + int(bool(d.get("can_create"))), int(time.time()))).lastrowid + except sqlite3.IntegrityError: + return None, f"There's already a user called {name}." + con.commit() + return uid, None + + +def _admins(con): + return con.execute("SELECT COUNT(*) FROM user WHERE role = 'admin'").fetchone()[0] + + +def delete_user(uid, me_id=None): + with closing(_db()) as con: + r = con.execute("SELECT role FROM user WHERE id = ?", (uid,)).fetchone() + if not r: + return "That user is gone." + if uid == me_id: + return "You can't delete yourself." + if r["role"] == "admin" and _admins(con) <= 1: + return "Keep at least one admin." + con.execute("DELETE FROM session WHERE user_id = ?", (uid,)) + con.execute("DELETE FROM user WHERE id = ?", (uid,)) + con.commit() + return None + + +def logout_everywhere(uid): + with closing(_db()) as con: + con.execute("DELETE FROM session WHERE user_id = ?", (uid,)) + con.commit() + + +def save_household(d, plugin_names): + cals = d.get("calendars") + with closing(_db()) as con: + con.execute("INSERT OR REPLACE INTO household VALUES (1, ?, ?)", + (json.dumps(_clean_list(d.get("plugins"), plugin_names)), + None if cals is None else json.dumps(_clean_list(cals)))) + con.commit() + + +if __name__ == "__main__": # python3 auth.py password + import getpass + import sys + if len(sys.argv) != 3 or sys.argv[1] != "password": + sys.exit("usage: python3 auth.py password ") + with closing(_db()) as con: + r = con.execute("SELECT * FROM user WHERE name = ?", (sys.argv[2],)).fetchone() + if not r: + sys.exit(f"no user {sys.argv[2]!r}") + p = getpass.getpass("New password: ") + _, err = save_user(dict(_user_profile(r), role=r["role"], password=p, + calendars=_loads(r["calendars"]), plugins=json.loads(r["plugins"] or "[]")), + None, me_id=r["id"]) + sys.exit(err or "Changed; that user is logged out everywhere.") diff --git a/dashboard/backlight.py b/dashboard/backlight.py new file mode 100644 index 0000000..47ba19f --- /dev/null +++ b/dashboard/backlight.py @@ -0,0 +1,53 @@ +"""Auto brightness via render-side multiplier. + +The hardware backlight on this panel is hardwired full-on. We dim by +multiplying RGB values in software before writing to the framebuffer. + +Brightness follows the sun (sunrise/sunset from the weather plugin — Open-Meteo — so this +falls back to MID until it has fetched once; with the weather plugin off, fixed 07:00 / +19:00): + + Morning 1h before sunrise (LOW) → sunrise (MID) → 1h after (HIGH) + Day HIGH + Evening 1h before sunset (HIGH) → sunset (MID) → 1h after (LOW) + Night LOW +""" +from datetime import datetime, timedelta + +LOW, MID, HIGH = 0.25, 0.55, 1.0 +HOUR = timedelta(hours=1) + + +def compute(store): + """Multiplier 0..1 for the next frame, from cached sunrise/sunset.""" + sr, ss = sun_times(store) + return _from_sun(datetime.now(), sr, ss) + + +FIXED = (7, 19) # without the weather plugin: "sunrise" 07:00, "sunset" 19:00 + + +def sun_times(store): + """Today's (sunrise, sunset): the weather plugin's (pluginhost.ask "sun"), (None, None) + until it has fetched once, fixed hours (FIXED) when it's off.""" + import pluginhost + if not pluginhost.enabled(store, "weather"): + today = datetime.now().replace(minute=0, second=0, microsecond=0) + return today.replace(hour=FIXED[0]), today.replace(hour=FIXED[1]) + return pluginhost.ask(store, "weather", "sun") or (None, None) + + +def _from_sun(now, sunrise, sunset): + if sunrise is None or sunset is None: + return MID # safe default + if sunrise - HOUR <= now < sunrise: # dawn: LOW -> MID + return LOW + (MID - LOW) * ((now - (sunrise - HOUR)) / HOUR) + if sunrise <= now < sunrise + HOUR: # post: MID -> HIGH + return MID + (HIGH - MID) * ((now - sunrise) / HOUR) + if sunset - HOUR <= now < sunset: # dusk: HIGH -> MID + return HIGH - (HIGH - MID) * ((now - (sunset - HOUR)) / HOUR) + if sunset <= now < sunset + HOUR: # post: MID -> LOW + return MID - (MID - LOW) * ((now - sunset) / HOUR) + if sunrise + HOUR <= now < sunset - HOUR: + return HIGH # daytime + return LOW # deep night diff --git a/dashboard/config.py b/dashboard/config.py new file mode 100644 index 0000000..147eba8 --- /dev/null +++ b/dashboard/config.py @@ -0,0 +1,73 @@ +"""Paths, defaults, and visual theme. + +Everything that's a constant or a setting lives here. Other modules import +from this file rather than holding their own copies. +""" +import json +import os + +# ---- paths ---------------------------------------------------------------- +FB_DEV = "/dev/fb0" # the default when Settings ▸ General says so; see panel.find_screen +HERE = os.path.dirname(os.path.abspath(__file__)) +CONFIG_PATH = os.path.join(HERE, "dash_config.json") +CALIB_FILE = os.path.join(HERE, "dash_calib.json") +HISTORY_FILE = os.path.join(HERE, "dash_history.json") +WEATHER_CACHE = os.path.join(HERE, "dash_weather.json") # last good weather (survives restarts) +CAL_ERRORS = os.path.join(HERE, "dash_cal_errors.json") # calendars currently failing (Settings shows them) +LOCAL_FILE = os.path.join(HERE, "dash_local.ics") # the "Local" calendar (web create event) +FONT_DIRS = ("/usr/share/fonts/truetype/dejavu", # Debian, Raspberry Pi OS, Ubuntu (fonts-dejavu-core) + "/usr/share/fonts/dejavu-sans-fonts", # Fedora + "/usr/share/fonts/TTF", # Arch + "/usr/share/fonts/dejavu") # openSUSE, Alpine +FONT_DIR = next((d for d in FONT_DIRS if os.path.exists(os.path.join(d, "DejaVuSans.ttf"))), FONT_DIRS[0]) + +DEFAULT_CONFIG = { + "owm_api_key": "", "location_name": "—", "lat": 0.0, "lon": 0.0, + "units": "metric", + "termix": { # remote sensor source; see sensors.py + "url": "", # e.g. "https://termix.example.com/api/stm32.php" + "api_key": "", + "device_ids": [], # ordered; the first is shown on Home + }, + "calendar": {"enabled": False, "caldav_url": "", "username": "", + "app_password": "", "calendar_name": "", + "show_anniversaries": False, "show_death_dates": False}, + "web": {"enabled": False, "host": "0.0.0.0", "port": 8080}, # web.py +} + +# ---- theme: one dark bg everywhere, a single coloured line on top ---------- +THEME = { + "bg": "#0d1017", "topline": "#ffb33a", "fg": "#e8eaed", "muted": "#8b929e", + "dim": "#5a616e", "accent": "#ffb33a", "warm": "#ff9d5c", "cool": "#5cc8ff", + "highlight": "#ffb33a", "ink": "#0d1017", "card": "#161a23", "graph": "#ffb33a", + "good": "#7fd6a3", # light green (e.g. "Nextcloud ok") + "bday": "#ff6b7a", # birthdays, only if Nextcloud gives the calendar no colour + # Home indoor temperature bands (panel.temp_colour): <20 / 20-23 / 23-26 (accent) + # / 26-29 (warm) / 29+ + "t_cold": "#6e9cff", "t_ok": "#7fd6a3", "t_hot": "#ff5f5f", + "allday": "#7fd6a3", # calendar glyph for today's all-day events on Home +} +TOP_H = 4 +NAV_H = 60 + + +def load_config(): + cfg = json.loads(json.dumps(DEFAULT_CONFIG)) # deep copy + try: + with open(CONFIG_PATH) as f: + mine = json.load(f) + except FileNotFoundError: + mine = {} + for k, v in mine.items(): # a section given in part keeps the other defaults + cfg[k] = {**cfg[k], **v} if isinstance(v, dict) and isinstance(cfg.get(k), dict) else v + return cfg + + +def save_config(cfg): + """Atomic write, owner-only (the file holds the API keys and the Nextcloud password).""" + tmp = CONFIG_PATH + ".tmp" + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w") as f: + json.dump(cfg, f, indent=2, ensure_ascii=False) + os.chmod(tmp, 0o600) + os.replace(tmp, CONFIG_PATH) diff --git a/dashboard/dash.py b/dashboard/dash.py new file mode 100644 index 0000000..b790606 --- /dev/null +++ b/dashboard/dash.py @@ -0,0 +1,179 @@ +#!/usr/bin/env python3 +""" +Framebuffer dashboard for a 3.5" ILI9486 SPI panel (/dev/fb0, 480x320, RGB565). + +Screens, shown as icon buttons along the bottom and switched with number keys (1 = Home, +then the plugins' screens — Temp, Weather, Calendar … —, the last = Settings; screens.py). +Left/Right arrows act *within* a screen (the plugin's key(): the next sensor, the next +calendar page …; Settings: Celsius / Fahrenheit). q quits. + +Run: python3 dash.py (first run / after a flip: python3 dash.py --calibrate) + +Layout (split for readability — all sibling modules in this folder): + config.py paths, THEME, load/save config + store.py Store + TempSource + hit/dispatch_tap (tap-region registry) + panel.py framebuffer, fonts, text/draw helpers, nav bar, graph + touch.py evdev touch device, calibration, raw->screen mapping + backlight.py auto brightness from sunrise/sunset (render-side dim) + screens.py Home + Settings, the screen list, render() + pluginhost.py the plugins (plugins//) — weather, calendar, the measurement + stations are plugins too (their workers, screens, Home parts) + web.py the web pages (Flask, templates/ + static/, webview.py) — the big-screen layout + dash.py this file: main loop, key + touch event dispatch +""" + +import json +import os +import select +import signal +import sys +import termios +import threading +import time +import tty + +import backlight +import pluginhost +from config import CALIB_FILE, load_config +from panel import Panel +from screens import render, screen_list +from store import Store, dispatch_tap, goto_screen +from touch import (HAVE_EVDEV, calibrate, ecodes, find_touch_device, + raw_to_screen) + +IDLE_TIMEOUT_S = 10 * 60 # auto-return to Home after this much idle; see main loop + + +def read_key(): + ch = sys.stdin.read(1) + if ch == "\x1b": # escape seq (arrow keys) + r, _, _ = select.select([sys.stdin], [], [], 0.01) + if r: + ch += sys.stdin.read(2) + return ch + + +def handle_key(ch, store): + store.last_activity_t = time.monotonic() + screens = screen_list(store) + if ch.isdigit() and 1 <= int(ch) <= len(screens): + goto_screen(store, int(ch) - 1, screens) + elif ch in ("\x1b[C", "\x1b[D"): # right / left: the screen's own + sc = screens[min(store.screen, len(screens) - 1)] + if sc.get("units"): + store.toggle_units() + elif sc.get("key"): + sc["key"]("right" if ch == "\x1b[C" else "left") + elif ch in ("q", "Q"): + return False + return True + + +def main(): + import system + system.apply_pending() # Settings ▸ General ▸ Restore: before anything opens a database + cfg = load_config() + from panel import find_screen + screen = None if "--headless" in sys.argv else find_screen(cfg) + headless = screen is None # no small screen (another computer): workers + web pages only + panel = None if headless else Panel(screen) + if panel: + print(f"screen: {screen} ({panel.w}×{panel.h}, {panel.bpp} bpp)", flush=True) + store = Store(cfg) + store.headless = headless + pluginhost.load(store) # every plugin (weather, calendar, stations …): their workers start here + if (cfg.get("web") or {}).get("enabled"): # the web pages (web.py) + from web import web_worker + threading.Thread(target=web_worker, args=(store,), daemon=True).start() + if headless: + signal.signal(signal.SIGTERM, lambda *_: sys.exit(0)) # systemd stop → the finally below + print("headless: no small screen (Settings ▸ General ▸ Screen) — web pages and workers only", flush=True) + try: + while True: + time.sleep(3600) + except (KeyboardInterrupt, SystemExit): + pass + finally: + pluginhost.shutdown() + return + + # optional touch (tap-to-select); keyboard always works regardless + touch, calib = None, None + if HAVE_EVDEV: + try: + touch = find_touch_device() + except Exception as e: + print("touch disabled:", e) + else: + print("touch disabled: python3-evdev not installed (keyboard still works).") + if touch is not None: + if "--calibrate" in sys.argv or not os.path.exists(CALIB_FILE): + calib = calibrate(panel, touch) + else: + try: + with open(CALIB_FILE) as f: + calib = json.load(f) + except Exception: + calib = calibrate(panel, touch) + + kbd = sys.stdin.isatty() # no terminal (e.g. systemd) -> display + touch only + fd = sys.stdin.fileno() if kbd else None + old = termios.tcgetattr(fd) if kbd else None + if not kbd: + print("No TTY — keyboard disabled; running display + touch only.") + + next_draw = 0.0 + pressed, tcx, tcy, psx, psy = False, None, None, 0.0, 0.0 + try: + if kbd: + tty.setcbreak(fd) + while True: + watch = ([sys.stdin] if kbd else []) + ([touch.fd] if touch else []) + r, _, _ = select.select(watch, [], [], 0.5) + if kbd and sys.stdin in r and not handle_key(read_key(), store): + break + if touch and touch.fd in r: + for ev in touch.read(): + if ev.type == ecodes.EV_ABS: + if ev.code == ecodes.ABS_X: + tcx = ev.value + elif ev.code == ecodes.ABS_Y: + tcy = ev.value + elif ev.type == ecodes.EV_KEY and ev.code == ecodes.BTN_TOUCH: + if ev.value == 1 and tcx is not None: + pressed = True + psx, psy = raw_to_screen(calib, tcx, tcy) + elif ev.value == 0 and pressed: + pressed = False + rx, ry = raw_to_screen(calib, tcx, tcy) + if abs(rx - psx) < 25 and abs(ry - psy) < 25: # tap, not a drag + dispatch_tap(store, rx, ry) + store.last_activity_t = time.monotonic() + next_draw = 0.0 + now = time.monotonic() + + # Idle return-to-Home: after N minutes with no touch/key, jump back + # to Home unless the screen asks to stay (Home itself, the Temp grid — + # left open as a passive display: the screen's stay()). + if now - store.last_activity_t > IDLE_TIMEOUT_S: + screens = screen_list(store) + sc = screens[min(store.screen, len(screens) - 1)] + if not (sc.get("stay") and sc["stay"]()): + goto_screen(store, 0, screens) + next_draw = 0.0 + + if r or now >= next_draw: + store.brightness = backlight.compute(store) + panel.blit(render(panel, store), store.brightness) + next_draw = now + 1.0 + except KeyboardInterrupt: + pass + finally: + pluginhost.shutdown() # the plugins save what's in memory (the 24 h history …) + if kbd: + termios.tcsetattr(fd, termios.TCSADRAIN, old) + panel.clear() + + +if __name__ == "__main__": + main() diff --git a/dashboard/dash_config.example.json b/dashboard/dash_config.example.json new file mode 100644 index 0000000..89e0f27 --- /dev/null +++ b/dashboard/dash_config.example.json @@ -0,0 +1,26 @@ +{ + "location_name": "Your town", + "lat": 0.0, + "lon": 0.0, + "units": "metric", + "web": { + "enabled": true, + "host": "0.0.0.0", + "port": 8080, + "hosts": [] + }, + "calendar": { + "enabled": false, + "caldav_url": "", + "username": "", + "app_password": "" + }, + "termix": { + "url": "", + "api_key": "", + "device_ids": [] + }, + "sync": { + "primary": true + } +} diff --git a/dashboard/dashboard.service b/dashboard/dashboard.service new file mode 100644 index 0000000..a9eba2b --- /dev/null +++ b/dashboard/dashboard.service @@ -0,0 +1,22 @@ +# Template: install.sh fills in @USER@, @DIR@ and @ARGS@ and writes /etc/systemd/system/dashboard.service. +[Unit] +Description=dashPi dashboard (3.5" screen + web pages) +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=@USER@ +SupplementaryGroups=video input +WorkingDirectory=@DIR@ +ExecStart=/usr/bin/python3 @DIR@/dash.py @ARGS@ +Restart=on-failure +RestartSec=5 +# Optional: another time zone than the machine's for the band imports +#Environment=DASH_TZ=Europe/Berlin +NoNewPrivileges=yes +PrivateTmp=yes +ProtectSystem=full + +[Install] +WantedBy=multi-user.target diff --git a/dashboard/install.sh b/dashboard/install.sh new file mode 100755 index 0000000..1bbbb5f --- /dev/null +++ b/dashboard/install.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# Install or update the dashboard on Raspberry Pi OS / Debian (Bookworm or newer): +# +# sudo ./install.sh the Pi with the 3.5" SPI screen, as the user who ran sudo +# sudo ./install.sh --headless any computer: no screen, web pages + workers only +# (without it: a small screen is used if one is found, else the same) +# options: --dir /opt/dashboard --user (made if missing) --no-apt --no-service +# +# Copies this folder to --dir (your dash_config.json, dash_data/ … there are never touched), installs the +# packages, writes the systemd service and starts it. Run it again after a git pull to update. +set -euo pipefail +SRC=$(cd "$(dirname "$0")" && pwd) +DIR=/opt/dashboard; RUN_AS=${SUDO_USER:-}; ARGS=""; APT=1; SERVICE=1 +while [ $# -gt 0 ]; do + case "$1" in + --headless) ARGS="--headless"; shift ;; + --dir) DIR=$2; shift 2 ;; + --user) RUN_AS=$2; shift 2 ;; + --no-apt) APT=0; shift ;; + --no-service) SERVICE=0; shift ;; + *) sed -n '2,9p' "$0"; exit 2 ;; + esac +done +[ "$(id -u)" = 0 ] || { echo "run it with sudo"; exit 1; } +[ -n "$RUN_AS" ] && [ "$RUN_AS" != root ] || { echo "say which user runs it: --user "; exit 1; } + +if ! id "$RUN_AS" >/dev/null 2>&1; then + useradd --system --create-home --home-dir "/var/lib/$RUN_AS" --shell /usr/sbin/nologin "$RUN_AS" + echo "made the system user $RUN_AS" +fi +[ -z "$ARGS" ] && usermod -aG video,input "$RUN_AS" # /dev/fb0 + the touch screen + +if [ "$APT" = 1 ]; then + apt-get update -qq + apt-get install -y python3-pil python3-numpy python3-flask python3-nacl python3-caldav \ + python3-recurring-ical-events python3-qrcode python3-paho-mqtt fonts-dejavu-core fonts-symbola rsync + [ -z "$ARGS" ] && apt-get install -y python3-evdev +fi + +mkdir -p "$DIR" +rsync -a --delete \ + --exclude 'dash_config.json' --exclude 'dash_calib.json' --exclude 'dash_history.json' --exclude 'dash_weather.json' \ + --exclude 'dash_cal_errors.json' --exclude 'dash_local.ics*' --exclude 'dash_data' --exclude '__pycache__' \ + --exclude '*.bak' --exclude '.git' --exclude 'restore.zip*' --exclude '*.before-restore-*' --exclude '*.upload' \ + "$SRC/" "$DIR/" +if [ ! -f "$DIR/dash_config.json" ]; then + cp "$SRC/dash_config.example.json" "$DIR/dash_config.json" + echo "wrote $DIR/dash_config.json from the example — the rest is in the web page's Settings" +fi +chmod 600 "$DIR/dash_config.json" +# the food database: the one the app ships (USDA + some shop products), unless there is one already +if [ -f "$SRC/../app/assets/foods.db" ] && [ ! -f "$DIR/dash_data/food/foods.db" ]; then + install -D -m 600 "$SRC/../app/assets/foods.db" "$DIR/dash_data/food/foods.db" + echo "food database: copied the app's ($DIR/dash_data/food/foods.db)" +fi +chown -R "$RUN_AS": "$DIR" + +if [ "$SERVICE" = 1 ]; then + sed -e "s|@USER@|$RUN_AS|g" -e "s|@DIR@|$DIR|g" -e "s|@ARGS@|$ARGS|g" "$SRC/dashboard.service" \ + | grep -v '^# Template' > /etc/systemd/system/dashboard.service + systemctl daemon-reload + systemctl enable --now dashboard >/dev/null + systemctl restart dashboard + sleep 3 + port=$(python3 -c "import json; print((json.load(open('$DIR/dash_config.json')).get('web') or {}).get('port', 8080))") + echo + echo "running: http://$(hostname -I | awk '{print $1}'):$port/ (logs: journalctl -u dashboard -f)" + journalctl -u dashboard -n 50 --no-pager | grep -o 'setup code: .*' | tail -1 | sed 's/^/first admin — /' || true +fi diff --git a/dashboard/panel.py b/dashboard/panel.py new file mode 100644 index 0000000..ba5d23d --- /dev/null +++ b/dashboard/panel.py @@ -0,0 +1,329 @@ +"""Drawing primitives. + +`Panel` owns the framebuffer, the fonts, and the optional emoji fallback. +Everything else in this file is a stateless helper used by the screen +renderers: text alignment, ellipsised + emoji-aware text, the date/event +formatters, the bottom nav bar, and the temperature graph. +""" +import glob +import os +from datetime import date, datetime, timedelta + +import numpy as np +from PIL import Image, ImageFont + +from config import FB_DEV, FONT_DIR, NAV_H, THEME +from store import goto_screen, hit + + +# ---- framebuffer ---------------------------------------------------------- + +SYS_FB = "/sys/class/graphics" +SMALL = ("fb_", "fbtft", "ili9", "st7", "hx83", "piscreen", "waveshare") # SPI panels' driver names + + +def framebuffers(): + """[{"dev": "/dev/fb1", "name": "fb_ili9486", "w", "h", "bpp", "small"}] — every framebuffer here.""" + out = [] + for p in sorted(glob.glob(os.path.join(SYS_FB, "fb[0-9]*"))): + n = os.path.basename(p) + try: + w, h, bpp = fb_geometry(n) + with open(os.path.join(p, "name")) as f: + name = f.read().strip() + except (OSError, ValueError): + continue + out.append({"dev": f"/dev/{n}", "name": name, "w": w, "h": h, "bpp": bpp, + "small": (any(k in name.lower() for k in SMALL) and w <= 1024 and h <= 800) or max(w, h) <= 800}) + return out + + +def find_screen(cfg): + """Which framebuffer to draw on → its /dev path, or None (web pages only). Settings ▸ General ▸ Screen: + "auto" (the default) = a small SPI panel's (fb_ili9486 …), never a desktop's GPU console; "none"; or a path.""" + want = str((cfg.get("screen") or {}).get("fb") or "auto") + if want == "none": + return None + fbs = framebuffers() + if want != "auto": + return want if any(f["dev"] == want for f in fbs) else None + small = [f for f in fbs if f["small"]] + return small[0]["dev"] if small else None + + +def fb_geometry(n="fb0"): + with open(os.path.join(SYS_FB, n, "virtual_size")) as f: + w, h = (int(x) for x in f.read().strip().split(",")) + with open(os.path.join(SYS_FB, n, "bits_per_pixel")) as f: + bpp = int(f.read().strip()) + return w, h, bpp + + +def to_rgb565(img, brightness=1.0): + a = np.asarray(img, dtype=np.uint16) + if brightness < 1.0: + a = (a * brightness).astype(np.uint16) # multiplier ≤ 1, no overflow + r = (a[..., 0] >> 3) << 11 + g = (a[..., 1] >> 2) << 5 + b = a[..., 2] >> 3 + return (r | g | b).astype(" max_w: + s = s[:-1] + return s + "…" + + +def fmt_when(dt, long=False): + """Format an event datetime: compact for Home, fuller for the Calendar screen.""" + now = datetime.now() + if long: + return dt.strftime("%a %d %b · %H:%M") + if dt.date() == now.date(): + return "Today " + dt.strftime("%H:%M") + if dt.date() == (now + timedelta(days=1)).date(): + return "Tmrw " + dt.strftime("%H:%M") + return dt.strftime("%a %d %H:%M") + + +WEEKDAY_DAYS = 7 # short labels name the weekday only this far ahead + + +def _short_day(d, ordinal=False): + """'Mo 19' within WEEKDAY_DAYS of today, else '23 Oct'; ordinal: 'Mo 19th', '23rd Oct'.""" + day = _ordinal(d.day) if ordinal else d.strftime("%d") + if (d - date.today()).days <= WEEKDAY_DAYS: + return f"{d:%a}"[:2] + " " + day + return f"{day} {d:%b}" + + +def _day_label(d, long=False, ordinal=False): + today = date.today() + if d == today: + return "Today" + if d == today + timedelta(days=1): + return "Tmrw" + return d.strftime("%a %d %b") if long else _short_day(d, ordinal) + + +def fmt_event(ev, long=False, ordinal=False): + """When-text for an event: all-day -> day only; multi-day -> 'from – to' (no time).""" + start = ev["start"] + sd = start.date() + end = ev.get("end") + if end is not None and end > sd: # multi-day -> date range, no time + return f"{_day_label(sd, long, ordinal)} – {_day_label(end, long, ordinal)}" + if ev.get("all_day"): # full-day -> day only, no time + return _day_label(sd, long, ordinal) + if long: # timed, single day + return start.strftime("%a %d %b · %H:%M") + if sd == date.today(): + return "Today " + start.strftime("%H:%M") + if sd == date.today() + timedelta(days=1): + return "Tmrw " + start.strftime("%H:%M") + return f"{_short_day(sd, ordinal)} {start:%H:%M}" + + +def _ordinal(n): + suf = "th" if 10 <= n % 100 <= 20 else {1: "st", 2: "nd", 3: "rd"}.get(n % 10, "th") + return f"{n}{suf}" + + +def fmt_range(start, end): + """Multi-day span as '16th – 18th', or '30th Oct – 2nd Nov' across months.""" + if (start.year, start.month) == (end.year, end.month): + return f"{_ordinal(start.day)} – {_ordinal(end.day)}" + return f"{_ordinal(start.day)} {start:%b} – {_ordinal(end.day)} {end:%b}" + + +def is_emoji(ch): + o = ord(ch) + return (0x1F300 <= o <= 0x1FAFF) or (0x1F000 <= o <= 0x1F2FF) or \ + (0x2600 <= o <= 0x27BF) or (0x2B00 <= o <= 0x2BFF) or \ + (0x1F1E6 <= o <= 0x1F1FF) + + +def _rich_width(d, s, base, emoji): + w = 0 + for ch in s: + if 0xFE00 <= ord(ch) <= 0xFE0F: # variation selectors: zero-width + continue + f = emoji if (emoji is not None and is_emoji(ch)) else base + w += d.textlength(ch, font=f) + return w + + +def draw_rich(d, xy, text, base, emoji, fill): + """Draw text, falling back to the emoji font for emoji codepoints.""" + x, y = xy + for ch in text: + if 0xFE00 <= ord(ch) <= 0xFE0F: + continue + f = emoji if (emoji is not None and is_emoji(ch)) else base + d.text((x, y), ch, font=f, fill=fill) + x += d.textlength(ch, font=f) + return x + + +def fit_rich(d, text, base, emoji, max_w): + """Truncate (with …) to max_w, measuring emoji with the emoji font.""" + if _rich_width(d, text, base, emoji) <= max_w: + return text + s = text + while s and _rich_width(d, s + "…", base, emoji) > max_w: + s = s[:-1] + return s + "…" + + +# ---- nav icons (simple filled silhouettes; col = icon colour) ------------- + +def ic_home(d, cx, cy, s, col): + eave = cy - s * 0.15 + d.polygon([(cx - s, eave), (cx, cy - s), (cx + s, eave)], fill=col) + d.rectangle([cx - s * 0.68, eave, cx + s * 0.68, cy + s * 0.8], fill=col) + + +def ic_thermo(d, cx, cy, s, col): + tw, br = s * 0.42, s * 0.5 + bcy = cy + s * 0.55 + d.rounded_rectangle([cx - tw / 2, cy - s, cx + tw / 2, bcy], radius=tw / 2, fill=col) + d.ellipse([cx - br, bcy - br, cx + br, bcy + br], fill=col) + + +def ic_cloud(d, cx, cy, s, col): + base = cy + s * 0.5 + d.ellipse([cx - s, cy, cx - s * 0.05, base], fill=col) + d.ellipse([cx - s * 0.55, cy - s * 0.5, cx + s * 0.45, base], fill=col) + d.ellipse([cx + 0.0, cy - s * 0.1, cx + s, base], fill=col) + d.rectangle([cx - s * 0.78, base - s * 0.35, cx + s * 0.82, base], fill=col) + + +def ic_cal(d, cx, cy, s, col): + d.rounded_rectangle([cx - s, cy - s * 0.65, cx + s, cy + s * 0.85], radius=s * 0.18, fill=col) + d.rectangle([cx - s * 0.5, cy - s, cx - s * 0.32, cy - s * 0.55], fill=col) + d.rectangle([cx + s * 0.32, cy - s, cx + s * 0.5, cy - s * 0.55], fill=col) + + +def ic_settings(d, cx, cy, s, col): + rows = [cy - s * 0.55, cy, cy + s * 0.55] + knobs = [cx + s * 0.35, cx - s * 0.35, cx + s * 0.1] + for yy, kx in zip(rows, knobs): + d.line([(cx - s, yy), (cx + s, yy)], fill=col, width=2) + r = s * 0.22 + d.ellipse([kx - r, yy - r, kx + r, yy + r], fill=col) + + +def draw_nav(d, panel, store, screens): + """The bottom bar: one button per screen (screens.screen_list), the current one lit.""" + n = len(screens) + cw = panel.w / n + top = panel.h - NAV_H + for i, fn in enumerate(sc["icon"] for sc in screens): + cx, cy = cw * i + cw / 2, top + NAV_H / 2 + if i == store.screen: + d.rounded_rectangle([cw * i + 8, top + 6, cw * (i + 1) - 8, panel.h - 6], + radius=12, fill=THEME["highlight"]) + fn(d, cx, cy, 15, THEME["ink"]) + else: + fn(d, cx, cy, 15, THEME["muted"]) + hit(store, (cw * i, top, cw * (i + 1), panel.h), + lambda i=i: goto_screen(store, i, screens)) + + +# ---- graph (used by the Temperature screen) ------------------------------- + +def draw_graph(d, panel, box, vals_c, units): + x0, y0, x1, y1 = box + d.rectangle(box, outline=THEME["card"], width=1) + if len(vals_c) < 2: + return + vals = [disp_temp(v, units)[0] for v in vals_c] + lo, hi = min(vals), max(vals) + if hi - lo < 1: + hi, lo = hi + 1, lo - 1 + n = len(vals) + pts = [(x0 + (x1 - x0) * i / (n - 1), + y1 - (y1 - y0) * (v - lo) / (hi - lo)) for i, v in enumerate(vals)] + d.line(pts, fill=THEME["graph"], width=2, joint="curve") + u = disp_temp(0, units)[1] + d.text((x0 + 4, y0 + 2), f"{hi:.0f}{u}", font=panel.f["xs"], fill=THEME["dim"]) + d.text((x0 + 4, y1 - 16), f"{lo:.0f}{u}", font=panel.f["xs"], fill=THEME["dim"]) diff --git a/dashboard/pluginhost.py b/dashboard/pluginhost.py new file mode 100644 index 0000000..c470f1c --- /dev/null +++ b/dashboard/pluginhost.py @@ -0,0 +1,592 @@ +"""Plugins: optional features that live in plugins// and reach the dashboard +only through the `Context` they get in `register(ctx)`. + +A plugin is a Python package with + + META = {"title": "…", "description": "…", "glyph": "⏱", "glyph_color": None (optional CSS colour), + "glyph_svg": None (optional {"viewBox": "…", "d": "…"}: drawn instead of the glyph), + "settings": [{"key": "currency", "label": "Currency", "type": "text", + "default": "EUR", "max": 3}, …], + "sync": {"x.db": {"table": {…}}}} # optional: tables synced between devices (syncdb.py) + def register(ctx): … # make a blueprint, add a nav link, start a worker + +Every plugin found is imported and registered at start-up (`load`, by dash.main — also +without the web pages), enabled or not; whether it is on is checked per request +(`plugins..enabled` in dash_config.json, the Settings ▸ Plugins tab; a plugin +whose META says "default_on" counts as on until it's switched off), so switching one on +or off needs no restart — a disabled plugin's pages answer 404, its nav link, Home parts +and 3.5" screens disappear. Only workers are started once, for the plugins enabled at +start-up. + +The built-in plugins (calendar, weather, stations — once part of the core) may also use +`ctx.store` (the live Store their workers fill) and import the drawing helpers (panel, +config) for the 3.5" screen; the others stay with the ctx API. + +A plugin keeps its own data under dash_data// (`ctx.data_path`) — never in +dash_config.json, which holds only its settings. A plugin that fails to import or +register is listed in Settings with the error; the rest of the dashboard runs on. + +`ctx` is the whole API on purpose: if a plugin needs something from the core, it +gets a method here instead of importing core modules, so the core can change +inside without breaking plugins. +""" +import functools +import importlib +import json +import os +import re +import threading +import time +import traceback +from collections import OrderedDict +from datetime import date + +from flask import Blueprint, abort, has_request_context, request + +import auth + +HERE = os.path.dirname(os.path.abspath(__file__)) +PLUGIN_DIR = os.path.join(HERE, "plugins") +DATA_DIR = os.path.join(HERE, "dash_data") +TYPES = ("text", "number", "bool", "select") + +_plugins = {} # name -> Plugin, in discovery order + + +class Invalid(ValueError): + def __init__(self, field, msg): + super().__init__(msg) + self.field = field + + +class Plugin: + def __init__(self, name): + self.name, self.module, self.error = name, None, None + self.meta, self.nav, self.workers = {}, [], [] + self.tab, self.panel = name, None # Settings tab name, settings_panel() + self.pages, self.warm = OrderedDict(), [] # cached_page HTML, warm() paths + self.tabs, self.more = [], [] # section_tabs(items, more) + self.host, self.add, self.report = None, None, None # inside(host, add, report, blocks) + self.blocks = [] + self.provides = {} # provide(name, fn): answers for other plugins + self.home_parts = {} # home(region, fn): web Home regions + self.screens = [] # screen(…): 3.5" screens + self.home_slots = {} # home_screen(slot, fn): parts of the 3.5" Home + self.exits = [] # on_exit(fn) + self.globals = {} # template_globals(…) + + +class Context: + """What a plugin may use. Its settings come back with the declared defaults filled in.""" + + def __init__(self, store, plugin, same_origin): + self._store, self._p = store, plugin + self.name = plugin.name + self.same_origin = same_origin # call in POST handlers: False = refuse (403) + self.store = store # the live Store — built-in plugins only (see above) + + # ---- settings + data + @property + def enabled(self): + return enabled(self._store, self.name) + + @property + def settings(self): + mine = ((self._store.cfg.get("plugins") or {}).get(self.name) or {}) + return {f["key"]: mine.get(f["key"], f.get("default")) for f in self._p.meta.get("settings", [])} + + def data_path(self, filename): + d = os.path.join(DATA_DIR, self.name) + os.makedirs(d, exist_ok=True) + return os.path.join(d, filename) + + def data_version(self, filename): + """Changes with every write to a data file (SQLite: its -wal file too).""" + out = [] + for f in (filename, filename + "-wal"): + try: + st = os.stat(self.data_path(f)) + out.append((st.st_mtime_ns, st.st_size)) + except OSError: + out.append(None) + return tuple(out) + + # ---- caching + def cached_page(self, *files, extra=None): + """Decorator for a GET page whose HTML only depends on the request URL, the + plugin's data `files`, the config, the code and the date: the finished page is + kept (CACHE_PAGES per plugin) and served again until one of those changes — or + extra() returns something else. Not for pages showing the time of day.""" + def deco(fn): + pages = self._p.pages + + @functools.wraps(fn) + def wrapped(*a, **kw): + key = (request.full_path, tuple(self.data_version(f) for f in files), _config_key(self._store), + _code_version(), date.today(), extra() if extra else None, auth.cache_key()) + with _cache_lock: + html = pages.get(key) + if html is not None: + pages.move_to_end(key) + return html + html = fn(*a, **kw) # outside the lock: other pages stay served + if isinstance(html, str): + with _cache_lock: + pages[key] = html + while len(pages) > CACHE_PAGES: + pages.popitem(last=False) + return html + return wrapped + return deco + + def warm(self, *paths): + """Pages the background warmer keeps built (cached_page ones): after a change, + the next visit is fast too. Checked every WARM_EVERY seconds.""" + self._p.warm.extend(paths) + + # ---- web + def blueprint(self, url_prefix): + """A Flask blueprint for the plugin's pages (templates/ + static/ of its folder). + Name templates /x.html so they never shadow the core's; they may + {% extends "base.html" %}.""" + bp = Blueprint(self.name, self._p.module.__name__, url_prefix=url_prefix or None, + template_folder="templates", static_folder="static", + static_url_path="/static" if url_prefix else f"/p/{self.name}/static") # no prefix: /week … + + @bp.before_request + def gate(): + if not self.enabled or not auth.allows(self.name): # off, or not for this viewer + abort(404) + self._p.blueprints = getattr(self._p, "blueprints", []) + [bp] + return bp + + def nav(self, label, href, glyph=None, also=()): + """A link on phone Home and a button in the page headers. The first one also names + the plugin's Settings tab (/work -> /settings#work) unless META "settings_tab" does. + also = more addresses of the plugin's pages that light the button (/month).""" + if not self._p.nav and not self._p.meta.get("settings_tab"): + self._p.tab = href.strip("/").split("/")[0] or self.name + self._p.nav.append({"label": label, "href": href, "glyph": glyph or self._p.meta.get("glyph", ""), + "color": self._p.meta.get("glyph_color"), "svg": self._p.meta.get("glyph_svg"), + "own": list(also)}) + + def section_tabs(self, items, more=()): + """The plugin's sections as the tab row under its header: [(href, label)]; `more` = + [(label, href[, own])] behind the row's ⋮ menu (right end) — own=True: only on the + plugin's own tabs (not on a guest's page). Plugins living inside it + (inside()) are appended while they're on (pluginhost.section).""" + self._p.tabs, self._p.more = list(items), list(more) + + def inside(self, host, add=None, report=None, blocks=()): + """Show this plugin as a section of another one while that one is on: its first nav + link becomes a tab in the host's row (section) and leaves the nav buttons (the host's + button stays lit on its pages); add = (label, href) — an entry for the host's "add" + menu; report(days) → HTML, its part of the host's report page (the host shows it while + it's on); blocks = [{id, kind ("tile" / "card"), label, w, render() → HTML, version() → + anything that changes with its data, href?}] — pieces the host may place on its pages + (Health: Overview's add picker). Its own on / off, data, settings stay.""" + self._p.host, self._p.add, self._p.report = host, add, report + self._p.blocks = [dict(b, tab=self.name) for b in blocks] + + def provide(self, name, fn): + """Offer other plugins an answer: fn(*args) → plain data (they get it through ask). + Keeps plugins from importing each other — Health offers its energy estimate, the + food diary asks for it.""" + self._p.provides[name] = fn + + def ask(self, plugin, name, *args): + """Another plugin's provide()d answer, or None when that plugin isn't installed, is + off, doesn't offer it, or fails (logged) — the asker carries on without it.""" + p = _plugins.get(plugin) + fn = p.provides.get(name) if p and (_seen if has_request_context() else _on)(self._store, plugin) else None + if not fn: + return None + try: + return fn(*args) + except Exception: + print(f"plugin {self.name}: ask {plugin}.{name}: {traceback.format_exc()}", flush=True) + return None + + def section(self): + """This plugin's section now (pluginhost.section): tabs, add entries, the guests' + report parts, ⋯ links.""" + return section(self._store, self.name) + + # ---- the dashboard's own surfaces (Home, the 3.5" screen) + def home(self, region, render): + """A region of the web Home (its grid area in dash.css): render() → HTML, "" = nothing + to show. Regions: weather, stations, main, side, up, day. A region nobody fills is + left out and the grid closes up (home.html: has- classes).""" + self._p.home_parts[region] = render + + def screen(self, label, icon, render, key=None, on_open=None, stay=None, order=50): + """A screen on the 3.5" panel, a button in its bottom bar (after Home, before Settings). + icon(d, cx, cy, size, colour) draws the button; render(img, d, panel, store) the screen + (register taps with ctx.hit); key(ch) gets ← / → ("left" / "right"); on_open() runs when + it's switched to; stay() → True: the idle return to Home leaves it open (a passive display); + order = its place in the bar (lower = further left).""" + self._p.screens.append({"label": label, "icon": icon, "render": render, "key": key, "open": on_open, + "stay": stay, "order": order, "plugin": self.name}) + + def home_screen(self, slot, render): + """A part of the 3.5" Home: render(img, d, panel, store). Slots: "corner" (top right), + "indoor" (bottom right), "agenda" (the left column under the date).""" + self._p.home_slots[slot] = render + + def hit(self, box, fn): + """A tappable region (x0, y0, x1, y1) on the 3.5" panel for the frame being drawn.""" + from store import hit + hit(self._store, box, fn) + + def on_exit(self, fn): + """fn() when the dashboard stops (dash.main's finally): save what's in memory.""" + self._p.exits.append(fn) + + def template_globals(self, **kw): + """Names every template sees (the plugin's helpers, e.g. the day view's SCALE).""" + self._p.globals.update(kw) + + def settings_panel(self, template, view): + """Extra content on the plugin's Settings tab, under its fields and outside the + Settings form (it saves on its own, through the plugin's API): `template` is + rendered with view() -> dict of template variables, inside the Settings request.""" + self._p.panel = (template, view) + + # ---- core services + def events_between(self, start, end): + """Calendar events overlapping [start, end) (naive local datetimes), shown + calendars only: [{title, start, end, all_day, colour, calendar}].""" + return ask(self._store, "calendar", "events_between", start, end) or [] + + def day_bands(self, day): + """Sleep / lunch bands set in Settings ▸ Calendar for `day` (a date): + [{"label", "start", "end"}] in hours (0–24; a band over midnight comes as two).""" + from webview import BANDS, _band + return [{"label": label, "start": a, "end": z} + for key, label in BANDS for a, z in _band(self._store.cfg, key, day)] + + def units(self): + return self._store.units + + def worker(self, fn): + """Run fn(ctx) on a daemon thread (started only if the plugin is on at start-up).""" + self._p.workers.append(fn) + + def as_owner(self): + """with ctx.as_owner(): … — outside a request, answer as the admin (auth.as_owner), e.g. for + what's made for the owner's phone; elsewhere a worker sees what the household sees.""" + import auth + return auth.as_owner() + + def primary(self): + """Is this dashboard the one that makes the shared results (summaries for the app, station hours)? + `sync.primary` in dash_config.json, default yes; a second dashboard (a laptop) sets false — + it still gets them through the sync, and two writers would keep overwriting each other.""" + return (self._store.cfg.get("sync") or {}).get("primary", True) + + def on_sync(self, fn): + """fn() runs after the phone app's "sync now" pulled (sync.kick); True = it wrote something to send back.""" + import sync + sync.kick_hooks.append(fn) + + +CACHE_PAGES = 40 +_cache_lock = threading.Lock() +WARM_EVERY = 60 +_code = {"t": 0, "v": None} + + +def _config_key(store): + """The whole config: settings, plugins on / off, units… (a few KB, cheap to dump).""" + return json.dumps(store.cfg, sort_keys=True, default=str) + + +def _code_version(): + """Newest template / static file of the core and the plugins (a deploy changes it; + templates reload without a restart). Looked at once every 5 s at most.""" + if time.time() - _code["t"] > 5: + newest = 0 + for top in (os.path.join(HERE, "templates"), os.path.join(HERE, "static"), PLUGIN_DIR): + for d, dirs, files in os.walk(top): + dirs[:] = [x for x in dirs if x != "__pycache__"] + for f in files: + try: + newest = max(newest, os.stat(os.path.join(d, f)).st_mtime_ns) + except OSError: + pass + _code.update(t=time.time(), v=newest) + return _code["v"] + + +def _warmer(app, store): + """Fetch the warm() pages of the enabled plugins now and then: a cached page costs + almost nothing, a stale one (new data, new day) is rebuilt here instead of on a visit.""" + time.sleep(20) # let start-up finish first + client = app.test_client() + while True: + for name, p in list(_plugins.items()): + if p.error or not enabled(store, name): + continue + for path in p.warm: + try: + client.get(path, environ_base={"dash.internal": True}) # as admin (auth) + except Exception as e: + print(f"plugin {name}: warm {path}: {type(e).__name__}: {e}", flush=True) + time.sleep(WARM_EVERY) + + +def enabled(store, name): + sec = (store.cfg.get("plugins") or {}).get(name) or {} + if "enabled" in sec: + return bool(sec["enabled"]) + p = _plugins.get(name) # never set: the plugin's default (built-ins: on) + return bool(p and p.meta.get("default_on")) + + +def discover(): + if not os.path.isdir(PLUGIN_DIR): + return [] + return sorted(n for n in os.listdir(PLUGIN_DIR) + if re.fullmatch(r"[a-z][a-z0-9_]*", n) + and os.path.exists(os.path.join(PLUGIN_DIR, n, "__init__.py"))) + + +def _same_origin(): # the web's check, once the web pages run + import web + return web.same_origin() + + +def load(store): + """Import + register every plugin and start the workers of the enabled ones — once, at + start-up (dash.main; web.create_app calls it too, for a web-only run). The web pages + come later (attach).""" + if _plugins: + return + for name in discover(): + p = _plugins[name] = Plugin(name) + try: + p.module = importlib.import_module(f"plugins.{name}") + p.meta = dict(getattr(p.module, "META", {})) + p.meta.setdefault("title", name.title()) + if p.meta.get("settings_tab"): + p.tab = p.meta["settings_tab"] + for f in p.meta.get("settings", []): + assert f.get("type") in TYPES and f.get("key"), f"bad setting {f!r}" + p.ctx = Context(store, p, _same_origin) + p.module.register(p.ctx) + except Exception as e: + p.error = f"{type(e).__name__}: {e}" + print(f"plugin {name}: failed to load\n{traceback.format_exc()}", flush=True) + continue + if enabled(store, name): + for fn in p.workers: + threading.Thread(target=fn, args=(p.ctx,), daemon=True, name=f"plugin-{name}").start() + print(f"plugin {name}: loaded{' (on)' if enabled(store, name) else ''}", flush=True) + try: # META["sync"]: stamp those tables, start the sync worker + import sync + sync.boot(store) + except Exception: + print(f"sync: {traceback.format_exc()}", flush=True) + + +def attach(app, store, same_origin=None): + """Hang the plugins' blueprints + template names on the web app (web.create_app).""" + load(store) + for name, p in _plugins.items(): + if p.error: + continue + for bp in getattr(p, "blueprints", []): + app.register_blueprint(bp) + app.jinja_env.globals.update(p.globals) + if any(p.warm for p in _plugins.values()): + threading.Thread(target=_warmer, args=(app, store), daemon=True, name="plugin-warm").start() + + +def ask(store, plugin, name, *args): + """A plugin's provide()d answer for the core (backlight, Home …) — None when it's off.""" + p = _plugins.get(plugin) + return p.ctx.ask(plugin, name, *args) if p and not p.error and hasattr(p, "ctx") else None + + +def home_parts(store): + """{region: HTML} of the web Home from the plugins that are on (empty ones left out).""" + out = {} + for name, p in _plugins.items(): + if not _seen(store, name): + continue + for region, fn in p.home_parts.items(): + try: + html = fn() + except Exception: + print(f"plugin {name}: home {region}: {traceback.format_exc()}", flush=True) + continue + if html and str(html).strip(): + out[region] = html + return out + + +def screens(store): + """The 3.5" screens of the plugins that are on, by their order.""" + return sorted((sc for name, p in _plugins.items() if _seen(store, name) for sc in p.screens), + key=lambda sc: sc["order"]) + + +def home_slot(store, slot): + """The plugin drawing that part of the 3.5" Home, or None.""" + for name, p in _plugins.items(): + if _seen(store, name) and slot in p.home_slots: + return p.home_slots[slot] + return None + + +def shutdown(): + for name, p in _plugins.items(): + for fn in p.exits: + try: + fn() + except Exception: + print(f"plugin {name}: on exit: {traceback.format_exc()}", flush=True) + + +def catalog(): + """The loaded plugins for Settings ▸ Users: [{name, title, host}].""" + return [{"name": n, "title": p.meta.get("title", n), "host": p.host} for n, p in _plugins.items() if not p.error] + + +def _on(store, name): + p = _plugins.get(name) + return bool(p and not p.error and enabled(store, name)) + + +def _seen(store, name): + """On, and for this viewer (auth: a member's / the household's plugins; the 3.5" screen = household).""" + return _on(store, name) and auth.allows(name) + + +def host_of(store, name): + """The plugin `name` lives inside (inside()), if that plugin is installed and loaded — + on or off: a host that's off still frames its guests (its section shows just them).""" + p = _plugins.get(name) + h = _plugins.get(p.host) if p and p.host else None + return p.host if h and not h.error else None + + +def _guests(store, name): + """The plugins on now that live inside `name`.""" + return [g for gn, g in _plugins.items() if g.nav and _seen(store, gn) and host_of(store, gn) == name] + + +def nav(store): + """Nav links (templates: phone Home, page headers): the enabled plugins, minus those + living inside another one — the host's button stands for its section instead. Its link + carries the guests' addresses (`also`) so it stays lit on their pages; a host that's off + but has guests on still shows, pointing at the first guest.""" + out = [] + for name, p in _plugins.items(): + if p.error or host_of(store, name): + continue + guests = [g.nav[0]["href"] for g in _guests(store, name)] + if enabled(store, name) and auth.allows(name): + out += [dict(link, also=guests + link.get("own", [])) for link in p.nav] + elif guests and p.nav: + out.append(dict(p.nav[0], href=guests[0], also=guests)) + return out + + +def section(store, name): + """The tab row of plugin `name`'s section: its own tabs (while it's on) + the plugins + inside it that are on, their entries for its add menu and their report parts, and the + host's ⋯ links (while it's on): {"tabs": [(href, label)], "adds": [(label, href)], + "reports": [report(days) → HTML], "more": [{label, href, own}], "own": [its own tab hrefs], + "blocks": [the guests' blocks + "tab_label"]}.""" + p = _plugins.get(name) + on = _seen(store, name) + tabs, more = (list(p.tabs), [{"label": m[0], "href": m[1], "own": bool(m[2:] and m[2])} for m in p.more]) \ + if p and on else ([], []) + own = [h for h, _ in tabs] + adds, reports, gblocks = [], [], [] + for g in _guests(store, name): + tabs.append((g.nav[0]["href"], g.nav[0]["label"])) + gblocks += [dict(b, tab_label=g.nav[0]["label"]) for b in g.blocks] + if g.add: + adds.append(g.add) + if g.report: + reports.append(g.report) + return {"tabs": tabs, "adds": adds, "reports": reports, "more": more, "own": own, "blocks": gblocks} + + +# ---- Settings ▸ Plugins ------------------------------------------------------------- + +def settings_view(store): + """Settings: General lists every plugin (on / off); each one that loaded gets its own + tab (`tab`) with its fields and its panel (settings_panel, rendered here).""" + from flask import render_template + out = [] + for name, p in _plugins.items(): + mine = ((store.cfg.get("plugins") or {}).get(name) or {}) + fields = [dict(f, value=mine.get(f["key"], f.get("default"))) for f in p.meta.get("settings", [])] + panel = None + if p.panel and not p.error and enabled(store, name): + try: + panel = render_template(p.panel[0], **p.panel[1]()) + except Exception as e: + print(f"plugin {name}: settings panel: {traceback.format_exc()}", flush=True) + panel = f'

{type(e).__name__}: {e}

' + out.append({"name": name, "title": p.meta.get("title", name), "glyph": p.meta.get("glyph", ""), + "glyph_color": p.meta.get("glyph_color"), "glyph_svg": p.meta.get("glyph_svg"), + "description": p.meta.get("description", ""), "error": p.error, "tab": p.tab, + "label": p.nav[0]["label"] if p.nav else p.meta.get("title", name), + "core_tab": bool(p.meta.get("settings_tab")), # its tab is one of Settings' own panes + "enabled": enabled(store, name), "fields": fields, "panel": panel, + "links": p.meta.get("links", [])}) + return out + + +def _value(f, v, field): + t = f["type"] + if t == "bool": + return bool(v) + if t == "number": + try: + n = float(str(v).replace(",", ".")) + except (TypeError, ValueError): + raise Invalid(field, "Must be a number.") + lo, hi = f.get("min", float("-inf")), f.get("max", float("inf")) + if not lo <= n <= hi: + raise Invalid(field, f"Must be between {lo:g} and {hi:g}.") + return int(n) if f.get("integer") else n + if t == "select": + opts = [o[0] if isinstance(o, (list, tuple)) else o for o in f.get("options", [])] + for o in opts: # the form sends text; options may be numbers + if str(o) == str(v): + return o + raise Invalid(field, "Pick one of the options.") + v = str(v or "").strip() + if len(v) > f.get("max", 200): + raise Invalid(field, f"At most {f.get('max', 200)} characters.") + if f.get("pattern") and v and not re.fullmatch(f["pattern"], v): + raise Invalid(field, f.get("pattern_help", "Not a valid value.")) + return v + + +def build_settings(cfg, d): + """New `plugins` config section from the form (keeps sections of plugins not + installed now, so removing a plugin folder doesn't lose its settings).""" + out = {k: dict(v) for k, v in (cfg.get("plugins") or {}).items() if isinstance(v, dict)} + for name, p in _plugins.items(): + if p.error: + continue + sent = (d or {}).get(name) + if not isinstance(sent, dict): + continue + sec = out.setdefault(name, {}) + sec["enabled"] = bool(sent.get("enabled")) + for f in p.meta.get("settings", []): + if f["key"] in sent or f["type"] == "bool": + sec[f["key"]] = _value(f, sent.get(f["key"]), f"plugins.{name}.{f['key']}") + check = getattr(p.module, "validate_settings", None) + if check: # cross-field checks: returns (key, message) or None + bad = check(sec) + if bad: + raise Invalid(f"plugins.{name}.{bad[0]}", bad[1]) + return out diff --git a/dashboard/plugins/__init__.py b/dashboard/plugins/__init__.py new file mode 100644 index 0000000..1295312 --- /dev/null +++ b/dashboard/plugins/__init__.py @@ -0,0 +1 @@ +"""Dashboard plugins: one package per folder, loaded by pluginhost.py.""" diff --git a/dashboard/plugins/activity/__init__.py b/dashboard/plugins/activity/__init__.py new file mode 100644 index 0000000..da283a0 --- /dev/null +++ b/dashboard/plugins/activity/__init__.py @@ -0,0 +1,260 @@ +"""Activity: what you did on your computers, from ActivityWatch — FlowWatch rebuilt inside the +dashboard, living inside Work (an Activity button next to Work's Report). Plan + status: the dashboard +notes, CLAUDE.md ▸ Activity. + +Each computer runs ActivityWatch listening on the home network (aw-server.toml host = "0.0.0.0"); +a worker here asks each one every few minutes for what's new (pull.py) and keeps it in +dash_data/activity/activity.db (db.py). A computer that was away is caught up when it's back. +The sorting happens here (sorter.py: active time, window + browser tab / tmux / VS Code detail, +FlowWatch's rules, the calendar around it, smoothing); views.py shapes it for the pages and for Work's +week (provide "blocks": its Activity lane): + + /activity?d=YYYY-MM-DD the day: time per category (tree; "Move to…" makes a learned rule), + per-computer strips, the unsorted list (ranked; "Sort" makes a rule), + the week; &raw=1 = before smoothing + /activity/rules categories (tree: colour, productive / distraction) and their rules + +Settings ▸ Activity: the computers (name=url, …), how often, a panel with what each one has sent +(+ "Pull now"). FlowWatch's categories, rules and cached days came in once by hand: +python3 -m plugins.activity.pull --flowwatch dash_data/activity/activity.db +""" +import os +import re +import threading +import time +from contextlib import closing +from datetime import date, datetime, timedelta + +from flask import abort, jsonify, render_template, request + +from . import db, pull, sorter, views + +META = { + "title": "Activity", + "glyph": "⏱", + "glyph_color": "#7fd6a3", + "description": "What you did on your computers, from ActivityWatch: pulled from each one it can reach, shared with " + "the other dashboards through the sync, sorted into your categories here.", + "links": [{"label": "Open", "href": "/activity"}, {"label": "Categories & rules", "href": "/activity/rules"}], + "settings": [ + {"key": "sources", "label": "Computers (name=address, comma separated)", "type": "text", "max": 500, + "default": "", + "help": "Each one's ActivityWatch, listening on the home network (aw-server.toml: host = \"0.0.0.0\"). " + "A dashboard running on one of them reaches its own at http://127.0.0.1:5600 — that works away from home; " + "what the others pull arrives through the sync."}, + {"key": "every", "label": "Ask every (minutes)", "type": "number", "default": 5, "min": 1, "max": 60, "integer": True}, + {"key": "smooth", "label": "Smooth out switches shorter than (seconds; 0 = off)", "type": "number", "default": sorter.SMOOTH, + "min": 0, "max": 900, "integer": True, + "help": "A short switch between two stretches of the same category takes theirs; unsorted short ones take the longer neighbour. " + "Distractions are never smoothed away. The day page can show it raw too."}, + ], + # what ActivityWatch recorded, so a computer away from home still reaches the others (sync.py / syncdb.py); + # keyed by computer + bucket + time, so two dashboards pulling the same computer agree on its rows. + # Not synced: source (each dashboard's own pull status), categories / rules, meta. + "sync": {"activity.db": { + "bucket": {"key": "NEW.source || '/' || NEW.bucket_id"}, + "event": {"key": "(SELECT source || '/' || bucket_id FROM bucket WHERE id = NEW.bucket) || '@' || NEW.ts", + "refs": {"bucket": "bucket"}}, + "input_min": {"key": "(SELECT source || '/' || bucket_id FROM bucket WHERE id = NEW.bucket) || '#' || NEW.minute", + "refs": {"bucket": "bucket"}}, + }}, +} +COLOR = re.compile(r"^#[0-9a-fA-F]{6}$") + + +def register(ctx): + path = ctx.data_path("activity.db") + with closing(db.connect(path)): # schema + the one-time rowid rebuild before the sync stamps it + pass + state = {"last": None, "result": {}, "busy": False, "pulled": 0} + lock = threading.Lock() + memo = views.Memo() + + def pull_now(): + with lock: + state["busy"] = True + try: + state["result"] = pull.pull_all(path, pull.parse_sources(ctx.settings.get("sources"))) + state["last"] = time.time() + state["pulled"] += 1 # today's sorting is stale from here + finally: + state["busy"] = False + return state["result"] + + def worker(_ctx): + time.sleep(20) # let the rest start first + while True: + try: + pull_now() + except Exception as e: + print(f"activity: {e}", flush=True) + time.sleep(max(1, int(ctx.settings.get("every") or 5)) * 60) + + ctx.worker(worker) + bp = ctx.blueprint("/activity") + here = os.path.dirname(os.path.abspath(__file__)) + + @bp.context_processor + def asset_version(): # cache-buster for activity.css / .js + st = os.path.join(here, "static") + return {"asset_v": "%x" % int(max(os.path.getmtime(os.path.join(st, f)) for f in os.listdir(st)))} + ctx.nav("Activity", "/activity") + ctx.inside("workload") # Work shows an Activity button by Report; Work's nav button stays lit here + + def con(): + return closing(db.connect(path)) + + def rules_v(c): + r = c.execute("SELECT v FROM meta WHERE k = 'rules_v'").fetchone() + return r[0] if r else 0 + + def bump(c): # rules / categories changed: every sorted day is stale + c.execute("INSERT INTO meta VALUES ('rules_v', 1) ON CONFLICT(k) DO UPDATE SET v = v + 1") + c.commit() + + def context(d): + """The day's timed calendar events (cancelled ones left out) + the smoothing, for the sorter.""" + a = datetime.combine(d, datetime.min.time()) + evs = [(int(e["start"].timestamp() * 1000), int(e["end"].timestamp() * 1000), e["calendar"] or "", e["title"] or "") + for e in ctx.events_between(a, a + timedelta(days=1)) + if not e["all_day"] and e.get("end") and not re.match(r"\s*\[?cancel", e["title"] or "", re.I)] + return sorted(evs), int(ctx.settings.get("smooth") if ctx.settings.get("smooth") is not None else sorter.SMOOTH) + + def blocks(d0, d1): # for Work's week: {iso: [blocks]} + with con() as c: + return views.work_blocks(c, memo, d0, d1, rules_v(c), state["pulled"], context) + ctx.provide("blocks", blocks) + + # ---- Settings ▸ Activity panel + def ago(t): + if not t: + return "never" + s = int(time.time() - t) + return "just now" if s < 60 else f"{s // 60} min ago" if s < 3600 else f"{s // 3600} h ago" if s < 86400 else f"{s // 86400} days ago" + + def when(ms): + return datetime.fromtimestamp(ms / 1000).strftime("%-d %b %H:%M") if ms else "—" + + def panel(): + with con() as c: + st, n = db.status(c), db.counts(c) + names = [x for x, _ in pull.parse_sources(ctx.settings.get("sources"))] + return {"sources": st, "names": names, "c": n, "ago": ago, "when": when, "busy": state["busy"]} + + ctx.settings_panel("activity/_settings.html", panel) + + # ---- pages + @bp.route("/", strict_slashes=False) + def day_page(): + today = date.today() + try: + d = min(today, date.fromisoformat(request.args.get("d", ""))) + except ValueError: + d = today + with con() as c: + v = views.day(c, memo, d, rules_v(c), state["pulled"], today, context, smoothed=not request.args.get("raw")) + return render_template("activity/day.html", v=v, hm=views.hm, page="activity") + + @bp.route("/rules") + def rules_page(): + with con() as c: + v = views.rules_page(c) + return render_template("activity/rules.html", v=v, page="activity") + + # ---- API (same-origin JSON writes) + def body(): + if not ctx.same_origin(): + abort(403) + return request.get_json(silent=True) or {} + + def bad(field, msg): + return jsonify(error=msg, field=field), 400 + + @bp.route("/api/pull", methods=["POST"]) + def api_pull(): + body() + return jsonify(pull_now()) + + @bp.route("/api/rule", methods=["POST"]) + def api_rule(): # {id?, category_id, field, match, pattern, priority, origin?} + d = body() + field, match, pattern = d.get("field"), d.get("match"), str(d.get("pattern") or "").strip() + if field not in sorter.FIELDS: + return bad("field", "Which field?") + if match not in sorter.MATCHES: + return bad("match", "Contains, equals or regex?") + if not pattern or len(pattern) > 500: + return bad("pattern", "What should it match?") + if match == "regex": + try: + re.compile(pattern) + except re.error as e: + return bad("pattern", f"Not a valid regex: {e}") + try: + prio = int(d.get("priority") or 0) + cid = int(d.get("category_id")) + except (TypeError, ValueError): + return bad("category_id", "Pick a category.") + with con() as c: + if not c.execute("SELECT 1 FROM category WHERE id = ?", (cid,)).fetchone(): + return bad("category_id", "That category is gone.") + if d.get("id"): + c.execute("UPDATE rule SET category_id = ?, field = ?, match = ?, pattern = ?, priority = ? WHERE id = ?", + (cid, field, match, pattern, prio, int(d["id"]))) + rid = int(d["id"]) + else: + rid = c.execute("INSERT INTO rule (category_id, field, match, pattern, priority, origin) VALUES (?, ?, ?, ?, ?, ?)", + (cid, field, match, pattern, prio, d.get("origin") if d.get("origin") in ("manual", "learned") else "manual")).lastrowid + bump(c) + return jsonify(ok=True, id=rid) + + @bp.route("/api/rule/delete", methods=["POST"]) + def api_rule_delete(): # {id} + d = body() + with con() as c: + c.execute("DELETE FROM rule WHERE id = ?", (int(d.get("id") or 0),)) + bump(c) + return jsonify(ok=True) + + @bp.route("/api/category", methods=["POST"]) + def api_category(): # {id?, name, parent_id, color, productive, distraction, vague} + d = body() + name = " ".join(str(d.get("name") or "").split())[:80] + if not name: + return bad("name", "Name it.") + color = str(d.get("color") or "#6366f1") + if not COLOR.match(color): + return bad("color", "A colour like #388e3c.") + pid = int(d["parent_id"]) if d.get("parent_id") else None + with con() as c: + cid = int(d["id"]) if d.get("id") else None + p, seen = pid, set() + while p is not None: # no loops: not under itself or one of its own + if p == cid or p in seen: + return bad("parent_id", "It can't go under itself.") + seen.add(p) + r = c.execute("SELECT parent_id FROM category WHERE id = ?", (p,)).fetchone() + if not r: + return bad("parent_id", "That parent is gone.") + p = r[0] + vals = (pid, name, color, int(bool(d.get("productive"))), int(bool(d.get("distraction"))), int(bool(d.get("vague")))) + if cid: + c.execute("UPDATE category SET parent_id = ?, name = ?, color = ?, productive = ?, distraction = ?, vague = ? WHERE id = ?", + (*vals, cid)) + else: + cid = c.execute("INSERT INTO category (parent_id, name, color, productive, distraction, vague) VALUES (?, ?, ?, ?, ?, ?)", + vals).lastrowid + bump(c) + return jsonify(ok=True, id=cid) + + @bp.route("/api/category/delete", methods=["POST"]) + def api_category_delete(): # {id} — its sub-categories move up, its rules go with it + d = body() + cid = int(d.get("id") or 0) + with con() as c: + r = c.execute("SELECT parent_id FROM category WHERE id = ?", (cid,)).fetchone() + if r: + c.execute("UPDATE category SET parent_id = ? WHERE parent_id = ?", (r[0], cid)) + c.execute("DELETE FROM category WHERE id = ?", (cid,)) + bump(c) + return jsonify(ok=True) diff --git a/dashboard/plugins/activity/db.py b/dashboard/plugins/activity/db.py new file mode 100644 index 0000000..2c07350 --- /dev/null +++ b/dashboard/plugins/activity/db.py @@ -0,0 +1,177 @@ +"""The activity plugin's SQLite (dash_data/activity/activity.db, chmod 600): what ActivityWatch +recorded on each computer, pulled here (pull.py), and the categories + rules that sort it. + +- source: a computer's ActivityWatch (name from Settings, its URL, what it says it is, last pull) +- bucket: one ActivityWatch bucket of a source (window, afk, web, tmux, vscode, input …); + `pulled_to` = the newest event start pulled (UTC ms) — the next pull asks from there, so the + still-growing last event is fetched again and replaced +- event: (bucket, ts) → duration, data — ts = the event's start, UTC ms. ActivityWatch's own event + ids restart when it's reinstalled, so they aren't used. +- input_min: keyboard / mouse per minute (aw-watcher-input sends an event a second — kept summed) +- category: a tree (FlowWatch's: colour, productive / distraction; vague = calendar context may + override it); rule: field + match + pattern → category, with a priority and where it came from + (flowwatch / manual / learned — "Move to…" on the day page) + +bucket / event / input_min sync between dashboards (META["sync"], keyed by source + bucket + time), so +each computer's activity reaches the others whoever pulled it. Writes are upserts that leave an +unchanged row alone — every write is a change to send. event / input_min were WITHOUT ROWID tables +until 2026-10-22 (the sync's triggers need a rowid): connect() rebuilds them once. +""" +import json +import os +import re +import sqlite3 + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS source ( + name TEXT PRIMARY KEY, + url TEXT NOT NULL, + hostname TEXT, + device_id TEXT, + version TEXT, + last_try INTEGER, -- unix s + last_ok INTEGER, + error TEXT +); +CREATE TABLE IF NOT EXISTS bucket ( + id INTEGER PRIMARY KEY, + source TEXT NOT NULL, + bucket_id TEXT NOT NULL, + type TEXT, + client TEXT, + hostname TEXT, + pulled_to INTEGER, -- UTC ms: the newest event start pulled + UNIQUE (source, bucket_id) +); +CREATE TABLE IF NOT EXISTS event ( + bucket INTEGER NOT NULL REFERENCES bucket(id), + ts INTEGER NOT NULL, -- start, UTC ms + dur REAL NOT NULL, -- seconds + data TEXT NOT NULL, -- JSON + UNIQUE (bucket, ts) +); +CREATE TABLE IF NOT EXISTS input_min ( + bucket INTEGER NOT NULL REFERENCES bucket(id), + minute INTEGER NOT NULL, -- UTC unix minute (s // 60) + presses INTEGER NOT NULL DEFAULT 0, + clicks INTEGER NOT NULL DEFAULT 0, + scroll REAL NOT NULL DEFAULT 0, + moved REAL NOT NULL DEFAULT 0, + UNIQUE (bucket, minute) +); +CREATE TABLE IF NOT EXISTS category ( + id INTEGER PRIMARY KEY, + parent_id INTEGER REFERENCES category(id), + name TEXT NOT NULL, + color TEXT NOT NULL DEFAULT '#6366f1', + productive INTEGER NOT NULL DEFAULT 0, + distraction INTEGER NOT NULL DEFAULT 0, + vague INTEGER NOT NULL DEFAULT 0 -- says little on its own (Terminal …): calendar context may override +); +CREATE TABLE IF NOT EXISTS rule ( + id INTEGER PRIMARY KEY, + category_id INTEGER NOT NULL REFERENCES category(id) ON DELETE CASCADE, + field TEXT NOT NULL, -- app / title / url / tmux_session / vscode_project (more to come) + match TEXT NOT NULL, -- regex / contains / equals + pattern TEXT NOT NULL, + priority INTEGER NOT NULL DEFAULT 0, + origin TEXT NOT NULL DEFAULT 'manual' -- flowwatch / manual / learned +); +CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v); +""" +INDEXES = "CREATE INDEX IF NOT EXISTS event_ts ON event (ts);" # a day's events of every bucket (views.Memo) +ROWID = ("event", "input_min") # WITHOUT ROWID tables before 2026-10-22 → rebuilt with a rowid, same rows + + +def _rowid_tables(con): + for t in ROWID: + sql = con.execute("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?", (t,)).fetchone() + if not sql or "WITHOUT ROWID" not in sql[0].upper(): + continue + new = re.sub(r"PRIMARY KEY \(", "UNIQUE (", sql[0].replace(f"CREATE TABLE {t}", f"CREATE TABLE {t}_new", 1), count=1) + new = re.sub(r"\)\s*WITHOUT ROWID\s*$", ")", new, flags=re.I) + cols = ", ".join(r[1] for r in con.execute(f"PRAGMA table_info({t})")) # every column, sync's included + con.executescript(f"BEGIN; {new}; INSERT INTO {t}_new ({cols}) SELECT {cols} FROM {t}; " + f"DROP TABLE {t}; ALTER TABLE {t}_new RENAME TO {t}; COMMIT;") + print(f"activity: {t} rebuilt with a rowid (for the sync)", flush=True) + + +def connect(path): + new = not os.path.exists(path) + con = sqlite3.connect(path, timeout=30) + con.row_factory = sqlite3.Row + con.execute("PRAGMA journal_mode = WAL") + con.execute("PRAGMA foreign_keys = ON") + con.executescript(SCHEMA) + if "vague" not in {r[1] for r in con.execute("PRAGMA table_info(category)")}: # added 2026-10-20 + con.execute("ALTER TABLE category ADD COLUMN vague INTEGER NOT NULL DEFAULT 0") + _rowid_tables(con) + con.executescript(INDEXES) + if new: # a fresh database: a starting set of categories (defaults.py) + from . import defaults + defaults.seed(con) + con.commit() + if new: + os.chmod(path, 0o600) + return con + + +def bucket_row(con, source, bid, info): + """The local id of a source's bucket (made on first sight; type etc. refreshed).""" + con.execute("INSERT INTO bucket (source, bucket_id, type, client, hostname) VALUES (?, ?, ?, ?, ?) " + "ON CONFLICT(source, bucket_id) DO UPDATE SET type = excluded.type, client = excluded.client, " + "hostname = excluded.hostname WHERE type IS NOT excluded.type OR client IS NOT excluded.client " + "OR hostname IS NOT excluded.hostname", + (source, bid, info.get("type"), info.get("client"), info.get("hostname"))) + return con.execute("SELECT id, pulled_to FROM bucket WHERE source = ? AND bucket_id = ?", (source, bid)).fetchone() + + +def store_events(con, bucket, events): + """[(ts ms, dur s, data dict)] → upserted (the same start = the same event, grown).""" + con.executemany("INSERT INTO event (bucket, ts, dur, data) VALUES (?, ?, ?, ?) ON CONFLICT(bucket, ts) DO UPDATE " + "SET dur = excluded.dur, data = excluded.data WHERE dur IS NOT excluded.dur OR data IS NOT excluded.data", + [(bucket, ts, dur, json.dumps(data, ensure_ascii=False, separators=(",", ":"))) for ts, dur, data in events]) + + +def store_input(con, bucket, from_minute, minutes): + """Minutes ≥ from_minute replaced by `minutes` {minute: [presses, clicks, scroll, moved]}.""" + keep = [m for m in minutes if m >= from_minute] + con.execute(f"DELETE FROM input_min WHERE bucket = ? AND minute >= ? AND minute NOT IN ({','.join('?' * len(keep))})", + (bucket, from_minute, *keep)) + con.executemany("INSERT INTO input_min (bucket, minute, presses, clicks, scroll, moved) VALUES (?, ?, ?, ?, ?, ?) " + "ON CONFLICT(bucket, minute) DO UPDATE SET presses = excluded.presses, clicks = excluded.clicks, " + "scroll = excluded.scroll, moved = excluded.moved WHERE presses IS NOT excluded.presses " + "OR clicks IS NOT excluded.clicks OR scroll IS NOT excluded.scroll OR moved IS NOT excluded.moved", + [(bucket, m, *minutes[m]) for m in keep]) + + +def set_pulled(con, bucket, ts): + con.execute("UPDATE bucket SET pulled_to = max(coalesce(pulled_to, 0), ?) WHERE id = ?", (ts, bucket)) + + +def source_seen(con, name, url, **kw): + con.execute("INSERT INTO source (name, url) VALUES (?, ?) ON CONFLICT(name) DO UPDATE SET url = excluded.url", (name, url)) + if kw: + con.execute(f"UPDATE source SET {', '.join(f'{k} = ?' for k in kw)} WHERE name = ?", (*kw.values(), name)) + + +def status(con): + """Per source: what it is, the last pull, and per bucket how much is here.""" + out = [] + for s in con.execute("SELECT * FROM source ORDER BY name"): + bs = [] + for b in con.execute("SELECT * FROM bucket WHERE source = ? ORDER BY bucket_id", (s["name"],)): + if b["type"] == "os.hid.input": + r = con.execute("SELECT count(*) n, min(minute) * 60000 first, max(minute) * 60000 last FROM input_min WHERE bucket = ?", + (b["id"],)).fetchone() + else: + r = con.execute("SELECT count(*) n, min(ts) first, max(ts + dur * 1000) last FROM event WHERE bucket = ?", + (b["id"],)).fetchone() + bs.append(dict(b, n=r["n"], first=r["first"], last=r["last"])) + out.append(dict(s, buckets=bs)) + return out + + +def counts(con): + return {"categories": con.execute("SELECT count(*) FROM category").fetchone()[0], + "rules": con.execute("SELECT count(*) FROM rule").fetchone()[0]} diff --git a/dashboard/plugins/activity/defaults.py b/dashboard/plugins/activity/defaults.py new file mode 100644 index 0000000..a27d66d --- /dev/null +++ b/dashboard/plugins/activity/defaults.py @@ -0,0 +1,56 @@ +"""A starting set of categories and rules for a new Activity database, so a fresh install sorts something +before anyone opens Activity ▸ Categories & rules. Made once (meta "defaults"): deleting them all doesn't +bring them back. Everything here is editable there.""" + +# (name, colour, productive, distraction, vague, [(field, match, pattern, priority)], children) +TREE = [ + ("Work", "#2e7d32", 1, 0, 0, [], [ + ("Programming", "#43a047", 1, 0, 0, [ + ("app", "regex", r"^(code|code-oss|codium|vscodium|pycharm.*|idea.*|webstorm.*|clion.*|goland.*|android-studio|" + r"sublime_text|geany|kate|gedit|emacs|nvim|vim|zed)$", 10), + ("domain", "regex", r"(^|\.)(github\.com|gitlab\.com|bitbucket\.org|codeberg\.org|stackoverflow\.com)$", 10)], []), + ("Terminal", "#66bb6a", 1, 0, 1, [ + ("app", "regex", r"^(gnome-terminal(-server)?|konsole|alacritty|kitty|wezterm|tilix|xterm|foot|terminator|" + r"xfce4-terminal|mate-terminal|x-terminal-emulator)$", 5)], []), + ("Documents", "#81c784", 1, 0, 0, [ + ("app", "regex", r"^(libreoffice.*|soffice.*|evince|okular|xournalpp|obsidian|logseq|joplin)$", 10), + ("domain", "regex", r"^(docs\.google\.com|.*\.atlassian\.net|notion\.so|.*\.sharepoint\.com)$", 10)], []), + ("Meetings", "#a5d6a7", 1, 0, 0, [ + ("app", "regex", r"^(zoom|teams|teams-for-linux|skype)$", 10), + ("domain", "regex", r"^(meet\.google\.com|.*\.zoom\.us|teams\.microsoft\.com|meet\.jit\.si)$", 10)], []), + ]), + ("Communication", "#1e88e5", 0, 0, 0, [ + ("app", "regex", r"^(thunderbird|evolution|geary|signal|telegram-desktop|element|slack|discord|wire)$", 10), + ("domain", "regex", r"^(mail\.google\.com|outlook\.(live|office)\.com|web\.whatsapp\.com|app\.slack\.com|" + r"discord\.com|web\.telegram\.org)$", 10)], []), + ("Social & news", "#e53935", 0, 1, 0, [ + ("domain", "regex", r"(^|\.)(facebook\.com|instagram\.com|x\.com|twitter\.com|reddit\.com|tiktok\.com|" + r"linkedin\.com|news\.ycombinator\.com|mastodon\.social)$", 10)], []), + ("Video & music", "#8e24aa", 0, 1, 0, [ + ("app", "regex", r"^(vlc|mpv|totem|spotify|celluloid|jellyfinmediaplayer)$", 10), + ("domain", "regex", r"(^|\.)(youtube\.com|netflix\.com|twitch\.tv|open\.spotify\.com|primevideo\.com)$", 10)], []), + ("System", "#757575", 0, 0, 1, [ + ("app", "regex", r"^(nautilus|nemo|thunar|dolphin|gnome-control-center|cinnamon-settings|systemsettings|" + r"gnome-system-monitor|synaptic|software-properties-gtk)$", 5)], []), +] + + +def seed(con): + """Into an Activity database with no categories (and never seeded): TREE. → True when it did.""" + if con.execute("SELECT 1 FROM meta WHERE k = 'defaults'").fetchone(): + return False + if con.execute("SELECT COUNT(*) FROM category").fetchone()[0]: + con.execute("INSERT INTO meta VALUES ('defaults', 'had categories')") + return False + + def add(nodes, parent): + for name, color, prod, dist, vague, rules, kids in nodes: + cid = con.execute("INSERT INTO category (parent_id, name, color, productive, distraction, vague) " + "VALUES (?, ?, ?, ?, ?, ?)", (parent, name, color, prod, dist, vague)).lastrowid + for field, match, pattern, prio in rules: + con.execute("INSERT INTO rule (category_id, field, match, pattern, priority, origin) VALUES (?, ?, ?, ?, ?, 'default')", + (cid, field, match, pattern, prio)) + add(kids, cid) + add(TREE, None) + con.execute("INSERT INTO meta VALUES ('defaults', 'seeded')") + return True diff --git a/dashboard/plugins/activity/pull.py b/dashboard/plugins/activity/pull.py new file mode 100644 index 0000000..853bc57 --- /dev/null +++ b/dashboard/plugins/activity/pull.py @@ -0,0 +1,190 @@ +"""Pull what each computer's ActivityWatch recorded into activity.db, and the one-time import of +FlowWatch (its categories, rules and cached ActivityWatch days). + +Pull, per source and bucket: GET /api/0/buckets//events?start= — from the start of +the newest event already here, so that one (still growing: ActivityWatch merges heartbeats into +it) comes again and is replaced, and nothing before it can have changed. A computer that was away +just answers later: everything since is fetched then. Keyboard / mouse (bucket type +os.hid.input: an event a second) is summed per minute instead of kept. + + python3 -m plugins.activity.pull = … pull once (by hand) + python3 -m plugins.activity.pull --flowwatch +""" +import json +import sys +import time +import urllib.parse +import urllib.request +from datetime import datetime, timezone + +from . import db + +TIMEOUT = 20 +INPUT = "os.hid.input" + + +def _get(url): + with urllib.request.urlopen(urllib.request.Request(url, headers={"Accept": "application/json"}), timeout=TIMEOUT) as r: + return json.loads(r.read()) + + +def _ms(iso): + return int(datetime.fromisoformat(iso.replace("Z", "+00:00")).timestamp() * 1000) + + +def _iso(ms): + return datetime.fromtimestamp(ms / 1000, timezone.utc).isoformat() + + +def parse_sources(text): + """'laptop=http://192.168.1.20:5600, desktop=http://…' → [(name, url)].""" + out = [] + for part in (text or "").replace("\n", ",").split(","): + name, _, url = part.strip().partition("=") + if name.strip() and url.strip(): + out.append((name.strip(), url.strip().rstrip("/"))) + return out + + +def minutes_of(events): + """aw-watcher-input events → {UTC minute: [presses, clicks, scroll, moved]}.""" + out = {} + for ts, _dur, d in events: + m = out.setdefault(ts // 60000, [0, 0, 0.0, 0.0]) + m[0] += int(d.get("presses") or 0) + m[1] += int(d.get("clicks") or 0) + m[2] += abs(d.get("scrollX") or 0) + abs(d.get("scrollY") or 0) + m[3] += abs(d.get("deltaX") or 0) + abs(d.get("deltaY") or 0) + return out + + +def store(con, bucket, btype, since, events): + """Events of one bucket fetched from `since` (UTC ms or None) → stored; returns how many.""" + if not events: + return 0 + if btype == INPUT: # a first pull starts at its first minute (older ones: the import's) + db.store_input(con, bucket, (since or min(ts for ts, _, _ in events)) // 60000, minutes_of(events)) + else: + db.store_events(con, bucket, events) + db.set_pulled(con, bucket, max(ts for ts, _, _ in events)) + return len(events) + + +def pull_source(con, name, url): + """→ {bucket id: events fetched}; raises when the computer can't be reached.""" + now = int(time.time()) + db.source_seen(con, name, url, last_try=now) + con.commit() + try: + info = _get(f"{url}/api/0/info") + buckets = _get(f"{url}/api/0/buckets/") + except Exception as e: + db.source_seen(con, name, url, error=f"{type(e).__name__}: {e}") + con.commit() + raise + got = {} + for bid, b in buckets.items(): + row = db.bucket_row(con, name, bid, b) + since = row["pulled_to"] + q = {"limit": -1} + if since: + q["start"] = _iso(since) + raw = _get(f"{url}/api/0/buckets/{urllib.parse.quote(bid, safe='')}/events?{urllib.parse.urlencode(q)}") + events = [(_ms(e["timestamp"]), float(e.get("duration") or 0), e.get("data") or {}) for e in raw] + if since: + events = [e for e in events if e[0] >= since] + got[bid] = store(con, row["id"], b.get("type"), since, events) + con.commit() + db.source_seen(con, name, url, last_ok=now, error=None, hostname=info.get("hostname"), + device_id=info.get("device_id"), version=info.get("version")) + con.commit() + return got + + +def pull_all(path, sources): + """Every source once → {name: {bucket: n} or the error text}.""" + out = {} + con = db.connect(path) + try: + for name, url in sources: + try: + out[name] = pull_source(con, name, url) + except Exception as e: + out[name] = f"{type(e).__name__}: {e}" + finally: + con.close() + return out + + +# ---- FlowWatch, once -------------------------------------------------------------------------- + +TYPES = {"window": "currentwindow", "afk": "afkstatus", "web": "web.tab.current", "tmux": "tmux.activity", + "vscode": "app.editor.activity", "input": INPUT} + + +def _type_of(bid): + for k, t in TYPES.items(): + if f"watcher-{k}" in bid: + return t + return None + + +def import_flowwatch(fw_path, path, source): + """Categories + rules (replacing earlier FlowWatch ones) and every cached ActivityWatch day + (as source `source`'s buckets — the same names the live pull uses, so they join up).""" + import sqlite3 + fw = sqlite3.connect(f"file:{fw_path}?mode=ro", uri=True) + fw.row_factory = sqlite3.Row + con = db.connect(path) + try: + con.execute("DELETE FROM rule WHERE origin = 'flowwatch'") + ids = {} + cats = [dict(r) for r in fw.execute("SELECT * FROM category ORDER BY id")] + while cats: # parents first + later = [] + for c in cats: + if c["parent_id"] and c["parent_id"] not in ids: + later.append(c) + continue + have = con.execute("SELECT id FROM category WHERE name = ? AND parent_id IS ?", + (c["name"], ids.get(c["parent_id"]))).fetchone() + if have: + ids[c["id"]] = have[0] + else: + ids[c["id"]] = con.execute("INSERT INTO category (parent_id, name, color, productive, distraction) " + "VALUES (?, ?, ?, ?, ?)", (ids.get(c["parent_id"]), c["name"], c["color"], + int(c["is_productive"]), int(c["is_distraction"]))).lastrowid + if len(later) == len(cats): + raise ValueError("FlowWatch categories with a parent that doesn't exist") + cats = later + rules = [(ids[r["category_id"]], r["field"], r["match_type"], r["pattern"], r["priority"]) + for r in fw.execute("SELECT * FROM rule") if r["category_id"] in ids] + con.executemany("INSERT INTO rule (category_id, field, match, pattern, priority, origin) VALUES (?, ?, ?, ?, ?, 'flowwatch')", rules) + n = 0 + for r in fw.execute("SELECT bucket_id, date_key, events_json FROM aweventcache ORDER BY bucket_id, date_key"): + btype = _type_of(r["bucket_id"]) + row = db.bucket_row(con, source, r["bucket_id"], {"type": btype, "client": "flowwatch-import", "hostname": source}) + events = [(_ms(e["timestamp"]), float(e.get("duration") or 0), e.get("data") or {}) for e in json.loads(r["events_json"])] + if btype == INPUT: # whole days: add, don't replace what other days put there + for m, v in minutes_of(events).items(): + con.execute("INSERT OR REPLACE INTO input_min (bucket, minute, presses, clicks, scroll, moved) VALUES (?, ?, ?, ?, ?, ?)", + (row["id"], m, *v)) + else: + db.store_events(con, row["id"], events) + n += len(events) + con.execute("INSERT OR REPLACE INTO meta VALUES ('flowwatch_import', ?)", (datetime.now().isoformat(timespec="seconds"),)) + con.commit() + return {"categories": len(ids), "rules": len(rules), "events": n} + finally: + con.close() + fw.close() + + +if __name__ == "__main__": + a = sys.argv[1:] + if len(a) == 4 and a[0] == "--flowwatch": + print(import_flowwatch(a[1], a[2], a[3])) + elif len(a) >= 2: + print(json.dumps(pull_all(a[0], parse_sources(",".join(a[1:]))), indent=1)) + else: + sys.exit(__doc__) diff --git a/dashboard/plugins/activity/sorter.py b/dashboard/plugins/activity/sorter.py new file mode 100644 index 0000000..619e9c6 --- /dev/null +++ b/dashboard/plugins/activity/sorter.py @@ -0,0 +1,450 @@ +"""Sorting what ActivityWatch recorded into categories — on the Pi, per computer and day. + +1. Active time = the AFK watcher's "not-afk" stretches (no AFK data that day: all window time counts). +2. What was in front = window events (app, title), cut to the active time. +3. Detail on top, only where it belongs: inside a browser stretch the web watcher's tab (url, domain, + path, tab title); inside a terminal stretch tmux (session, window, pane title — Claude Code puts its + task there —, command, folder); inside VS Code its project / file / language. Those watchers send + heartbeats with gaps (tmux in May: 30 s every ~70 s), so each detail holds until the next one, at + most HOLD. A stretch is split where the detail changes; the part without any keeps just the window. +4. Each stretch gets the first matching rule: rules on the rich fields (url, domain, tmux …, vscode …) + before those on app / title / computer, higher priority first, then the older rule (FlowWatch's + order). Matching ignores case; "tmux_session" also matches the pane title (FlowWatch read that). +5. Calendar context: a stretch left unsorted or in a *vague* category (Terminal, Programming … — the + category's "vague" tick) that falls inside a calendar event takes the category of the first rule on + the event's calendar / title ("calendar equals ACME" → Acme). Cut at the event's edges. +6. Smoothing (per computer): a run shorter than `smooth` seconds between two runs of the same category + takes theirs — unless theirs is vague (a short Agenda stretch inside Terminal stays Agenda); an + unsorted short run takes its longer sorted neighbour. Distractions stay as they are (a quick look + at Reddit is real). The category before smoothing is kept (`raw`) — the day page + shows either. + +day(con, d, events) → [Slice]; summary(slices, cats, smoothed) adds up categories, items and the +unsorted list. Results are kept per day until the rules, the day's events or (today) the data change +(memo in views). +""" +import bisect +import json +import re +from datetime import datetime, time as dtime, timedelta +from urllib.parse import urlsplit + +BROWSERS = {"brave-browser", "brave", "firefox", "chromium", "google-chrome", "chrome", "opera", "vivaldi", "epiphany"} +TERMINALS = {"gnome-terminal", "gnome-terminal-server", "tilix", "kitty", "alacritty", "konsole", "xfce4-terminal", + "terminator", "wezterm", "foot", "xterm", "x-terminal-emulator", "mate-terminal"} +EDITORS = {"code", "code-oss", "vscodium", "codium"} +RICH = {"url", "domain", "path", "tab_title", "tmux_session", "tmux_window", "tmux_pane", "tmux_cmd", "tmux_path", + "vscode_project", "vscode_file", "language"} +CONTEXT = {"calendar", "event"} # the calendar event around a stretch (step 5) +FIELDS = sorted(RICH | CONTEXT | {"app", "title", "source"}) +SMOOTH = 120 # seconds; runs shorter than this are smoothed +GAP = 60000 # ms; closer than this = next to each other +HOLD = 5 * 60000 # ms; a tab / pane / file lasts until the next one, this long at most +MATCHES = ("contains", "equals", "regex") + + +def _kind(btype, bid): + t = (btype or "") + " " + bid + for k, words in (("afk", ("afkstatus", "watcher-afk")), ("window", ("currentwindow", "watcher-window")), + ("web", ("web.tab", "watcher-web")), ("tmux", ("tmux",)), ("vscode", ("editor", "vscode"))): + if any(w in t for w in words): + return k + return None + + +def day_bounds(d): + a = datetime.combine(d, dtime.min) + return int(a.timestamp() * 1000), int((a + timedelta(days=1)).timestamp() * 1000) + + +def _events(con, source, a, z): + """{kind: [(start, end, data)]} of one computer, overlapping [a, z) ms, cut to it, sorted.""" + out = {} + for b in con.execute("SELECT id, bucket_id, type FROM bucket WHERE source = ?", (source,)): + k = _kind(b["type"], b["bucket_id"]) + if not k: + continue + for e in con.execute("SELECT ts, dur, data FROM event WHERE bucket = ? AND ts >= ? AND ts < ? ORDER BY ts", + (b["id"], a - 86400000, z)): + s, t = e["ts"], e["ts"] + int(e["dur"] * 1000) + if t > a and t > s: + out.setdefault(k, []).append((max(s, a), min(t, z), json.loads(e["data"]))) + for k in out: + out[k].sort(key=lambda x: x[0]) + return out + + +def _active(afk): + spans = sorted((s, t) for s, t, d in afk if d.get("status") == "not-afk") + merged = [] + for s, t in spans: + if merged and s <= merged[-1][1]: + merged[-1][1] = max(merged[-1][1], t) + else: + merged.append([s, t]) + return merged + + +def _clip(events, spans): + """Events cut to the spans (both sorted).""" + out, j = [], 0 + for s, t, d in events: + while j < len(spans) and spans[j][1] <= s: + j += 1 + k = j + while k < len(spans) and spans[k][0] < t: + a, z = max(s, spans[k][0]), min(t, spans[k][1]) + if z > a: + out.append((a, z, d)) + k += 1 + return out + + +def _split(s, t, events, starts): + i = max(0, bisect.bisect_right(starts, s) - 1) + out, cur = [], s + while i < len(events) and events[i][0] < t: + a, z, d = events[i] + a, z = max(a, s), min(z, t) + if z > a and z > cur: + a = max(a, cur) + if a > cur: + out.append((cur, a, None)) + out.append((a, z, d)) + cur = z + i += 1 + if cur < t: + out.append((cur, t, None)) + return out + + +def _signals(source, win, extra, kind): + sig = {"source": source, "app": win.get("app") or "", "title": win.get("title") or ""} + if extra and kind == "web": + url = extra.get("url") or "" + u = urlsplit(url) + host = (u.hostname or "").removeprefix("www.") + sig.update(url=url, domain=host, path=u.path or "", tab_title=extra.get("title") or "") + elif extra and kind == "tmux": + sig.update(tmux_session=extra.get("session_name") or extra.get("session") or "", tmux_window=extra.get("window_name") or "", + tmux_pane=extra.get("pane_title") or "", tmux_cmd=extra.get("pane_current_command") or "", + tmux_path=extra.get("pane_current_path") or "") + elif extra and kind == "vscode": + sig.update(vscode_project=extra.get("project") or "", vscode_file=extra.get("file") or "", language=extra.get("language") or "") + return sig + + +def _hold(events): + """Heartbeat events stretched to the next one's start (at most HOLD past their own end).""" + out = [] + for i, (s, t, d) in enumerate(events): + nxt = events[i + 1][0] if i + 1 < len(events) else t + out.append((s, max(t, min(nxt, t + HOLD)), d)) + return out + + +def timeline(con, source, d): + """One computer's day as [(start, end, signals)].""" + a, z = day_bounds(d) + ev = _events(con, source, a, z) + win = ev.get("window", []) + if ev.get("afk"): + win = _clip(win, _active(ev["afk"])) + extra = {k: (_hold(ev.get(k, [])), [e[0] for e in ev.get(k, [])]) for k in ("web", "tmux", "vscode")} + out = [] + for s, t, w in win: + app = (w.get("app") or "").lower() + kind = "web" if app in BROWSERS else "tmux" if app in TERMINALS else "vscode" if app in EDITORS else None + if kind and extra[kind][0]: + for a2, z2, x in _split(s, t, *extra[kind]): + out.append((a2, z2, _signals(source, w, x, kind))) + else: + out.append((s, t, _signals(source, w, None, None))) + return out + + +# ---- rules ------------------------------------------------------------------------------------ + +class Rules: + """The rules, compiled; classify(signals) → (category id, rule id) or (None, None), memoised.""" + + def __init__(self, rows): + self.rich, self.plain, self.context, self.memo = [], [], [], {} + for r in sorted(rows, key=lambda r: (-r["priority"], r["id"])): + m, p = r["match"], r["pattern"] + try: + test = (re.compile(p, re.I).search if m == "regex" else + (lambda v, p=p.lower(): v.lower() == p) if m == "equals" else + (lambda v, p=p.lower(): p in v.lower())) + except re.error: + continue + fields = ("tmux_session", "tmux_pane") if r["field"] == "tmux_session" else (r["field"],) + group = self.context if r["field"] in CONTEXT else self.rich if r["field"] in RICH else self.plain + group.append((fields, test, r["category_id"], r["id"])) + + def classify(self, sig): + key = tuple(sorted(sig.items())) + if key in self.memo: + return self.memo[key] + hit = (None, None) + for group in (self.rich, self.plain): + for fields, test, cat, rid in group: + if any(sig.get(f) and test(sig[f]) for f in fields): + hit = (cat, rid) + break + if hit[0] is not None: + break + self.memo[key] = hit + return hit + + def around(self, events): + """The first context rule matching one of the events [(calendar, title)]: (category, rule, event) or None.""" + for fields, test, cat, rid in self.context: + for cal, title in events: + sig = {"calendar": cal, "event": title} + if any(sig.get(f) and test(sig[f]) for f in fields): + return cat, rid, f"{cal} · {title}" + return None + + +def load_rules(con): + return Rules([dict(r) for r in con.execute("SELECT id, category_id, field, match, pattern, priority FROM rule")]) + + +def categories(con): + """{id: {id, name, parent_id, color, productive, distraction, path}} — path = "Work › Customer › Acme".""" + cats = {r["id"]: dict(r) for r in con.execute("SELECT * FROM category")} + for c in cats.values(): + names, p, seen = [c["name"]], c["parent_id"], {c["id"]} + while p in cats and p not in seen: + seen.add(p) + names.append(cats[p]["name"]) + p = cats[p]["parent_id"] + c["path"] = " › ".join(reversed(names)) + c["top"] = p if p is None else None + return cats + + +def sources(con): + return [r[0] for r in con.execute("SELECT DISTINCT source FROM bucket ORDER BY source")] + + +class Slice: + """A stretch of one computer's time: s, t (ms), source, signals, the category (smoothed) and the one + before smoothing (raw), the rule that sorted it, and why when it wasn't a plain rule: + ("calendar", "ACME · Release planning") or ("smoothed", None).""" + __slots__ = ("s", "t", "src", "sig", "cat", "raw", "rid", "why") + + def __init__(self, s, t, src, sig, cat, rid, why=None): + self.s, self.t, self.src, self.sig, self.cat, self.raw, self.rid, self.why = s, t, src, sig, cat, cat, rid, why + + +def _context(sl, events, rules, cats): + """The slice, cut where calendar events start / end; parts inside an event re-sorted by context + rules when the slice is unsorted or vague.""" + if sl.cat is not None and not cats.get(sl.cat, {}).get("vague"): + return [sl] + inside = [e for e in events if e[0] < sl.t and e[1] > sl.s] + if not inside: + return [sl] + cuts = sorted({sl.s, sl.t} | {x for e in inside for x in e[:2] if sl.s < x < sl.t}) + out = [] + for a, z in zip(cuts, cuts[1:]): + hit = rules.around([(e[2], e[3]) for e in inside if e[0] < z and e[1] > a]) + out.append(Slice(a, z, sl.src, sl.sig, hit[0], hit[1], ("calendar", hit[2])) if hit + else Slice(a, z, sl.src, sl.sig, sl.cat, sl.rid, sl.why)) + return out + + +def _smooth(rows, cats, limit_ms): + """One computer's slices (in time order): short runs take what's around them (see the top).""" + runs = [] # [cat, s, t, [slices]] + for x in rows: + if runs and runs[-1][0] == x.cat and x.s - runs[-1][2] < GAP: + runs[-1][2] = max(runs[-1][2], x.t) + runs[-1][3].append(x) + else: + runs.append([x.cat, x.s, x.t, [x]]) + for i, (cat, s, t, members) in enumerate(runs): + if t - s >= limit_ms or (cat is not None and cats.get(cat, {}).get("distraction")): + continue + prev = runs[i - 1] if i and s - runs[i - 1][2] < GAP else None + nxt = runs[i + 1] if i + 1 < len(runs) and runs[i + 1][1] - t < GAP else None + to = None + if prev and nxt and prev[0] == nxt[0] and prev[0] is not None \ + and (cat is None or not cats.get(prev[0], {}).get("vague")): # never specific → vague + to = prev[0] + elif cat is None: + sorted_by = [r for r in (prev, nxt) if r and r[0] is not None] + if sorted_by: + to = max(sorted_by, key=lambda r: r[2] - r[1])[0] + if to is not None and to != cat: + for x in members: + x.cat, x.why = to, ("smoothed", x.why) + return rows + + +def day(con, d, rules=None, events=(), smooth=SMOOTH, cats=None): + """The day's slices, all computers, in time order. events = the day's timed calendar events + [(start ms, end ms, calendar, title)]; smooth = seconds (0 = off).""" + rules = rules or load_rules(con) + cats = categories(con) if cats is None else cats + out = [] + for src in sources(con): + rows = [] + for s, t, sig in timeline(con, src, d): + cat, rid = rules.classify(sig) + rows += _context(Slice(s, t, src, sig, cat, rid), events, rules, cats) + out += _smooth(rows, cats, smooth * 1000) if smooth else rows + out.sort(key=lambda x: x.s) + return out + + +# ---- adding up --------------------------------------------------------------------------------- + +def _task(pane): + """A pane title without Claude Code's status symbol in front (✳ idle, ⠂ ⠐ … working).""" + return re.sub(r"^[^\w(\[]+", "", pane).strip() + + +def item_of(sig): + """What a stretch was about, for lists: (kind, label) — the most telling signal.""" + if sig.get("domain"): + return "domain", sig["domain"] + if sig.get("tmux_pane") and sig["tmux_pane"] not in (sig.get("tmux_session"), "bash"): + return "tmux", _task(sig["tmux_pane"]) or sig.get("tmux_session", "") + if sig.get("tmux_session"): + return "tmux", sig["tmux_session"] + if sig.get("vscode_project"): + return "project", sig["vscode_project"].rstrip("/").rsplit("/", 1)[-1] + if (sig.get("app") or "").lower() in BROWSERS and page_of(sig): # browser time the web watcher missed + return "page", page_of(sig) + return "app", sig.get("app") or "(unknown)" + + +def page_of(sig): + """A browser window's title without the browser's name ("Inbox - Gmail - Brave" → "Inbox - Gmail").""" + return re.sub(r"\s+[-—–]\s+(Brave|Mozilla Firefox|Firefox|Chromium|Google Chrome|Vivaldi|Opera)$", "", sig.get("title") or "").strip() + + +def suggest(sig): + """A rule that would catch this unsorted stretch: (field, match, pattern).""" + if sig.get("domain"): + return "domain", "equals", sig["domain"] + if sig.get("tmux_pane") and sig["tmux_pane"] not in (sig.get("tmux_session"), "bash"): + return "tmux_pane", "contains", _task(sig["tmux_pane"]) + if sig.get("vscode_project"): + return "vscode_project", "equals", sig["vscode_project"] + if (sig.get("app") or "").lower() in BROWSERS and page_of(sig): + return "title", "contains", page_of(sig) + return "app", "equals", sig.get("app") or "" + + +def summary(slices, cats, smoothed=True): + """Totals per category (own + with sub-categories), items per category (with a rule that would + catch each — "Move to…"), per-computer strips, unsorted, and how much calendar context and + smoothing moved. smoothed=False: the categories before smoothing.""" + own, items, unsorted, strips = {}, {}, {}, {} + total = via_cal = via_smooth = 0.0 + for x in slices: + cat = x.cat if smoothed else x.raw + sec = (x.t - x.s) / 1000 + total += sec + why = x.why if smoothed or not x.why or x.why[0] != "smoothed" else x.why[1] # raw: as before smoothing + tag = None + if why and why[0] == "smoothed": + via_smooth += sec + tag, why = "smoothed", why[1] + if why and why[0] == "calendar": + via_cal += sec + tag = tag or why[1] + kind, label = item_of(x.sig) + if cat is None: + u = unsorted.setdefault((kind, label), {"kind": kind, "label": label, "sec": 0.0, "titles": {}, "rule": suggest(x.sig)}) + u["sec"] += sec + title = x.sig.get("tab_title") or x.sig.get("title") or "" + u["titles"][title] = u["titles"].get(title, 0) + sec + else: + own[cat] = own.get(cat, 0) + sec + it = items.setdefault(cat, {}).setdefault((kind, label), {"sec": 0.0, "rule": suggest(x.sig)}) + it["sec"] += sec + strip = strips.setdefault(x.src, []) + if strip and strip[-1]["cat"] == cat and x.s - strip[-1]["t"] < GAP: # same category, gap < 1 min: one block + b = strip[-1] + b["t"] = x.t + else: + b = {"s": x.s, "t": x.t, "cat": cat, "items": {}, "why": {}} + strip.append(b) + b["items"][label] = b["items"].get(label, 0) + sec + if tag: + b["why"][tag] = b["why"].get(tag, 0) + sec + rolled = dict(own) + for cid, sec in own.items(): + p = cats.get(cid, {}).get("parent_id") + seen = {cid} + while p in cats and p not in seen: + seen.add(p) + rolled[p] = rolled.get(p, 0) + sec + p = cats[p]["parent_id"] + sorted_sec = sum(own.values()) + for u in unsorted.values(): + u["titles"] = [k for k, _ in sorted(u["titles"].items(), key=lambda x: -x[1]) if k][:3] + return {"total": total, "sorted": sorted_sec, "own": own, "rolled": rolled, "via_cal": via_cal, "via_smooth": via_smooth, + "items": {c: sorted(v.items(), key=lambda x: -x[1]["sec"]) for c, v in items.items()}, + "unsorted": sorted(unsorted.values(), key=lambda u: -u["sec"]), "strips": strips} + + +def booking_group(cats, cid): + """The level time is booked at: under Work › Customer the customer (Acme, Globex), under Work its + second level (Work › General), elsewhere the top level (Personal, Media, Messengers …).""" + chain, c, seen = [], cats.get(cid), set() + while c and c["id"] not in seen: + seen.add(c["id"]) + chain.append(c) + c = cats.get(c["parent_id"]) + chain.reverse() # top first + names = [c["name"].lower() for c in chain] + depth = 3 if names[:2] == ["work", "customer"] else 2 if names[:1] == ["work"] else 1 + return chain[min(depth, len(chain)) - 1]["id"] if chain else cid + + +def blocks(slices, cats, slot_ms=15 * 60000, min_sec=180): + """The day as a few big blocks for the work week (all computers): the day cut into 15-minute slots + (the week's booking snap), each slot given to the booking group (booking_group) with the most active + time in it (at least `min_sec`; else empty), neighbouring slots of the same group joined. + [{s, t, cat (the group), main (its biggest category), sec (active seconds), top}] — top = what it + was mostly about.""" + slots = {} # slot start → {group: [sec, {cat: sec}, {item: sec}]} + for x in slices: + if x.cat is None: + continue + g = booking_group(cats, x.cat) + label = item_of(x.sig)[1] + a = x.s - x.s % slot_ms + while a < x.t: + sec = (min(x.t, a + slot_ms) - max(x.s, a)) / 1000 + if sec > 0: + e = slots.setdefault(a, {}).setdefault(g, [0.0, {}, {}]) + e[0] += sec + e[1][x.cat] = e[1].get(x.cat, 0) + sec + e[2][label] = e[2].get(label, 0) + sec + a += slot_ms + out = [] + for a in sorted(slots): + g, (sec, cs, items) = max(slots[a].items(), key=lambda kv: kv[1][0]) + if sec < min_sec: + continue + b = out[-1] if out and out[-1]["cat"] == g and out[-1]["t"] == a else None + if b is None: + b = {"s": a, "t": a, "cat": g, "sec": 0.0, "cats": {}, "items": {}} + out.append(b) + b["t"] = a + slot_ms + b["sec"] += sec + for k, v in cs.items(): + b["cats"][k] = b["cats"].get(k, 0) + v + for k, v in items.items(): + b["items"][k] = b["items"].get(k, 0) + v + for b in out: + b["main"] = max(b["cats"], key=b["cats"].get) + b["top"] = [k for k, _ in sorted(b["items"].items(), key=lambda i: -i[1])[:3]] + return out diff --git a/dashboard/plugins/activity/static/activity.css b/dashboard/plugins/activity/static/activity.css new file mode 100644 index 0000000..42e197d --- /dev/null +++ b/dashboard/plugins/activity/static/activity.css @@ -0,0 +1,127 @@ +/* Activity pages (plugins/activity). Day: totals + week, strips, category tree | unsorted. + Rules: categories (indented by depth) with their rules, edited in place. */ +/* Day | Categories & rules + Work's Week / Report buttons (right) */ +.ac-sub { display: flex; gap: 4px; align-items: center; padding: 0 16px 10px; max-width: 1500px; margin: 0 auto; box-sizing: border-box; } +.ac-work { margin-left: auto; display: flex; gap: 8px; } /* like Work's Week / Report buttons */ +.ac-sub .ac-work a { border-radius: 10px; padding: 9px 20px; background: #262d3b; color: var(--fg); font: 700 15px "DejaVu Web", sans-serif; } +.ac-sub .ac-work a:hover { background: #1d222d; color: var(--fg); } +.ac-sub a { padding: 4px 12px; border-radius: 8px; color: var(--muted); text-decoration: none; font-size: 14px; } +.ac-sub a:hover { background: #1d222d; color: var(--fg); } +.ac-sub a.on { background: #262d3b; color: var(--accent); } +.ac { display: flex; flex-direction: column; gap: 12px; padding: 0 16px 24px; max-width: 1500px; margin: 0 auto; box-sizing: border-box; } +.ac-card { background: var(--card); border-radius: 12px; padding: 12px 16px; min-width: 0; } +.ac-card h2 { margin: 0 0 10px; font: 700 15.5px "DejaVu Web", sans-serif; } +.ac-card h2 small { color: var(--dim); font-weight: 400; font-size: 13.5px; margin-left: 6px; } +.ac-none { color: var(--dim); font-size: 14px; margin: 4px 0; } +.ac-two { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 12px; align-items: start; } +@media (max-width: 999px) { .ac-two { grid-template-columns: minmax(0, 1fr); } } + +/* totals, the category bar, the week */ +.ac-top { display: grid; grid-template-columns: auto minmax(0, 1fr); gap: 10px 24px; align-items: center; } +.ac-tot { display: flex; gap: 22px; grid-row: span 2; } +.ac-tot div { display: flex; flex-direction: column; } +.ac-tot b { font: 700 28px/1.1 "DejaVu Web", sans-serif; } +.ac-tot span { color: var(--dim); font-size: 12px; text-transform: uppercase; } +.ac-bar { display: flex; height: 14px; border-radius: 7px; overflow: hidden; background: #1b1f29; } +.ac-bar i { display: block; height: 100%; } +.ac-week { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 6px; } +.ac-wd { display: flex; flex-direction: column; align-items: center; gap: 3px; padding: 4px 2px; border-radius: 8px; color: var(--muted); text-decoration: none; font-size: 12px; } +.ac-wd:hover { background: #1d222d; } .ac-wd.sel { background: #262d3b; color: var(--fg); } +.ac-wd.today .ac-wn { color: var(--accent); font-weight: 700; } .ac-wd.future { opacity: .35; } +.ac-wb { position: relative; width: 14px; height: 34px; border-radius: 4px; background: #1b1f29; overflow: hidden; } +.ac-wb s, .ac-wb u { position: absolute; left: 0; right: 0; bottom: 0; } +.ac-wb s { background: #3a4256; } .ac-wb u { background: var(--good, #7fd6a3); } +@media (max-width: 699px) { .ac-top { grid-template-columns: minmax(0, 1fr); } .ac-tot { grid-row: auto; } } + +/* per-computer strips */ +.ac-strips { padding-top: 26px; } +.ac-hours { position: relative; height: 0; margin-left: 96px; } +.ac-hours span { position: absolute; top: -18px; transform: translateX(-50%); color: var(--dim); font-size: 11.5px; } +.ac-row { display: flex; align-items: center; gap: 8px; margin: 6px 0; } +.ac-src { width: 88px; flex: none; color: var(--muted); font-size: 13px; overflow: hidden; text-overflow: ellipsis; } +.ac-track { position: relative; flex: 1; height: 22px; border-radius: 5px; background: #1b1f29; overflow: hidden; } +.ac-hl { position: absolute; top: 0; bottom: 0; width: 1px; background: #262d3b; } +.ac-blk { position: absolute; top: 2px; bottom: 2px; border-radius: 2px; } +.ac-blk.un { background: repeating-linear-gradient(135deg, #3a4256 0 3px, #2a3040 3px 6px); } +.ac-blk:hover { outline: 1px solid var(--fg); z-index: 1; } + +/* the category tree */ +.ac-node { margin-left: 0; } +.ac-node .ac-node { margin-left: 16px; } +.ac-node summary { display: flex; align-items: center; gap: 8px; padding: 5px 4px; border-radius: 7px; cursor: pointer; list-style: none; font-size: 14.5px; } +.ac-node summary::-webkit-details-marker { display: none; } +.ac-node summary:hover { background: #1d222d; } +.ac-node summary i { width: 10px; height: 10px; border-radius: 3px; flex: none; } +.ac-nn { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ac-node summary b { font-variant-numeric: tabular-nums; } +.ac-flag { font-size: 9px; } .ac-flag.pr { color: var(--good, #7fd6a3); } .ac-flag.di { color: #ff9a9a; } +.ac-items { list-style: none; margin: 0 0 4px 22px; padding: 0; } +.ac-items li { display: flex; gap: 8px; align-items: baseline; padding: 2px 4px; font-size: 13px; color: var(--muted); } +.ac-k { width: 14px; flex: none; text-align: center; color: var(--dim); } +.ac-il { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.ac-items b { font-weight: 400; font-variant-numeric: tabular-nums; } + +/* unsorted */ +.ac-u { padding: 7px 0; border-top: 1px solid #222837; display: flex; flex-direction: column; gap: 5px; } +.ac-u:first-of-type { border-top: 0; } +.ac-uh { display: flex; gap: 10px; align-items: baseline; } +.ac-ul { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: default; } +.ac-uh b { font-variant-numeric: tabular-nums; } +.ac-ur { display: flex; gap: 6px; align-items: center; flex-wrap: wrap; } +.ac-rule { color: var(--dim); font-size: 12px; white-space: nowrap; } +.ac input, .ac select { font: 14px "DejaVu Web", sans-serif; color: var(--fg); background: #1d222d; border: 0; border-radius: 7px; padding: 5px 8px; min-width: 0; box-sizing: border-box; } +.ac input:focus, .ac select:focus { outline: 2px solid var(--accent); outline-offset: -1px; } +.ac .bad { outline: 2px solid #ff7a7a; outline-offset: -1px; } +.ac-pat { flex: 1 1 140px; } .ac-cat { flex: 1 1 180px; max-width: 280px; } +.ac-sort, .ac-btn, .ac-save { border: 0; border-radius: 7px; padding: 5px 12px; font: 700 13.5px "DejaVu Web", sans-serif; cursor: pointer; } +.ac-sort, .ac-save { background: var(--accent); color: var(--bg); } +.ac-btn { background: #262d3b; color: var(--accent); } +.ac-sort:disabled, .ac-save:disabled { opacity: .5; cursor: wait; } +.ac-err { color: #ff9a9a; font-size: 13px; } .ac-err:empty { display: none; } + +/* categories & rules */ +.ac-rbar { display: flex; gap: 8px; } +.ac-filter { flex: 1; max-width: 420px; } +.ac-cat-blk { padding-left: calc(var(--d) * 22px); } +.ac-cat-blk + .ac-cat-blk { border-top: 1px solid #222837; } +.ac-crow, .ac-rrow { display: flex; align-items: center; gap: 8px; padding: 5px 6px; border-radius: 7px; cursor: pointer; } +.ac-crow:hover, .ac-rrow:hover { background: #1d222d; } +.ac-crow:focus-visible, .ac-rrow:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.ac-crow i { width: 12px; height: 12px; border-radius: 3px; flex: none; } +.ac-crow b { font-size: 15px; } +.ac-cn { color: var(--dim); font-size: 12px; margin-left: auto; } +.ac-crow .ac-btn { padding: 2px 9px; font-size: 12.5px; opacity: 0; } +.ac-crow:hover .ac-btn, .ac-crow:focus-within .ac-btn { opacity: 1; } +@media (hover: none) { .ac-crow .ac-btn { opacity: 1; } } +.ac-rrow { margin-left: 20px; font-size: 13.5px; } +.ac-rf { color: var(--muted); width: 104px; flex: none; } +.ac-rm { color: var(--dim); width: 60px; flex: none; } +.ac-rrow code { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-family: "DejaVu Sans Mono", monospace; color: var(--fg); } +.ac-rp { color: var(--dim); font-size: 12px; width: 24px; text-align: right; flex: none; } +.ac-ed { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin: 4px 0 6px 20px; padding: 8px; border-radius: 9px; background: #171b24; box-shadow: inset 0 0 0 1px #2e3647; } +.ac-ed label { display: inline-flex; align-items: center; gap: 4px; color: var(--muted); font-size: 13px; } +.ac-ed .grow { flex: 1 1 200px; } +.ac-ed input[type="color"] { width: 38px; height: 30px; padding: 2px; } +.ac-ed input[type="number"] { width: 64px; } +.ac-del { border: 0; border-radius: 7px; padding: 5px 10px; background: #262d3b; color: #ff9a9a; cursor: pointer; font: 13px "DejaVu Web", sans-serif; } +.ac-del.armed { background: #8a2b2b; color: #fff; } +.ac-x { border: 0; background: none; color: var(--muted); cursor: pointer; font-size: 15px; padding: 2px 6px; } +.ac-hide { display: none !important; } + +/* folding (rules page) — ignored while the filter has text */ +.ac-fold { border: 0; background: none; color: var(--muted); cursor: pointer; width: 20px; padding: 0; font-size: 13px; transition: transform .12s; flex: none; } +.ac-fold:disabled { visibility: hidden; } +.ac-cat-blk.open > .ac-crow .ac-fold { transform: rotate(90deg); } +.ac-rules:not(.filtering) .ac-cat-blk.ac-out { display: none; } +.ac-rules:not(.filtering) .ac-cat-blk:not(.open) .ac-rrow { display: none; } +.ac-flag.va { color: var(--muted); font-size: 11px; } + +/* Smoothed | Raw */ +.ac-mode { display: flex; align-self: end; background: #1b1f29; border-radius: 8px; padding: 2px; } +.ac-mode a { padding: 3px 10px; border-radius: 6px; color: var(--muted); text-decoration: none; font-size: 13px; } +.ac-mode a.on { background: #262d3b; color: var(--accent); } + +/* category tree items: click = Move to… */ +.ac-item { cursor: pointer; border-radius: 6px; } +.ac-item:hover, .ac-item:focus-visible { background: #1d222d; color: var(--fg); outline: 0; } +.ac-move { margin: 0 0 6px 22px; padding: 6px 8px; border-radius: 9px; background: #171b24; box-shadow: inset 0 0 0 1px #2e3647; } diff --git a/dashboard/plugins/activity/static/activity.js b/dashboard/plugins/activity/static/activity.js new file mode 100644 index 0000000..f63f4eb --- /dev/null +++ b/dashboard/plugins/activity/static/activity.js @@ -0,0 +1,194 @@ +// Activity pages. Day: "Sort" on an unsorted item makes its suggested rule (pattern editable) in +// the picked category, then the page reloads sorted; a click on an item in the category tree opens +// the same form as "Move to…" (a learned rule, priority 30: beats every other rule). Categories & rules: +// ▸ folds a category open (remembered in this browser), a click on a category or rule opens its +// editor in place (one at a time); + Rule / + Category make new ones; Delete = click twice; the +// filter narrows the list. No browser dialogs. +(function () { + const post = async (url, data) => { + const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw Object.assign(new Error(j.error || `Error ${r.status}`), { field: j.field }); + return j; + }; + const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); + const RICH = new Set(["url", "domain", "path", "tab_title", "tmux_session", "tmux_window", "tmux_pane", "tmux_cmd", "tmux_path", + "vscode_project", "vscode_file", "language"]); + + // ---- day: move an item of the category tree (a form like an unsorted one's, under it) + const choices = document.getElementById("ac-choices")?.innerHTML || ""; + function moveForm(li) { + const old = document.querySelector(".ac-move"); + const same = old && old.previousElementSibling === li; + old?.remove(); + if (same) return; + const f = document.createElement("form"); + f.className = "ac-u ac-move"; + f.dataset.field = li.dataset.field; f.dataset.match = li.dataset.match; + f.innerHTML = `
${esc(li.dataset.field.replace(/_/g, " "))} ${esc(li.dataset.match)}` + + `` + + `` + + `
` + + ``; + f.querySelector(`.ac-cat option[value="${li.dataset.cat}"]`)?.setAttribute("disabled", ""); + li.after(f); + f.querySelector(".ac-cat").focus(); + } + document.addEventListener("click", (e) => { + const li = e.target.closest(".ac-item"); + if (li) return moveForm(li); + if (e.target.closest(".ac-move .ac-x")) document.querySelector(".ac-move")?.remove(); + }); + document.addEventListener("keydown", (e) => { + if (e.key === "Enter" && e.target.classList?.contains("ac-item")) moveForm(e.target); + if (e.key === "Escape" && document.querySelector(".ac-move")) { e.stopPropagation(); document.querySelector(".ac-move").remove(); } + }); + + // ---- day: sort an unsorted item / move one + document.addEventListener("submit", async (e) => { + const f = e.target.closest(".ac-u"); + if (!f) return; + e.preventDefault(); + const cat = f.querySelector(".ac-cat"), pat = f.querySelector(".ac-pat"), err = f.querySelector(".ac-err"); + err.textContent = ""; cat.classList.remove("bad"); pat.classList.remove("bad"); + if (!cat.value) { cat.classList.add("bad"); cat.focus(); return; } + const btn = f.querySelector(".ac-sort"); + btn.disabled = true; + try { + const move = f.classList.contains("ac-move"); + await post("/activity/api/rule", { category_id: cat.value, field: f.dataset.field, match: f.dataset.match, pattern: pat.value, + priority: move ? 30 : RICH.has(f.dataset.field) ? 10 : 5, origin: move ? "learned" : "manual" }); + location.reload(); + } catch (x) { err.textContent = x.message; (x.field === "pattern" ? pat : cat).classList.add("bad"); btn.disabled = false; } + }); + + // ---- categories & rules + const dataEl = document.getElementById("ac-data"); + if (!dataEl) return; + const D = JSON.parse(dataEl.textContent); + const catOptions = (sel, none) => (none ? `` : "") + + D.order.map((id) => ``).join(""); + let open = null; // {el, hidden} + function close() { if (!open) return; open.el.remove(); open.hidden?.classList.remove("ac-hide"); open = null; } + function arm(b) { if (b.classList.contains("armed")) return true; b.classList.add("armed"); b.textContent = "Click again to delete"; return false; } + function editor(html, after, hide) { + close(); + const el = document.createElement("form"); + el.className = "ac-ed"; + el.innerHTML = html + ``; + after.after(el); + if (hide) hide.classList.add("ac-hide"); + open = { el, hidden: hide }; + el.querySelector("input, select")?.focus(); + return el; + } + function fail(el, x) { + el.querySelector(".ac-err").textContent = x.message; + const f = x.field && el.querySelector(`[name="${x.field}"]`); + if (f) { f.classList.add("bad"); f.focus(); } + } + + function ruleEditor(r, after, hide) { + const el = editor( + `` + + `` + + `` + + `` + + `` + + `${r.id ? `` : ""}` + + ``, after, hide); + el.addEventListener("submit", async (e) => { + e.preventDefault(); + const F = el.elements; + try { + await post("/activity/api/rule", { id: r.id || null, category_id: F.category_id.value, field: F.field.value, match: F.match.value, + pattern: F.pattern.value, priority: F.priority.value }); + location.reload(); + } catch (x) { fail(el, x); } + }); + el.querySelector(".ac-del")?.addEventListener("click", async (e) => { + if (!arm(e.target)) return; + try { await post("/activity/api/rule/delete", { id: r.id }); location.reload(); } catch (x) { fail(el, x); } + }); + } + + function catEditor(c, after, hide) { + const el = editor( + `` + + `` + + `` + + `` + + `` + + `` + + `${c.id ? `` : ""}` + + ``, after, hide); + el.addEventListener("submit", async (e) => { + e.preventDefault(); + const F = el.elements; + try { + await post("/activity/api/category", { id: c.id || null, name: F.name.value, parent_id: F.parent_id.value || null, + color: F.color.value, productive: F.productive.checked, distraction: F.distraction.checked, + vague: F.vague.checked }); + location.reload(); + } catch (x) { fail(el, x); } + }); + el.querySelector(".ac-del")?.addEventListener("click", async (e) => { + if (!arm(e.target)) return; + try { await post("/activity/api/category/delete", { id: c.id }); location.reload(); } catch (x) { fail(el, x); } + }); + } + + // folding: a category's rules + sub-categories show while it's open (closed by default) + let opened = new Set(); + try { opened = new Set(JSON.parse(localStorage.getItem("activity.open") || "[]").map(String)); } catch (x) { /* private mode */ } + const blks = [...document.querySelectorAll(".ac-cat-blk")]; + function fold() { + blks.forEach((b) => { + let p = b.dataset.parent, out = false; + while (p && !out) { out = !opened.has(p); p = D.cats[p]?.parent_id ? String(D.cats[p].parent_id) : ""; } + b.classList.toggle("ac-out", out); + b.classList.toggle("open", opened.has(b.dataset.id)); + b.querySelector(".ac-fold")?.setAttribute("aria-expanded", opened.has(b.dataset.id)); + }); + try { localStorage.setItem("activity.open", JSON.stringify([...opened])); } catch (x) { /* private mode */ } + } + fold(); + + document.addEventListener("click", (e) => { + const fb = e.target.closest(".ac-fold"); + if (fb) { const id = fb.closest(".ac-cat-blk").dataset.id; opened.has(id) ? opened.delete(id) : opened.add(id); return fold(); } + const fa = e.target.closest(".ac-fold-all"); + if (fa) { opened = new Set(fa.dataset.open ? blks.map((b) => b.dataset.id) : []); return fold(); } + if (e.target.closest(".ac-x")) return close(); + if (e.target.closest(".ac-ed")) return; + const add = e.target.closest(".ac-addrule"); + if (add) { const blk = add.closest(".ac-cat-blk"); return ruleEditor({ category_id: add.dataset.cat, field: "title", match: "contains", pattern: "", priority: 5 }, blk.querySelector(".ac-crow")); } + if (e.target.closest(".ac-newcat")) return catEditor({}, document.querySelector(".ac-rbar")); + const rr = e.target.closest(".ac-rrow"); + if (rr) return ruleEditor(D.rules[rr.dataset.rule], rr, rr); + const cr = e.target.closest(".ac-crow"); + if (cr) return catEditor(D.cats[cr.dataset.cat], cr, null); + }); + document.addEventListener("keydown", (e) => { + if (e.key === "Escape" && open) { e.stopPropagation(); close(); } + if (e.key === "Enter" && !open && (e.target.classList?.contains("ac-crow") || e.target.classList?.contains("ac-rrow"))) e.target.click(); + }); + + // filter: categories whose name / path, or any of whose rules, contain the text + document.querySelector(".ac-filter")?.addEventListener("input", (e) => { + const q = e.target.value.trim().toLowerCase(); + document.querySelector(".ac-rules")?.classList.toggle("filtering", !!q); // folds ignored while filtering + document.querySelectorAll(".ac-cat-blk").forEach((blk) => { + const c = D.cats[blk.dataset.id]; + let any = !q || c.path.toLowerCase().includes(q); + blk.querySelectorAll(".ac-rrow").forEach((row) => { + const r = D.rules[row.dataset.rule]; + const hit = !q || any || r.pattern.toLowerCase().includes(q) || r.field.includes(q); + row.classList.toggle("ac-hide", !hit); + any = any || (q && hit); + }); + blk.classList.toggle("ac-hide", !any); + }); + }); +})(); diff --git a/dashboard/plugins/activity/templates/activity/_head.html b/dashboard/plugins/activity/templates/activity/_head.html new file mode 100644 index 0000000..e2b1e15 --- /dev/null +++ b/dashboard/plugins/activity/templates/activity/_head.html @@ -0,0 +1,20 @@ +{# Activity pages: the core header (⌂ 📅 … ··· ‹ title › ··· ⚙ → Settings ▸ Activity), the + sub-heading, the Day | Categories & rules switch with Work's Week / Report buttons at its right end + (Activity lives inside Work: Work has an Activity button in the same spot), the stylesheet + script. #} +{% from "_header.html" import nav_btns, settings_btn, title_block, subline %} +{% macro assets() %}{% endmacro %} +{% macro script() %}{% endmacro %} +{% macro head(title, sub, current=True, center="/activity", prev=None, next=None, can_next=True) %} +
+ {{ nav_btns() }} + {{ title_block(title, center, current, prev, next, can_next=can_next, + prev_title="Day before", next_title="Day after", link_title="Today") }} + {{ settings_btn("activity") }} +
+{{ subline(sub) }} +
{# Day | Categories & rules — and back to Work's pages, where Work has its Activity button #} + {% for href, label in [("/activity", "Day"), ("/activity/rules", "Categories & rules")] %}{{ label }}{% endfor %} + WeekReport +
+{% endmacro %} +{% macro day_label(d, today) %}{% if d == today %}Today{% elif (today - d).days == 1 %}Yesterday{% else %}{{ d.strftime("%a") }} {{ d.day }} {{ d.strftime("%b") }}{% endif %}{% endmacro %} diff --git a/dashboard/plugins/activity/templates/activity/_settings.html b/dashboard/plugins/activity/templates/activity/_settings.html new file mode 100644 index 0000000..69cef89 --- /dev/null +++ b/dashboard/plugins/activity/templates/activity/_settings.html @@ -0,0 +1,40 @@ +{# Settings ▸ Activity, above the fields: each computer's ActivityWatch — reachable?, last pull, what + each bucket has sent so far — and "Pull now" (POST /activity/api/pull, then the page reloads). + Styles inline (settings page). #} + +{% macro n(x) %}{{ "{:,.0f}".format(x).replace(",", " ") if x is not none else "—" }}{% endmacro %} +
+ {% for s in sources if s.name in names %} +
+

{{ s.name }} {% if s.error %}· not reachable{% elif s.last_ok %}· ok{% endif %}

+
{{ s.url }}{% if s.version %} · ActivityWatch {{ s.version }}{% endif %} · last pull {{ ago(s.last_ok) }}{% if s.error %} · tried {{ ago(s.last_try) }}{% endif %}
+
+ + + {% for b in s.buckets %} + + {% else %}{% endfor %} + +
BucketKeptFromNewest
{{ b.bucket_id }}{{ n(b.n) }}{% if b.type == "os.hid.input" %} min{% endif %}{{ when(b.first) }}{{ when(b.last) }}
Nothing yet.
+ + {% else %} +

No computers yet

Add them below: name=address, e.g. laptop=http://192.168.1.20:5600
+ {% endfor %} +
+

Sorting

+
{{ c.categories }} categories · {{ c.rules }} rules{% if not c.categories %} — import FlowWatch's: python3 -m plugins.activity.pull --flowwatch …{% endif %}
+ +
+ diff --git a/dashboard/plugins/activity/templates/activity/day.html b/dashboard/plugins/activity/templates/activity/day.html new file mode 100644 index 0000000..5fb7372 --- /dev/null +++ b/dashboard/plugins/activity/templates/activity/day.html @@ -0,0 +1,85 @@ +{% extends "base.html" %} +{% import "activity/_head.html" as ac with context %} +{% block title %}Activity{% endblock %} +{% block head %}{{ ac.assets() }}{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{# One day, sorted (views.day): the totals + week + Smoothed | Raw, per-computer strips over the hours + that had anything (hover: what, why), the category tree (time incl. sub-categories; what it was about + inside — click one to move it: a learned rule), the unsorted list — "Sort" makes the suggested rule + (pattern editable) and the page sorts again (activity.js). #} +{% macro node(n, depth) %} +
+ {{ n.cat.name }} + {% if n.cat.productive %}●{% endif %}{% if n.cat.distraction %}●{% endif %} + {{ hm(n.sec) }} + {% if n.top %}
    {% for i in n.top %}
  • {{ {"domain": "🌐", "tmux": "▸", "project": "◇", "page": "▢", "app": "▪"}[i.kind] }}{{ i.label }}{{ hm(i.sec) }}
  • {% endfor %}
{% endif %} + {% for c in n.kids %}{{ node(c, depth + 1) }}{% endfor %} +
+{% endmacro %} +{% block page %} +{% set rq = "" if v.smoothed else "&raw=1" %} +{{ ac.head(ac.day_label(v.day, v.today), v.day.strftime("%A ") ~ v.day.day ~ v.day.strftime(" %B %Y"), v.day == v.today, + "/activity" ~ ("?raw=1" if not v.smoothed else ""), "/activity?d=" ~ v.prev.isoformat() ~ rq, + ("/activity?d=" ~ v.next.isoformat() ~ rq) if v.next else None, v.next is not none) }} + +
+
+
+
{{ hm(v.total) }}active
+
{{ v.pct }} %sorted
+ +
+ + +
+ + {% if v.strips.rows %} +
+
{% for h in v.strips.hours %}{{ h.label }}{% endfor %}
+ {% for r in v.strips.rows %} +
{{ r.source }} +
{% for h in v.strips.hours %}{% endfor %}{% for b in r.blocks %}{% endfor %}
+
+ {% endfor %} +
+ {% endif %} + +
+
+

By category{% if v.via_cal >= 60 %} {{ hm(v.via_cal) }} by calendar{% endif %}

+ {% for n in v.tree %}{{ node(n, 0) }}{% else %}

Nothing sorted {{ "yet " if v.day == v.today }}this day.

{% endfor %} +
+
+

Unsorted{% if v.total > v.sorted %} {{ hm(v.total - v.sorted) }}{% endif %}

+ {% for u in v.unsorted %} +
+
{{ u.label }}{{ hm(u.sec) }}
+
+ {{ u.field | replace("_", " ") }} {{ u.match }} + + + +
+ +
+ {% else %}

{{ "All sorted." if v.total else "Nothing recorded this day." }}

{% endfor %} + {% if v.unsorted_more %}

… and {{ v.unsorted_more }} more, smaller ones

{% endif %} +
+
+
+{% endblock %} +{% block scripts %} +{{ ac.script() }}{% endblock %} diff --git a/dashboard/plugins/activity/templates/activity/rules.html b/dashboard/plugins/activity/templates/activity/rules.html new file mode 100644 index 0000000..0798d9f --- /dev/null +++ b/dashboard/plugins/activity/templates/activity/rules.html @@ -0,0 +1,43 @@ +{% extends "base.html" %} +{% import "activity/_head.html" as ac with context %} +{% block title %}Activity — categories & rules{% endblock %} +{% block head %}{{ ac.assets() }}{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{# Every category (tree order, indented by depth) with its rules. ▸ folds a category open (its rules + + sub-categories; closed by default, remembered per browser), Open all / Close all at the top. A click + on a category or rule edits it in place; + Rule under a category, + Category at the top; the filter + box narrows the list (and opens what matches). The data for the editors is in #ac-data + (activity.js); saving reloads the page. #} +{% block page %} +{{ ac.head("Activity", v.cats | length ~ " categories · " ~ v.n_rules ~ " rules", True, "/activity") }} + +
+
+ + + + +
+
+ {% for c in v.cats %} +
+
+ + {{ c.name }} + {% if c.productive %}●{% endif %}{% if c.distraction %}●{% endif %}{% if c.vague %}◌{% endif %} + {{ c.rules | length or "" }} + +
+ {% for r in c.rules %} +
+ {{ r.field | replace("_", " ") }}{{ r.match }} + {{ r.pattern }}{{ r.priority }} +
+ {% endfor %} +
+ {% endfor %} +
+
+ +{% endblock %} +{% block scripts %}{{ ac.script() }}{% endblock %} diff --git a/dashboard/plugins/activity/views.py b/dashboard/plugins/activity/views.py new file mode 100644 index 0000000..0563fbb --- /dev/null +++ b/dashboard/plugins/activity/views.py @@ -0,0 +1,171 @@ +"""What the activity pages show, from sorter.py's results. + +day(): the day page — totals, the category tree with time (own + sub-categories; each item can be +moved: "Move to…"), per-computer strips over the hours that had anything (hover: what it was, why), +the unsorted list (ranked, with a suggested rule), the week strip; smoothed or raw (?raw=1). +work_blocks(): the days as big blocks for Work's week (its Activity lane). +Sorted days are remembered (Memo) until the rules, the day's calendar events or the smoothing change, +or — for today — new data was pulled. +""" +from datetime import date, datetime, timedelta + +from . import sorter + +UNSORTED_SHOWN = 30 + + +class Memo: + """Sorted days: (day) → (key, slices). Kept until the rules change, the day's events change (a pull, + or rows arriving through the sync — any day), or, today, the next pull.""" + + def __init__(self, size=60): + self.size, self.data = size, {} + + def get(self, con, d, rules_v, pulled, context): + """context(d) → (the day's events [(start ms, end ms, calendar, title)], smoothing seconds).""" + events, smooth = context(d) + a, z = sorter.day_bounds(d) + stamp = tuple(con.execute("SELECT count(*), total(dur) FROM event WHERE ts >= ? AND ts < ?", + (a - 86400000, z)).fetchone()) # sorter._events reads from a day before + key = (rules_v, pulled if d >= date.today() else None, tuple(events), smooth, stamp) + hit = self.data.get(d) + if hit and hit[0] == key: + return hit[1] + slices = sorter.day(con, d, events=events, smooth=smooth) + if len(self.data) >= self.size: + self.data.pop(next(iter(self.data))) + self.data[d] = (key, slices) + return slices + + +def hm(sec): + m = int(round(sec / 60)) + return f"{m // 60}:{m % 60:02d}" if m >= 60 else f"{m} min" + + +def _clock(ms): + return datetime.fromtimestamp(ms / 1000).strftime("%H:%M") + + +def tree(cats, rolled, own, items): + """Categories with time, as a nested list, biggest first: [{cat, sec, own, items, kids}].""" + kids = {} + for c in cats.values(): + kids.setdefault(c["parent_id"], []).append(c) + + def build(pid): + out = [] + for c in kids.get(pid, []): + sec = rolled.get(c["id"], 0) + if sec < 30: + continue + out.append({"cat": c, "sec": sec, "own": own.get(c["id"], 0), "kids": build(c["id"]), + "top": [{"kind": k, "label": label, "sec": it["sec"], "field": it["rule"][0], "match": it["rule"][1], + "pattern": it["rule"][2]} for (k, label), it in items.get(c["id"], [])[:6]]}) + return sorted(out, key=lambda x: -x["sec"]) + return build(None) + + +def strips(sm, cats, slices): + """Per computer: blocks over the hours that had anything (whole hours), as % of that span.""" + if not slices: + return {"hours": [], "rows": []} + a = min(x.s for x in slices) + z = max(x.t for x in slices) + h0 = datetime.fromtimestamp(a / 1000).replace(minute=0, second=0, microsecond=0) + h1 = datetime.fromtimestamp(z / 1000).replace(minute=0, second=0, microsecond=0) + timedelta(hours=1) + lo, hi = h0.timestamp() * 1000, h1.timestamp() * 1000 + span = hi - lo + rows = [] + for src, blocks in sorted(sm["strips"].items()): + bs = [] + for b in blocks: + s, t, c = b["s"], b["t"], cats.get(b["cat"]) + tip = [f"{_clock(s)}–{_clock(t)} · {c['path'] if c else 'Unsorted'} · {hm((t - s) / 1000)}"] + tip += [f" {label} · {hm(sec)}" for label, sec in sorted(b["items"].items(), key=lambda i: -i[1])[:4]] + tip += [f"{'smoothed' if k == 'smoothed' else 'calendar: ' + k} · {hm(sec)}" for k, sec in b["why"].items() if sec >= 30] + bs.append({"left": (s - lo) / span * 100, "width": max(0.15, (t - s) / span * 100), + "color": c["color"] if c else None, "tip": "\n".join(tip)}) + rows.append({"source": src, "blocks": bs}) + n = int((h1 - h0).total_seconds() // 3600) + step = 1 if n <= 8 else 2 if n <= 16 else 3 + hours = [{"left": i / n * 100, "label": (h0 + timedelta(hours=i)).strftime("%H")} for i in range(0, n + 1, step)] + return {"hours": hours, "rows": rows} + + +def day(con, memo, d, rules_v, pulled, today, context, smoothed=True): + cats = sorter.categories(con) + slices = memo.get(con, d, rules_v, pulled, context) + sm = sorter.summary(slices, cats, smoothed) + roots = sorted(((cats[c], s) for c, s in sm["rolled"].items() if c in cats and cats[c]["parent_id"] is None), key=lambda x: -x[1]) + total = sm["total"] or 1 + bar = [{"cat": c, "sec": s, "pct": s / total * 100} for c, s in roots] + if sm["total"] - sm["sorted"] > 30: + bar.append({"cat": None, "sec": sm["total"] - sm["sorted"], "pct": (sm["total"] - sm["sorted"]) / total * 100}) + mon = d - timedelta(days=d.weekday()) + week = [] + for i in range(7): + x = mon + timedelta(days=i) + if x > today: + week.append({"d": x, "future": True}) + continue + s2 = sorter.summary(memo.get(con, x, rules_v, pulled, context), cats, smoothed) + week.append({"d": x, "sec": s2["total"], "sorted": s2["sorted"], "sel": x == d, "today": x == today}) + peak = max([w.get("sec", 0) for w in week] + [1]) + for w in week: + w["h"] = round(w.get("sec", 0) / peak * 100) + w["sh"] = round(w.get("sorted", 0) / peak * 100) + unsorted = sm["unsorted"][:UNSORTED_SHOWN] + for u in unsorted: + u["field"], u["match"], u["pattern"] = u.pop("rule") + return {"day": d, "today": today, "prev": d - timedelta(days=1), "next": d + timedelta(days=1) if d < today else None, + "total": sm["total"], "sorted": sm["sorted"], "pct": round(sm["sorted"] / total * 100) if sm["total"] else 0, + "bar": bar, "tree": tree(cats, sm["rolled"], sm["own"], sm["items"]), "strips": strips(sm, cats, slices), + "unsorted": unsorted, "unsorted_more": max(0, len(sm["unsorted"]) - UNSORTED_SHOWN), + "week": week, "choices": sorted(cats.values(), key=lambda c: c["path"].lower()), + "smoothed": smoothed, "via_cal": sm["via_cal"], "via_smooth": sm["via_smooth"]} + + +def work_blocks(con, memo, d0, d1, rules_v, pulled, context): + """Days d0 … d1 (dates, inclusive, not after today) as big blocks for Work's week: + {iso: [{start, end ("HH:MM"), a, b (minutes since midnight), cat, path, names, color, top, dur}]} — per + booking group (sorter.booking_group: a customer, Work › General, Personal …); names = its biggest + category and that one's parents, nearest first (Work matches them to its customers).""" + cats = sorter.categories(con) + out, d = {}, d0 + while d <= min(d1, date.today()): + midnight = datetime.combine(d, datetime.min.time()).timestamp() * 1000 + rows = [] + for b in sorter.blocks(memo.get(con, d, rules_v, pulled, context), cats): + c, main = cats.get(b["cat"]), cats.get(b["main"]) + if not c: + continue + names, p = [], main or c # the guess goes by its biggest part (Rocket inside Acme) + while p: + names.append(p["name"]) + p = cats.get(p["parent_id"]) + a, z = (b["s"] - midnight) / 60000, min(1440, (b["t"] - midnight) / 60000) + rows.append({"start": _clock(b["s"]), "end": "24:00" if z >= 1440 else _clock(b["t"]), "a": a, "b": z, + "cat": c["id"], "path": (main or c)["path"], "name": c["name"], "names": names, "color": c["color"], + "top": b["top"], "dur": hm(b["sec"])}) + out[d.isoformat()] = rows + d += timedelta(days=1) + return out + + +def rules_page(con): + cats = sorter.categories(con) + rules = {} + for r in con.execute("SELECT * FROM rule ORDER BY priority DESC, id"): + rules.setdefault(r["category_id"], []).append(dict(r)) + order = sorted(cats.values(), key=lambda c: c["path"].lower()) + parents = {c["parent_id"] for c in order} + for c in order: + c["depth"] = c["path"].count(" › ") + c["rules"] = rules.get(c["id"], []) + c["has_kids"] = c["id"] in parents + data = {"fields": sorter.FIELDS, "matches": sorter.MATCHES, + "cats": {c["id"]: {k: c[k] for k in ("id", "name", "path", "parent_id", "color", "productive", "distraction", "vague")} for c in order}, + "order": [c["id"] for c in order], + "rules": {r["id"]: r for c in order for r in c["rules"]}} + return {"cats": order, "data": data, "n_rules": sum(len(v) for v in rules.values())} diff --git a/dashboard/plugins/calendar/__init__.py b/dashboard/plugins/calendar/__init__.py new file mode 100644 index 0000000..37d0450 --- /dev/null +++ b/dashboard/plugins/calendar/__init__.py @@ -0,0 +1,155 @@ +"""Calendar (built in): Nextcloud (CalDAV) + ICS subscriptions + the Local calendar (cal.py: +change detection, all history kept, repeats expanded locally, reminders from VALARMs). + + /week?w=N, /month?m=N the week and month pages + /api/reminders reminders firing in the next 24 h (dash.js dings + opens the card) + /api/calendars calendars a new event can go to + /api/events POST: create an event; /api/events/delete (Local only) + /api/calendars/reload POST: sync now (Settings ▸ Calendar) + +Also the Home's birthdays + next-event cards ("side"), Upcoming ("up") and the day view +("day") with the info cards' data, the 3.5" Calendar screen and the 3.5" Home's agenda, +and for the other plugins provide("events_between") (ctx.events_between: Workload's ghosts). +Settings ▸ Calendar is one of the Settings page's own panes (settings_tab). +""" +from datetime import datetime, timedelta + +from flask import abort, g, jsonify, render_template, request + +import auth + +from . import cal, screens, views + +CAL_SVG = {"viewBox": "-12 -12 24 24", + "d": "M-8 -8.5 H8 A2.5 2.5 0 0 1 10.5 -6 V8 A2.5 2.5 0 0 1 8 10.5 H-8 A2.5 2.5 0 0 1 -10.5 8 V-6 A2.5 2.5 0 0 1 -8 -8.5 Z " + "M-8 -3 V8 H8 V-3 Z M-6.5 -11.5 H-3.5 V-6 H-6.5 Z M3.5 -11.5 H6.5 V-6 H3.5 Z M-6 -1 H-2 V3 H-6 Z"} +META = { + "title": "Calendar", + "glyph": "📅", + "glyph_svg": CAL_SVG, + "description": "Nextcloud + subscribed calendars: the week and month pages, the Home's day view, birthdays, " + "Upcoming and reminders, the 3.5\" agenda.", + "default_on": True, + "settings_tab": "calendar", + "links": [{"label": "Week", "href": "/week"}, {"label": "Month", "href": "/month"}], + "sync": {"local.db": {"event": {"key": "'ev:' || NEW.uid"}}}, # the Local calendar (cal.local_setup) +} + + +def register(ctx): + store = ctx.store + views._Details.cfg = store.cfg # the info card's Edit links need the URLs + cal.local_setup(ctx.data_path("local.db")) + ctx.worker(lambda c: cal.calendar_worker(store)) + ctx.template_globals(SCALE=views.SCALE) # the day view's time axis (dash.js reads it from ) + bp = ctx.blueprint("") + ctx.warm("/week", "/month") + ctx.nav("Calendar", "/week", also=["/month"]) + + def events_between(start, end): + return [{"title": e["title"], "start": e["start"], "end": e["_until"], "all_day": e["all_day"], + "colour": e.get("cal_color"), "calendar": e.get("cal_name", "")} + for e in cal.mine(cal.events_between(store, start, end))] + ctx.provide("events_between", events_between) + ctx.provide("status", lambda: store.cal_status) + + def home_view(): # once per Home request: the parts share the info cards' ids + if "cal_home" not in g: + g.cal_home = views.home(store) + return g.cal_home + ctx.home("side", lambda: render_template("calendar/_home_side.html", v=home_view())) + ctx.home("up", lambda: render_template("calendar/_home_up.html", v=home_view())) + ctx.home("day", lambda: render_template("calendar/_home_day.html", v=home_view())) + ctx.home("evdata", lambda: render_template("calendar/_evdata.html", details=home_view()["details"])) + + ctx.screen("Cal", screens.icon, screens.screen, key=lambda ch: screens.key(store, ch), + on_open=lambda: setattr(store, "cal_page", 0), order=30) + ctx.home_screen("agenda", screens.home_agenda) + + @bp.route("/week") + def week(): + try: + offset = max(-52, min(52, int(request.args.get("w", 0)))) + except ValueError: + offset = 0 + return render_template("calendar/week.html", v=views.week(store, offset), page="week") + + @bp.route("/month") + def month(): + try: + offset = int(request.args.get("m", 0)) + except ValueError: + offset = 0 + return render_template("calendar/month.html", v=views.month(store, offset), page="month") + + @bp.route("/api/reminders") + def api_reminders(): + if "demo" in request.args: # ?demo-reminder on a page -> test the ding + return jsonify(views.demo_reminder(store)) + return jsonify(views.reminders(store)) + + def targets(): # where this viewer may add events + if not auth.can_create(): + return [] + return [t for t in store.cal_targets if auth.calendar_ok(t["name"])] + + @bp.route("/api/calendars") + def api_calendars(): + return jsonify(targets()) + + @bp.route("/api/events", methods=["POST"]) + def api_create(): + if not ctx.same_origin(): + abort(403) + d = request.get_json(silent=True) or {} + title = str(d.get("title") or "").strip()[:200] + try: + all_day = bool(d.get("all_day")) + day = datetime.strptime(d.get("date", ""), "%Y-%m-%d") + if all_day: + start = day + end = datetime.strptime(d.get("end_date") or d["date"], "%Y-%m-%d") + else: + start = datetime.strptime(f"{d['date']} {d['start']}", "%Y-%m-%d %H:%M") + end = datetime.strptime(f"{d['date']} {d['end']}", "%Y-%m-%d %H:%M") + if end <= start: # e.g. 23:00 – 01:00: ends the next day + end += timedelta(days=1) + except (KeyError, ValueError): + return jsonify(error="Check the date and times."), 400 + if not title: + return jsonify(error="Add a title."), 400 + if str(d.get("cal") or "") not in {t["id"] for t in targets()}: + return jsonify(error="You can't add events to that calendar."), 403 + if end < start: + return jsonify(error="The end is before the start."), 400 + try: + url = cal.create_event(store, str(d.get("cal") or ""), title, start, end, all_day, + str(d.get("location") or "").strip()[:300]) + except Exception as e: + print(f"calendar: create event: {type(e).__name__}: {e}", flush=True) + return jsonify(error=f"Could not save it ({type(e).__name__})."), 502 + return jsonify(open=url) + + @bp.route("/api/events/delete", methods=["POST"]) + def api_delete(): + if not ctx.same_origin(): + abort(403) + uid = str((request.get_json(silent=True) or {}).get("uid") or "") + local = (store.cfg.get("calendar") or {}).get("local_name") or "Local" + if not (auth.can_create() and auth.calendar_ok(local)): + abort(403) + return jsonify(ok=bool(uid) and cal.delete_local(store, uid)) + + @bp.route("/api/calendars/reload", methods=["POST"]) + def api_reload(): + """Sync now (Settings: "Reload from Nextcloud") and wait for it, up to 40 s.""" + if not ctx.same_origin() or not auth.is_admin(): + abort(403) + import time + t0 = store.cal_synced + store.cal_wake.set() + for _ in range(80): + if store.cal_synced > t0: + return jsonify(ok=True) + time.sleep(0.5) + return jsonify(ok=False, error=store.cal_status), 504 diff --git a/dashboard/plugins/calendar/cal.py b/dashboard/plugins/calendar/cal.py new file mode 100644 index 0000000..d2d80c4 --- /dev/null +++ b/dashboard/plugins/calendar/cal.py @@ -0,0 +1,763 @@ +"""Nextcloud / CalDAV calendar, plus ICS subscriptions. + +`calendar_worker` runs on a background thread every 5 min (2 min after a +failure) and only re-downloads what changed: + + - Nextcloud calendars: one PROPFIND lists every collection with its ctag + (change counter); a calendar is re-queried only when its ctag moved. + - Subscriptions (webcal/ICS): Nextcloud's own copy is unreliable, so the + feed is fetched straight from its source URL with If-None-Match / + If-Modified-Since (304 = unchanged). Feeds that ignore those (Google) are + downloaded but only re-parsed when the body's SHA-256 changed. + +Events are cached from the previous month's grid start to FETCH_AHEAD_DAYS +ahead (the web week / month views use them) and filtered to DISPLAY_DAYS for +Home; once every FULL_REFRESH_DAYS all caches are dropped and everything is +re-fetched, so the window never runs short. +A failing source keeps its last good events; if Nextcloud itself is +unreachable the event list is cleared and the Calendar screen shows why. +""" +import hashlib +import json +import os +import re +import sqlite3 +import time +import uuid +import xml.etree.ElementTree as ET +from datetime import date, datetime, timedelta, timezone +from contextlib import closing +from urllib.parse import quote, unquote, urljoin, urlparse + +from config import CAL_ERRORS, LOCAL_FILE + +DISPLAY_DAYS = 30 +FULL_REFRESH_DAYS = 7 +POLL_OK, POLL_FAIL = 300, 120 # seconds +LIMIT = 50 +BIRTHDAY_CAL = "contact_birthdays" # Nextcloud's auto-generated contacts calendar +LOCAL_CAL = "local" # events saved on the dashboard itself (local_setup: a synced table) + +NS = {"d": "DAV:", "c": "urn:ietf:params:xml:ns:caldav", + "cs": "http://calendarserver.org/ns/", "a": "http://apple.com/ns/ical/"} +PROPFIND_BODY = """ + + + + +""" + + +def stub_calendar(): + """Sample events shown until Nextcloud is configured.""" + now = datetime.now() + samples = [ + (timedelta(hours=2), "Team standup"), + (timedelta(days=1, hours=-3), "Dentist appointment"), + (timedelta(days=1, hours=6), "Open-source meetup — a long title to show truncation"), + (timedelta(days=2), "Send monthly invoice"), + (timedelta(days=3, hours=1), "Hike in the hills"), + (timedelta(days=5), "ChirpStack firmware update"), + ] + return [{"start": now + delta, "end": None, "all_day": False, "title": title} + for delta, title in samples] + + +def get_calendar(store): + """Upcoming events (next DISPLAY_DAYS, soonest first) from the cached list — the + viewer's calendars only (mine()).""" + now = datetime.now() + horizon = now + timedelta(days=DISPLAY_DAYS) + return mine([e for e in store.cal_events if e["_until"] > now and e["start"] < horizon])[:LIMIT] + + +def mine(events): + """Only the events of calendars the viewer may see (auth: a member's / the household's + calendars; the 3.5" screen = household; admin = all).""" + import auth + cals = auth.viewer()["calendars"] + if cals is None: + return list(events) + cals = set(cals) + return [e for e in events if e.get("cal_name") in cals] + + +def contact_kind(ev): + """'birthday' / 'anniversary' / 'death' for Nextcloud's contacts calendar + ("🎂 Name (1973)", "💍 …", "⚰️ …"), None for any other event.""" + if ev.get("cal") != BIRTHDAY_CAL: + return None + t = ev["title"].lstrip() + if t.startswith("💍"): + return "anniversary" + if t.startswith("⚰"): + return "death" + return "birthday" + + +def is_birthday(ev): + return contact_kind(ev) == "birthday" + + +def _visible(ev, c): + """calendar.show_anniversaries / show_death_dates (both default off).""" + kind = contact_kind(ev) + if kind == "anniversary": + return c.get("show_anniversaries", False) + if kind == "death": + return c.get("show_death_dates", False) + return True + + +def birthday_name(ev): + """'🎂 Ocko (1973)' -> 'Ocko'.""" + t = ev["title"].strip().lstrip("🎂").strip() + return re.sub(r"\s*\(\d{4}\)$", "", t) or t + + +def birthday_year(ev): + """'🎂 Ocko (1973)' -> '1973', or '' when the contact has no year.""" + m = re.search(r"\((\d{4})\)\s*$", ev["title"]) + return m.group(1) if m else "" + + +def _normalize_dt(dt): + """icalendar dtstart -> naive local datetime (handles all-day dates + timezones).""" + from datetime import time as _time + if isinstance(dt, datetime): + return dt.astimezone().replace(tzinfo=None) if dt.tzinfo else dt + return datetime.combine(dt, _time(0, 0)) # all-day event (a bare date) + + +def _event(comp): + """One VEVENT (already expanded) -> event dict, or None if it has no start.""" + ds = comp.get("dtstart") + if ds is None: + return None + raw = ds.dt + all_day = isinstance(raw, date) and not isinstance(raw, datetime) + s = _normalize_dt(raw) + last = None # inclusive last day, if multi-day + until = s + timedelta(days=1) if all_day else s # when it stops being "upcoming" + de = comp.get("dtend") + if de is not None: + e_raw = de.dt + until = _normalize_dt(e_raw) + if isinstance(e_raw, date) and not isinstance(e_raw, datetime): + last = e_raw - timedelta(days=1) # all-day DTEND is exclusive + else: + e_dt = until + if e_dt.hour == 0 and e_dt.minute == 0: # ends at midnight -> prev day + e_dt -= timedelta(seconds=1) + last = e_dt.date() + elif comp.get("duration") is not None: + until = s + comp.get("duration").dt + if last is not None and last <= s.date(): + last = None # single-day -> no range + alarms = [] # reminder times (VALARM triggers) + for a in comp.walk("VALARM"): + trig = a.get("trigger") + if trig is None: + continue + if isinstance(trig.dt, timedelta): # relative: to the start (default) or end + base = until if str(trig.params.get("RELATED", "START")).upper() == "END" else s + alarms.append(base + trig.dt) + else: + alarms.append(_normalize_dt(trig.dt)) # absolute date-time + return {"start": s, "end": last, "all_day": all_day, "_until": until, "alarms": alarms, + "uid": str(comp.get("uid", "") or ""), + "title": str(comp.get("summary", "(no title)")), + # details for the web info card (kept short: they live in memory per occurrence) + "loc": str(comp.get("location", "") or "").strip()[:300], + "desc": str(comp.get("description", "") or "").strip()[:2000], + "url": str(comp.get("url", "") or "").strip()[:500]} + + +FETCH_AHEAD_DAYS = 80 # covers next month's grid even when the cache is a week old + + +def _window(): + """From the grid start of the previous month (Monday on/before its 1st) to + FETCH_AHEAD_DAYS ahead, so the web week / month views (previous, current and + next month) have their data; Home only shows DISPLAY_DAYS of it.""" + today = date.today() + prev_first = (today.replace(day=1) - timedelta(days=1)).replace(day=1) + start = datetime.combine(prev_first - timedelta(days=prev_first.weekday()), datetime.min.time()) + return start, datetime.combine(today, datetime.min.time()) + timedelta(days=FETCH_AHEAD_DAYS) + + +def _expand(ical, start, end): + """All VEVENT occurrences of one parsed calendar between start and end.""" + import recurring_ical_events + return [e for e in map(_event, recurring_ical_events.of(ical).between(start, end)) if e] + + +def _tag(events, meta, objs=None): + """Stamp which calendar the events came from (slug, name, colour, pictogram) and, + per UID, its DAV object path + whether it repeats (for the card's Edit link).""" + for e in events: + e.update(meta) + o = (objs or {}).get(e.get("uid")) + if o: + e["href"], e["repeats"] = o + moved = objs.get((e["uid"], e["start"])) # a moved occurrence: its original start + if moved: + e["orig_start"] = moved + return events + + +def _objinfo(ical, href=None): + """{uid: (href, repeats)} for the VEVENT masters of one parsed calendar/object, plus + {(uid, moved start): original start} for occurrences moved out of their series — + Nextcloud / Google identify those by the original time (RECURRENCE-ID), which the + expansion drops.""" + out, moved = {}, {} + for comp in ical.walk("VEVENT"): + uid = str(comp.get("uid", "") or "") + if not uid: + continue + rid = comp.get("recurrence-id") + if rid is None: + out.setdefault(uid, (href, bool(comp.get("rrule")))) + elif comp.get("dtstart") is not None: + moved[(uid, _normalize_dt(comp.get("dtstart").dt))] = _normalize_dt(rid.dt) + for uid_start in moved: # an exception implies a repeating series + h, _ = out.get(uid_start[0], (href, True)) + out[uid_start[0]] = (h, True) + out.update(moved) + return out + + +def edit_link(ev, cfg): + """(label, url) to edit the event where it lives, or None: Nextcloud calendars -> + its Calendar app, Google ICS feeds -> Google Calendar. Read-only ones (birthdays + from contacts, Deck, other ICS feeds like ESC) get no link.""" + import base64 + import calendar + from urllib.parse import quote + c = cfg.get("calendar") or {} + cloud = (c.get("caldav_url") or "").split("/remote.php")[0] + href = ev.get("href") + if ev.get("cal") == BIRTHDAY_CAL or ev.get("cal", "").startswith("app-generated"): + return None # generated from contacts / Deck: read-only + if href and cloud: + # /apps/calendar/edit/ redirects to *today's* view, where Calendar only has + # this week's events loaded — so open the event's own week in the full editor, + # with the occurrence's start (moved: original) as recurrence id + obj = base64.b64encode(href.encode()).decode() + when = ev.get("orig_start") or ev["start"] + # all-day: Nextcloud (ical.js) reads a floating DATE as midnight *UTC*, not local + ts = calendar.timegm(when.date().timetuple()) if ev.get("all_day") else int(when.timestamp()) + # /index.php/ works with and without Nextcloud's "pretty URLs" (front controller rewrite) + return "Edit in Nextcloud", (f"{cloud}/index.php/apps/calendar/timeGridWeek/{ev['start']:%Y-%m-%d}" + f"/edit/full/{obj}/{ts}") + gcal = ev.get("gcal") + if gcal and ev.get("uid", "").endswith("@google.com"): + eid = ev["uid"][:-len("@google.com")] + if ev.get("repeats"): # one occurrence (moved: its original time) + s = ev.get("orig_start") or ev["start"] + eid += "_" + (f"{s:%Y%m%d}" if ev.get("all_day") else + f"{datetime.fromtimestamp(s.timestamp(), timezone.utc):%Y%m%dT%H%M%SZ}") + token = base64.urlsafe_b64encode(f"{eid} {gcal}".encode()).decode().rstrip("=") + return "Open in Google Calendar", f"https://calendar.google.com/calendar/event?eid={token}&authuser={quote(gcal)}" + return None + + +FEED_COLOURS = ("#4fc3f7", "#81c784", "#ffb74d", "#f06292", "#9575cd", "#4db6ac") # feeds have no colour of their own + + +class CalendarSync: + """Per-collection cache: ctag / ETag / hash, the **raw parsed calendar** (all of + its history — a few hundred KB in total) and its occurrences expanded for the + default `_window()`. Other ranges are expanded on demand (`events_between`).""" + + def __init__(self, cfg): + import requests + c = cfg.get("calendar") or {} + self.only = c.get("calendar_name") or "" # old single-calendar filter (pre-Settings configs) + hidden = c.get("hidden_calendars") + self.hidden = set(hidden) if hidden is not None else None # names not shown (Settings) + self.no_create = set(c.get("no_create") or []) # names not offered for new events + self.icons = c.get("icons") or {} # display name -> glyph; "*" = any other + self.client = None # Nextcloud / CalDAV: optional (Settings ▸ Calendar) + if c.get("enabled") and c.get("caldav_url"): + import caldav + self.client = caldav.DAVClient(url=c["caldav_url"], username=c.get("username", ""), + password=c.get("app_password", "")) + # ICS feeds of their own (Settings ▸ Calendar ▸ Calendar feeds): [(name, url)], read like Nextcloud's subscriptions + self.feeds = [(str(f.get("name") or f["url"]), str(f["url"])) for f in c.get("feeds") or [] + if isinstance(f, dict) and f.get("url")] + self.http = requests.Session() # for ICS feeds (no Nextcloud auth) + self.errors = {} # name -> failure record (calendar_worker shares + saves it) + self.lang = c.get("feed_language") or "" # Google localises its Meet text per request + if self.lang: + self.http.headers["Accept-Language"] = self.lang + self.home = None + self.cache = {} # collection url -> dict + self.last_full = 0.0 + self.local_name = c.get("local_name") or "Local" + self.local_colour = c.get("local_color") or "#c792ea" + self.targets = [] # calendars a new event can go to, see targets() + self.collections = [] # every calendar found, shown or not (Settings) + + def shown(self, name): + if self.hidden is not None: + return name not in self.hidden + return not self.only or name == self.only + + def _list_collections(self): + """PROPFIND the calendar home: [(url, name, kind, ctag, source, colour, writable)] — none without CalDAV.""" + if self.client is None: + return [] + if self.home is None: + self.home = str(self.client.principal().calendar_home_set.url) + r = self.client.propfind(self.home, PROPFIND_BODY, depth=1) + if r.status >= 400: + raise IOError(f"PROPFIND {r.status}") + root = ET.fromstring(r.raw if isinstance(r.raw, (bytes, str)) else r.raw.encode()) + out = [] + for resp in root.findall("d:response", NS): + href = resp.findtext("d:href", namespaces=NS) + prop = resp.find("d:propstat/d:prop", NS) + rtype = prop.find("d:resourcetype", NS) if prop is not None else None + if rtype is None: + continue + if rtype.find("c:calendar", NS) is not None: + kind = "caldav" + elif rtype.find("cs:subscribed", NS) is not None: + kind = "ics" + else: + continue # home itself, inbox, trash, deleted… + name = prop.findtext("d:displayname", default="", namespaces=NS) + ctag = prop.findtext("cs:getctag", default="", namespaces=NS) + source = prop.findtext("cs:source/d:href", default="", namespaces=NS) + colour = prop.findtext("a:calendar-color", default="", namespaces=NS)[:7] + privs = {p.tag.split("}")[-1] for p in prop.findall("d:current-user-privilege-set/d:privilege/*", NS)} + comps = {c.get("name") for c in prop.findall("c:supported-calendar-component-set/c:comp", NS)} + writable = kind == "caldav" and bool(privs & {"all", "write", "write-content"}) + if writable and comps and "VEVENT" not in comps: + writable = None # writable, but takes no events (a tasks list) + out.append((urljoin(self.home, href), name, kind, ctag, source, colour, writable)) + return out + + def _fetch_caldav(self, url, ctag, entry): + if entry.get("ctag") == ctag and "ical" in entry: + return # unchanged since last time + import caldav + import icalendar + merged = icalendar.Calendar() # every object of the calendar, all history + merged.add("prodid", "-//dashboard//") + merged.add("version", "2.0") + tzids = set() + objs = {} + for obj in caldav.Calendar(client=self.client, url=url).search(event=True): + try: + ical = obj.icalendar_instance + except Exception: + continue + objs.update(_objinfo(ical, urlparse(str(obj.url)).path)) + for comp in ical.subcomponents: + if comp.name == "VTIMEZONE": + if str(comp.get("tzid")) in tzids: + continue + tzids.add(str(comp.get("tzid"))) + if comp.name in ("VEVENT", "VTIMEZONE"): + merged.add_component(comp) + entry.update(ctag=ctag, ical=merged, objs=objs, win=None) + + def _fetch_ics(self, source, entry): + import icalendar + url = source.replace("webcals://", "https://").replace("webcal://", "https://") + # a Nextcloud public calendar's *web page* / embed link → its calendar file (same token) + m = re.match(r"^(https?://.+?)/(?:index\.php/)?apps/calendar/(?:p|embed)/([A-Za-z0-9]+)", url) + if m: + url = f"{m.group(1)}/remote.php/dav/public-calendars/{m.group(2)}?export" + if self.lang and "calendar.google.com" in url: # Google ignores Accept-Language: en, + url += ("&" if "?" in url else "?") + "hl=" + self.lang # but honours ?hl= + if entry.get("url") != url: # new feed, or its URL changed + entry.clear() + entry["url"] = url + headers = {} + if entry.get("etag"): + headers["If-None-Match"] = entry["etag"] + if entry.get("lastmod"): + headers["If-Modified-Since"] = entry["lastmod"] + r = self.http.get(url, headers=headers, timeout=20) + if r.status_code == 304 and "ical" in entry: + return # server says unchanged + r.raise_for_status() + entry["etag"] = r.headers.get("ETag") + entry["lastmod"] = r.headers.get("Last-Modified") + digest = hashlib.sha256(r.content).hexdigest() + if entry.get("hash") == digest and "ical" in entry: + return # same bytes as last time + if not r.content.lstrip()[:15].upper().startswith(b"BEGIN:VCALENDAR"): + kind = "a web page" if b"= FULL_REFRESH_DAYS * 86400: + self.cache.clear() # weekly full re-download + self.last_full = time.time() + win = _window() + failed = [] + seen = set() + targets = [] + collections = self._list_collections() + for i, (name, url) in enumerate(self.feeds): # feeds of their own: like a subscription, no ctag + collections.append(("feed:" + url, name, "ics", "", url, FEED_COLOURS[i % len(FEED_COLOURS)], False)) + # the dashboard's own calendar, like a collection (its file appears with the first event) + local_ctag = _local_ctag() + collections.append((LOCAL_CAL, self.local_name, "local", local_ctag, "", self.local_colour, True)) + rows = [] + fine = set() # calendars that worked this pass + for url, name, kind, ctag, source, colour, writable in collections: + slug = url.rstrip("/").rsplit("/", 1)[-1] + g = re.search(r"calendar\.google\.com/calendar/ical/([^/]+)/", source or "") + if slug == BIRTHDAY_CAL: + edit, note = None, "birthdays from your contacts" + elif slug.startswith("app-generated"): + edit, note = None, "generated by Deck" + elif writable: + edit, note = kind if kind == "local" else "nextcloud", "" + elif g: + edit, note = "google", "" + else: + edit, note = None, ("tasks only, no events" if writable is None else + "subscription" if kind == "ics" else "") + rows.append({"name": name, "colour": colour or None, "edit": edit, "note": note, + "kind": kind, "shown": self.shown(name), "create": edit is not None + and name not in self.no_create}) + if g and edit == "google" and name not in self.no_create: # new events via Google's page + targets.append({"id": "google:" + unquote(g.group(1)), "name": name, + "colour": colour or None, "kind": "google"}) + elif edit in ("nextcloud", "local") and name not in self.no_create: + targets.append({"id": url, "name": name, "colour": colour or None, + "kind": "caldav" if edit == "nextcloud" else "local"}) + if not self.shown(name) or (kind == "local" and not ctag): + self.errors.pop(name, None) # not fetched: nothing to report + continue # hidden in Settings (or no local events yet) + seen.add(url) + entry = self.cache.setdefault(url, {}) + for attempt in (1, 2): # one quick retry: Nextcloud sometimes drops + try: # a reused connection after a big download + if kind == "caldav": + self._fetch_caldav(url, ctag, entry) + elif kind == "local": + if entry.get("ctag") != ctag: + ical = _read_local() + entry.update(ctag=ctag, ical=ical, objs=_objinfo(ical), win=None) + elif source: + self._fetch_ics(source, entry) + break + except Exception as e: # keep this source's last good data + if attempt == 2 or "Connection" not in type(e).__name__: + failed.append(name or url) + self._failed(name or url, e) + print(f"cal: {name}: {type(e).__name__}: {str(e)[:120]}", flush=True) + break + meta = {"cal": slug, "cal_name": name, + "cal_color": colour or None, "icon": self.icons.get(name, self.icons.get("*"))} + g = re.search(r"calendar\.google\.com/calendar/ical/([^/]+)/", source or "") + if g: # Google feed: its calendar id, for Edit links + meta["gcal"] = unquote(g.group(1)) + if "ical" in entry and (entry.get("win") != win or entry.get("meta") != meta): + try: # re-expand: data, window or colour changed + entry.update(events=_tag(_expand(entry["ical"], *win), meta, entry.get("objs")), + win=win, meta=meta) + except Exception as e: + failed.append(name or url) + self._failed(name or url, e, "expand") + print(f"cal: {name}: expand {type(e).__name__}: {str(e)[:120]}", flush=True) + if (name or url) not in failed: + fine.add(name or url) + for url in list(self.cache): # calendar removed in Nextcloud + if url not in seen: + del self.cache[url] + for n in fine: # working again: forget its failures + self.errors.pop(n, None) + for r in rows: + r["error"] = self.errors.get(r["name"]) + self.collections = sorted(rows, key=lambda r: (r["kind"] == "local", r["name"].lower())) + order = {"caldav": 0, "google": 1, "local": 2} + self.targets = sorted(targets, key=lambda t: (order[t["kind"]], t["name"].lower())) + events = [e for entry in self.cache.values() for e in entry.get("events", [])] + events.sort(key=lambda e: e["start"]) + sources = [(entry["meta"], entry["ical"], entry.get("objs")) for entry in self.cache.values() + if "ical" in entry and "meta" in entry] + return events, failed, sources + + +_RANGES = {} # (start, end, version) -> events, for on-demand views +_RANGES_MAX = 12 + +# Every calendar's occurrences over a long span (SPAN_BACK years back to SPAN_AHEAD ahead), +# expanded once in the background (warm_span, after each sync): expanding repeats costs the +# same ~0.3 s per calendar for a week as for 13 years (dateutil walks every rule from its +# first occurrence), so one long expansion answers every week / month in it instantly. +# Per calendar, keyed by its parsed object: only calendars whose data changed re-expand. +SPAN_BACK, SPAN_AHEAD = 10, 3 +_SPAN = {"range": None, "version": -1, "per": {}} # per: id(ical) -> (ical, meta key, events) + + +def _span_range(): + y = date.today().year + return datetime(y - SPAN_BACK, 1, 1), datetime(y + SPAN_AHEAD, 1, 1) + + +def warm_span(store): + """(Re)expand the long span for calendars that changed since the last call.""" + with store.lock: + sources, version = list(store.cal_sources), store.cal_version + rng = _span_range() + old = _SPAN["per"] if _SPAN["range"] == rng else {} + per = {} + for meta, ical, objs in sources: + mkey = json.dumps(meta, sort_keys=True, default=str) + hit = old.get(id(ical)) + if hit and hit[0] is ical and hit[1] == mkey: + per[id(ical)] = hit + continue + try: + per[id(ical)] = (ical, mkey, _tag(_expand(ical, *rng), meta, objs)) + except Exception as e: + print(f"cal: span {meta.get('cal_name')}: {type(e).__name__}", flush=True) + return # incomplete: ranges keep expanding on demand + _SPAN.update(range=rng, version=version, per=per) + + +def events_between(store, start, end): + """Events overlapping [start, end): from the default window when it covers + the range, then from the long span (warm_span) when it's current, otherwise + expanded on demand from the stored raw calendars (cached per range until the + data changes).""" + with store.lock: + win, events = store.cal_window, store.cal_events + sources, version = list(store.cal_sources), store.cal_version + if win and win[0] <= start and end <= win[1]: + return [e for e in events if e["start"] < end and e["_until"] > start] + key = (start, end, version) + span = _SPAN + if span["version"] == version and span["range"] and span["range"][0] <= start and end <= span["range"][1]: + c = store.cfg.get("calendar") or {} + out = [e for _, _, evs in span["per"].values() for e in evs + if e["start"] < end and e["_until"] > start and _visible(e, c)] + return sorted(out, key=lambda e: e["start"]) + if key not in _RANGES: + if len(_RANGES) >= _RANGES_MAX: + _RANGES.clear() + out = [] + for meta, ical, objs in sources: + try: + out += _tag(_expand(ical, start, end), meta, objs) + except Exception as e: + print(f"cal: expand {meta.get('cal_name')}: {type(e).__name__}", flush=True) + c = store.cfg.get("calendar") or {} + out = [e for e in out if _visible(e, c) and e["start"] < end and e["_until"] > start] + _RANGES[key] = sorted(out, key=lambda e: e["start"]) + return _RANGES[key] + + +def _load_errors(): + try: + with open(CAL_ERRORS) as f: + return json.load(f) + except Exception: + return {} + + +def _save_errors(errors): + tmp = CAL_ERRORS + ".tmp" + try: + with open(tmp, "w") as f: + json.dump(errors, f) + os.replace(tmp, CAL_ERRORS) + except OSError as e: + print(f"cal: errors not saved: {e}", flush=True) + + +def calendar_worker(store): + cfg = store.cfg + sync = None + while True: + if store.cal_reset: # Settings saved: new URL / login / icons / … + store.cal_reset, sync = False, None + cfg.setdefault("calendar", {}) # the Local calendar + feeds work without Nextcloud + ok = False + try: + if sync is None: + sync = CalendarSync(cfg) + sync.errors = _load_errors() # failures survive restarts and Settings saves + before = json.dumps(sync.errors, sort_keys=True) + events, failed, sources = sync.refresh() + if json.dumps(sync.errors, sort_keys=True) != before: + _save_errors(sync.errors) + store.cal_targets = sync.targets + store.cal_collections = sync.collections + store.cal_synced = time.time() + events = [e for e in events if _visible(e, cfg["calendar"])] + with store.lock: + store.cal_events = events + store.cal_window = _window() + if [id(src[1]) for src in sources] != [id(src[1]) for src in store.cal_sources] \ + or [src[0] for src in sources] != [src[0] for src in store.cal_sources]: + store.cal_sources = sources # new data -> on-demand ranges re-expand + store.cal_version += 1 + status = "ok · " + datetime.now().strftime("%H:%M") + if failed: + status += f" · {len(failed)} failed" + store.cal_status = status + ok = True + except ImportError as e: + with store.lock: + store.cal_events = [] + store.cal_status = ("install python3-caldav" if e.name == "caldav" + else f"install python3-{(e.name or '?').replace('_', '-')}") + except Exception as e: + with store.lock: + store.cal_events = [] # unavailable -> hide on Home + store.cal_status = type(e).__name__ + if ok: + try: + warm_span(store) # far weeks / months: ready before anyone asks + except Exception as e: + print(f"cal: span: {type(e).__name__}: {e}", flush=True) + store.cal_wake.wait(timeout=POLL_OK if ok else POLL_FAIL) + store.cal_wake.clear() + + +# ---- new events (web "create event": week / month / day view) ---------------------- + +# The Local calendar: dash_data/calendar/local.db, one row per event (its VEVENT as text) — synced +# between the dashboards (META "sync"), so an event made on one shows on the other. Until +# 2026-10-21 it was dash_local.ics; local_setup imports that once (→ dash_local.ics.imported). +LOCAL_DB = None +LOCAL_SCHEMA = "CREATE TABLE IF NOT EXISTS event (uid TEXT PRIMARY KEY, ics TEXT NOT NULL)" + + +def local_setup(path): + """At start-up (the plugin): the table, before the sync stamps it; an old dash_local.ics once.""" + global LOCAL_DB + LOCAL_DB = path + with closing(sqlite3.connect(path)) as c: + c.execute(LOCAL_SCHEMA) + if os.path.exists(LOCAL_FILE): + import icalendar + with open(LOCAL_FILE, "rb") as f: + old = icalendar.Calendar.from_ical(f.read()) + with c: + c.executemany("INSERT OR IGNORE INTO event (uid, ics) VALUES (?, ?)", + [(str(ev.get("uid")), ev.to_ical().decode()) for ev in old.walk("VEVENT")]) + os.replace(LOCAL_FILE, LOCAL_FILE + ".imported") + os.chmod(path, 0o600) + + +def _local(): + return closing(sqlite3.connect(LOCAL_DB, timeout=10)) + + +def _local_ctag(): + """Changes with every write (here or synced in); "" while there are no events (not fetched).""" + if not LOCAL_DB: + return "" + with _local() as c: + if not c.execute("SELECT 1 FROM event LIMIT 1").fetchone(): + return "" + return ":".join(f"{os.path.getmtime(f)}/{os.path.getsize(f)}" for f in (LOCAL_DB, LOCAL_DB + "-wal") if os.path.exists(f)) + + +def _read_local(): + import icalendar + cal = icalendar.Calendar() + cal.add("prodid", "-//dashboard//local//") + cal.add("version", "2.0") + with _local() as c: + for (ics,) in c.execute("SELECT ics FROM event ORDER BY uid"): + cal.add_component(icalendar.Event.from_ical(ics)) + return cal + + +def _vevent(title, start, end, all_day, location="", desc=""): + """A new VEVENT. Timed events are stored in UTC (converted from the Pi's local + time); all-day ones as dates with an exclusive DTEND.""" + import icalendar + ev = icalendar.Event() + ev.add("uid", f"{uuid.uuid4()}@dashboard") + ev.add("dtstamp", datetime.now(timezone.utc)) + ev.add("summary", title) + if all_day: + ev.add("dtstart", start.date()) + ev.add("dtend", end.date() + timedelta(days=1)) + else: + ev.add("dtstart", start.astimezone(timezone.utc)) + ev.add("dtend", end.astimezone(timezone.utc)) + if location: + ev.add("location", location) + if desc: + ev.add("description", desc) + return ev + + +def create_event(store, target, title, start, end, all_day, location="", desc=""): + """Create a new event in calendar `target` (an id from store.cal_targets). + start / end: naive local datetimes (all-day: the first and last day). + Returns the URL to open next, or None (local events need nothing more): + Nextcloud calendar -> saved over CalDAV, then its "Edit in Nextcloud" link; + Google feed (read-only here) -> Google Calendar's own new-event page, pre-filled; + local -> a row in the Local calendar's table (local.db).""" + import icalendar + t = next((t for t in store.cal_targets if t["id"] == target), None) + if t is None: + raise ValueError("unknown calendar") + vev = _vevent(title, start, end, all_day, location, desc) + if t["kind"] == "google": + fmt = (lambda d: f"{d:%Y%m%d}") if all_day else \ + (lambda d: f"{d.astimezone(timezone.utc):%Y%m%dT%H%M%SZ}") + stop = end + timedelta(days=1) if all_day else end + gcal = t["id"].split(":", 1)[1] + q = "&".join(f"{k}={quote(v)}" for k, v in ( + ("action", "TEMPLATE"), ("text", title), ("dates", f"{fmt(start)}/{fmt(stop)}"), + ("location", location), ("details", desc), ("src", gcal), ("authuser", gcal)) if v) + return "https://calendar.google.com/calendar/render?" + q + if t["kind"] == "local": + with _local() as c, c: + c.execute("INSERT INTO event (uid, ics) VALUES (?, ?)", (str(vev.get("uid")), vev.to_ical().decode())) + store.cal_wake.set() # re-sync now, so the views show it + return None + # Nextcloud: own DAV client (the worker thread uses the other one) + import caldav + c = store.cfg["calendar"] + client = caldav.DAVClient(url=c["caldav_url"], username=c["username"], password=c["app_password"]) + wrap = icalendar.Calendar() + wrap.add("prodid", "-//dashboard//") + wrap.add("version", "2.0") + wrap.add_component(vev) + obj = caldav.Calendar(client=client, url=t["id"]).save_event(wrap.to_ical().decode()) + store.cal_wake.set() + ev = {"href": urlparse(str(obj.url)).path, "start": start, "all_day": all_day, + "cal": t["id"].rstrip("/").rsplit("/", 1)[-1]} + link = edit_link(ev, store.cfg) + return link[1] if link else None + + +def delete_local(store, uid): + """Remove a local event (every occurrence) by UID. True if it was there.""" + with _local() as c, c: + if not c.execute("DELETE FROM event WHERE uid = ?", (uid,)).rowcount: + return False + store.cal_wake.set() + return True diff --git a/dashboard/plugins/calendar/screens.py b/dashboard/plugins/calendar/screens.py new file mode 100644 index 0000000..a8682b8 --- /dev/null +++ b/dashboard/plugins/calendar/screens.py @@ -0,0 +1,160 @@ +"""The calendar on the 3.5" panel: the agenda rows (`_agenda_rows`, shared by both), the +3.5" Home's agenda (left column, under the date) and the Calendar screen (one event a row, +paged — tap the left / right third or ← / →) — moved from the core's screens.py.""" +from datetime import date, datetime + +from config import NAV_H, THEME +from panel import draw_rich, fit_rich, fmt_event, fmt_range, ic_cal, text_r +from store import hit + +from .cal import birthday_name, get_calendar, is_birthday + +icon = ic_cal + + +def home_agenda(img, d, panel, store): + """Up to HOME_LINES rows (see _agenda_rows), stacking up to AGENDA_LAST_Y.""" + y = AGENDA_LAST_Y - (HOME_LINES - 1) * AGENDA_PITCH + for row in _agenda_rows(get_calendar(store), merge=True)[:HOME_LINES]: + _draw_agenda_row(d, panel, row, 16, y, AGENDA_RX) + y += AGENDA_PITCH + + +def key(store, ch): + """← / →: the previous / next page.""" + step = {"left": -1, "right": 1}.get(ch) + if step: + store.cal_page = (store.cal_page + step) % store.cal_pages + + +HOME_LINES = 6 +AGENDA_PITCH = 22 +AGENDA_LAST_Y = 220 # top of the 6th row; the rows stack upward from here +AGENDA_RX = 316 # agenda's right edge; weather + indoor temp sit to the right + + +def _agenda_rows(events, merge): + """Agenda rows (kind, head, items, pict), in order: + 1. today's birthdays ("bday", None, names) + 2. today's single-day all-day events ("allday", None, titles) — led by + their calendar's pictogram, or 📅 when it has none / the row mixes calendars + 3. multi-day events running today ("event", "16th – 18th", title) + 4. the upcoming events, by start ("event", "Tmrw 10:00", title) + later birthdays: ("bday", "Fri 23", names) + merge=True (Home): birthdays of one day share a row, so do today's all-day + events. merge=False (Calendar screen): one row per event. + pict = (glyph or None, colour) of the event's calendar; the colour also tints + the title. None on a merged all-day row that mixes calendars. + """ + today = date.today() + bdays, allday, ranges, rest = [], [], [], [] + later_bdays = {} # date -> its row's name list + cake = ("🎂", THEME["bday"]) # recoloured from the birthdays calendar + for ev in events: + sd, end = ev["start"].date(), ev.get("end") + pict = (ev.get("icon"), ev.get("cal_color") or THEME["fg"]) + if is_birthday(ev): + name = birthday_name(ev) + cake = ("🎂", ev.get("cal_color") or THEME["bday"]) + if sd == today: + bdays.append(name) + elif merge and sd in later_bdays: + later_bdays[sd].append(name) + else: + later_bdays[sd] = [name] + rest.append(("bday", fmt_event(ev), later_bdays[sd], cake)) + elif end is not None and end > sd and sd <= today <= end: + ranges.append(("event", fmt_range(sd, end), ev["title"], pict)) + elif sd == today and ev.get("all_day"): + allday.append((ev["title"], pict)) + else: + rest.append(("event", fmt_event(ev), ev["title"], pict)) + for names in later_bdays.values(): + names.sort(key=str.casefold) + bdays.sort(key=str.casefold) + if merge: + rows = [("bday", None, bdays, cake)] if bdays else [] + if allday: + same = len({p for _, p in allday}) == 1 + rows.append(("allday", None, [t for t, _ in allday], allday[0][1] if same else None)) + else: + rows = [("bday", None, [n], cake) for n in bdays] + rows += [("allday", None, [t], p) for t, p in allday] + return rows + ranges + rest + + +def _draw_pict(d, panel, pict, x, y): + """Calendar pictogram in its calendar's colour; returns the next x.""" + if not (pict and pict[0]): + return x + return draw_rich(d, (x, y), pict[0], panel.f["sm"], panel.emoji, pict[1]) + 5 + + +def _draw_agenda_row(d, panel, row, x, y, rx): + f, emo = panel.f["sm"], panel.emoji + kind, head, items, pict = row + if head: # "When:" in white + d.text((x, y), head + ":", font=f, fill=THEME["fg"]) + x += d.textlength(head + ":", font=f) + 6 + if kind == "event": # "When: [pict] Title", calendar colour + x = _draw_pict(d, panel, pict, x, y) + draw_rich(d, (x, y), fit_rich(d, items, f, emo, rx - x), f, emo, pict[1]) + return + if kind == "bday": # 🎂 Ana, Bob +2 — first two names, "+N" greyer; + icon, icol, shown = pict[0], pict[1], items[:2] # all in the calendar colour + tcol = icol + text = ", ".join(shown) + else: # ❤ Title +N — calendar's pictogram (or 📅) in green, + icon = pict[0] if pict and pict[0] else "📅" # first title only, in + icol, shown = THEME["allday"], items[:1] # the calendar colour + tcol = pict[1] if pict else THEME["fg"] + text = shown[0] + more = f"+{len(items) - len(shown)}" if len(items) > len(shown) else "" + tx = draw_rich(d, (x, y), icon, f, emo, icol) + 6 + mw = d.textlength(more, font=f) + 8 if more else 0 + tx = draw_rich(d, (tx, y), fit_rich(d, text, f, emo, rx - tx - mw), f, emo, tcol) + if more: + d.text((tx + 8, y), more, font=f, fill=THEME["muted"]) + + +def screen(img, d, panel, store): + rx = panel.w - 16 + d.text((16, 8), "Calendar", font=panel.f["lg"], fill=THEME["fg"]) + ok = store.cal_status.startswith("ok") + text_r(d, rx, 12, "up to date" if ok else store.cal_status, + panel.f["sm"], THEME["good"] if ok else THEME["muted"]) + text_r(d, rx, 34, datetime.now().strftime("%a %d %b"), panel.f["xs"], THEME["dim"]) + + events = get_calendar(store) + if not events: + if ok: + note = "Add events on the web pages, or a calendar in Settings ▸ Calendar" + elif store.cal_status == "install python3-caldav": + note = "Run: sudo apt install python3-caldav" + elif store.cal_status in ("", "—"): + note = "Loading…" + else: + note = f"Calendar unavailable — {store.cal_status}" + d.text((16, 84), "No upcoming events", font=panel.f["md"], fill=THEME["dim"]) + d.text((16, 116), note, font=panel.f["sm"], fill=THEME["dim"]) + return + + # same rows as Home but one per event, CAL_ROWS per page; tap the left / + # right third of the screen (or ‹/›) for the previous / next page (wrapping) + rows = _agenda_rows(events, merge=False) + store.cal_pages = pages = max(1, -(-len(rows) // CAL_ROWS)) + store.cal_page %= pages + first = store.cal_page * CAL_ROWS + y = AGENDA_LAST_Y - (CAL_ROWS - 1) * AGENDA_PITCH + for row in rows[first:first + CAL_ROWS]: + _draw_agenda_row(d, panel, row, 16, y, rx) + y += AGENDA_PITCH + text_r(d, rx, 241, f"{store.cal_page + 1}/{pages}", panel.f["xs"], THEME["muted"]) + + flip = lambda step: setattr(store, "cal_page", (store.cal_page + step) % store.cal_pages) + h, third = panel.h - NAV_H, panel.w // 3 + hit(store, (0, 0, third, h), lambda: flip(-1)) + hit(store, (panel.w - third, 0, panel.w, h), lambda: flip(1)) + + +CAL_ROWS = 8 diff --git a/dashboard/plugins/calendar/templates/calendar/_evdata.html b/dashboard/plugins/calendar/templates/calendar/_evdata.html new file mode 100644 index 0000000..f0be164 --- /dev/null +++ b/dashboard/plugins/calendar/templates/calendar/_evdata.html @@ -0,0 +1,2 @@ +{# the Home's info cards' data (dash.js opens a card from it on click) #} + diff --git a/dashboard/plugins/calendar/templates/calendar/_home_day.html b/dashboard/plugins/calendar/templates/calendar/_home_day.html new file mode 100644 index 0000000..b14429b --- /dev/null +++ b/dashboard/plugins/calendar/templates/calendar/_home_day.html @@ -0,0 +1,16 @@ +{# The Home's day view (region "day"): v = views.home. #} +{% from "calendar/_timeline.html" import timeline %} +{% set dv = v.day %} + +
{{ dv.weekday }}
+
{{ dv.date }}
+ {% if dv.pills or dv.more %} +
+ {% for p in dv.pills %} +
{% if p.range %}{{ p.range }}  {% endif %}{% if p.icon %}{{ p.icon }} {% endif %}{{ p.title }}
+ {% endfor %} + {% if dv.more %}
+{{ dv.more }} more
{% endif %} +
+ {% endif %} +
{{ timeline(dv.lines, dv.bands, dv.blocks, dv.now, labels=dv.labels, day=dv.iso) }}
+
diff --git a/dashboard/plugins/calendar/templates/calendar/_home_side.html b/dashboard/plugins/calendar/templates/calendar/_home_side.html new file mode 100644 index 0000000..2ee5f56 --- /dev/null +++ b/dashboard/plugins/calendar/templates/calendar/_home_side.html @@ -0,0 +1,23 @@ +{# The Home's birthdays + next-event cards (region "side"): v = views.home. #} +{% macro bday(p) %} +
{{ p.when }}
{{ p.name }}
{{ p.year }}
+{% endmacro %} +{% set b = v.birthdays %} +
+
+
0 %} data-ev="{{ b.people[0].id }}"{% endif %}>{% if b.people|length > 0 %}{{ bday(b.people[0]) }}{% else %}
No birthdays
{% endif %}
+
🎂
+
1 %} data-ev="{{ b.people[1].id }}"{% endif %}>{% if b.people|length > 1 %}{{ bday(b.people[1]) }}{% endif %}
+
+
+ {% for c in v.cards %} +
+ {% if c.empty %}
{{ c.empty }}
+ {% else %} +
{{ c.when }}
+
{% if c.icon %}{{ c.icon }} {% endif %}{{ c.title }}
+ {% endif %} +
+ {% endfor %} +
+
diff --git a/dashboard/plugins/calendar/templates/calendar/_home_up.html b/dashboard/plugins/calendar/templates/calendar/_home_up.html new file mode 100644 index 0000000..851c738 --- /dev/null +++ b/dashboard/plugins/calendar/templates/calendar/_home_up.html @@ -0,0 +1,11 @@ +{# The Home's Upcoming list (region "up"): v = views.home. #} + +
Upcoming
+
+ {% for r in v.upcoming %} +
{{ r.date }}
+
{{ r.time }}
+
{% if r.icon %}{{ r.icon }} {% endif %}{{ r.title }}
+ {% endfor %} +
+
diff --git a/dashboard/plugins/calendar/templates/calendar/_timeline.html b/dashboard/plugins/calendar/templates/calendar/_timeline.html new file mode 100644 index 0000000..f2546ff --- /dev/null +++ b/dashboard/plugins/calendar/templates/calendar/_timeline.html @@ -0,0 +1,25 @@ +{# One day's timeline, positioned in % of its box (see webview._timeline_blocks). + lines / labels / bands / blocks / now come from webview; `labels` is only + passed where the hour numbers belong (day view, first week column). #} +{% macro timeline(lines, bands, blocks, now, labels=None, band_labels=True, tick=True, dot_at_edge=False, day=None) %} +
+ {% for b in bands %} +
+ {% if band_labels %}{{ b.label }}{% endif %} +
+ {% endfor %} + {% for y in lines %}
{% endfor %} + {% if labels %}{% for l in labels %}
{{ l.text }}
{% endfor %}{% endif %} + {% for e in blocks %} +
+ {% if e.font %}
{{ e.time }} {% if e.icon %}{{ e.icon }} {% endif %}{{ e.title }}
{% endif %} +
+ {% endfor %} + {% if 0 <= now <= 100 %} +
+ {% endif %} +
+{% endmacro %} diff --git a/dashboard/plugins/calendar/templates/calendar/month.html b/dashboard/plugins/calendar/templates/calendar/month.html new file mode 100644 index 0000000..a85a2c7 --- /dev/null +++ b/dashboard/plugins/calendar/templates/calendar/month.html @@ -0,0 +1,37 @@ +{% extends "base.html" %} +{% from "_header.html" import header %} +{% block title %}{{ v.title }} · Dashboard{% endblock %} +{% block page %} +{{ header(v.title, v.sub, v.current, "/month?m=" ~ (v.offset - 1), "/month?m=" ~ (v.offset + 1), + "month", "/month", v.can_prev, v.can_next) }} +
+
+ {% for c in v.cols %} +
{{ c.label }}
+ {% endfor %} +
+ {% for r in v.rows %} +
+ {% for c in r.cells %} + +
{{ c.num }}
+
+ {% for i in c.evs %} +
{{ i.time }} {% if i.icon %}{{ i.icon }} {% endif %}{{ i.title }}
+ {% endfor %} + {% if c.more %}
+{{ c.more }} more
{% endif %} +
+
+ {% endfor %} + {% for b in r.bars %} +
{% if b.icon %}{{ b.icon }} {% endif %}{{ b.title }}
+ {% endfor %} +
+ {% endfor %} +
+
+
+{% endblock %} diff --git a/dashboard/plugins/calendar/templates/calendar/week.html b/dashboard/plugins/calendar/templates/calendar/week.html new file mode 100644 index 0000000..f6c8295 --- /dev/null +++ b/dashboard/plugins/calendar/templates/calendar/week.html @@ -0,0 +1,33 @@ +{% extends "base.html" %} +{% from "calendar/_timeline.html" import timeline %} +{% from "_header.html" import header %} +{% block title %}CW {{ v.cw }} · Dashboard{% endblock %} +{% block page %} +{{ header("CW " ~ v.cw, v.range, v.offset == 0, "/week?w=" ~ (v.offset - 1), "/week?w=" ~ (v.offset + 1), "week", "/week") }} + +{# .wk scrolls sideways on narrow screens; .wk-in keeps the seven columns readable #} +
+
+
+ {% for c in v.cols %} +
{{ c.label }}
+ {% if not loop.first %}
{% endif %} + {% endfor %} + {% for b in v.bars %} +
{% if b.icon %}{{ b.icon }} {% endif %}{{ b.title }}
+ {% endfor %} +
+ {% for c in v.cols %} +
+ {{ timeline(v.lines, c.bands, c.blocks, c.now, labels=v.labels if loop.first else None, + band_labels=False, tick=loop.first, dot_at_edge=True, day=c.day.isoformat()) }} +
+ {% endfor %} +
+
+
+
+{% endblock %} diff --git a/dashboard/plugins/calendar/views.py b/dashboard/plugins/calendar/views.py new file mode 100644 index 0000000..20ccdf3 --- /dev/null +++ b/dashboard/plugins/calendar/views.py @@ -0,0 +1,534 @@ +"""View models of the calendar plugin: the Home parts (birthdays, next-event cards, +Upcoming, the day view), the week and month pages, reminders — plain dicts for the +templates, timeline geometry in % (moved here from the core's webview.py). +""" +from datetime import datetime, timedelta + +from config import THEME +from panel import _day_label, _ordinal, fmt_range +from webview import BANDS, _band + +from .cal import (LOCAL_CAL, birthday_name, birthday_year, edit_link, events_between, get_calendar, mine, + is_birthday) + +# day view: (from hour, to hour, height per hour relative to working hours) +SCALE = ((0, 7, 0.2), (7, 9, 0.5), (9, 18, 1.0), (18, 24, 0.5)) +# calendars that get their own "next event" card under the birthdays (and are left +# out of Upcoming); overridable with calendar.card_calendars +CARD_CALENDARS = () # Settings ▸ Calendar ▸ Home cards picks them +PAST_TINT = 0.2 # past timed events are filled with 20 % of their colour +WEEK_WEIGHT = {"work": 1.0, "weekend": 0.66, "today_extra": 0.2} +MAX_PILLS = 4 # day view: all-day one-liners before "+N more" +MAX_LANES = 4 # week view: lanes of all-day bars +PAST_BAR_MIX = 0.5 # past all-day / birthday bars (week + month): colour mixed half into the card grey + + +# ---- rules (time axis, colours, which events go where) ---------------------------- + +def hour_to_y(h, top, bottom): + """Hour of day (0..24, float) -> y on the day view's non-linear axis.""" + total = sum((b - a) * w for a, b, w in SCALE) + acc = 0.0 + for a, b, w in SCALE: + if h <= b: + acc += (h - a) * w + break + acc += (b - a) * w + return top + (bottom - top) * acc / total + + +def _ink_on(colour): + """Readable text colour on top of a filled `colour` block.""" + c = (colour or THEME["fg"]).lstrip("#") + r, g, b = (int(c[i:i + 2], 16) for i in (0, 2, 4)) + return THEME["ink"] if 0.299 * r + 0.587 * g + 0.114 * b > 140 else "#ffffff" + + +def _mix(a, b, t): + """Blend hex colour a toward b by t (0..1) -> hex.""" + pa = [int(a.lstrip("#")[i:i + 2], 16) for i in (0, 2, 4)] + pb = [int(b.lstrip("#")[i:i + 2], 16) for i in (0, 2, 4)] + return "#" + "".join(f"{round(x + (y - x) * t):02x}" for x, y in zip(pa, pb)) + + +def _long_date(d): + """'23rd October'.""" + return f"{_ordinal(d.day)} {d:%B}" + + +def _is_allday(e): + return e.get("all_day") or (e.get("end") and e["end"] > e["start"].date()) + + +def _ev_key(e): + return (e.get("cal"), e["title"], e["start"]) + + +def shown_on_cards(upcoming, cards): + """Keys of the events the side cards already show — the next two birthdays and + the next event of each card calendar. Only those stay out of Upcoming.""" + keys = {_ev_key(e) for e in [e for e in upcoming if is_birthday(e)][:2]} + for name in cards: + e = next((e for e in upcoming if e.get("cal_name") == name), None) + if e: + keys.add(_ev_key(e)) + return keys + + +def upcoming_list(upcoming, today, shown): + """[(event, display event)] after today, minus what the cards show; later + birthdays read '🎂 Name'.""" + out = [] + for e in upcoming: + if e["start"].date() <= today or _ev_key(e) in shown: + continue + out.append((e, dict(e, title="🎂 " + birthday_name(e), icon=None) if is_birthday(e) else e)) + return out + + +def place_blocks(timed, day0): + """Overlap layout for one day's timed events: [(event, until, col, ncols, start)] + — start/until clipped to the day, at least 15 min long; overlapping events + share the width (greedy columns per cluster of overlapping events).""" + day1 = day0 + timedelta(days=1) + placed, cluster, cluster_end, ncols = [], [], None, 0 + + def flush(): + for item in cluster: + item[3] = max(ncols, 1) + placed.extend(tuple(c) for c in cluster) + + for e in sorted(timed, key=lambda e: e["start"]): + s, u = max(e["start"], day0), min(max(e["_until"], e["start"] + timedelta(minutes=15)), day1) + if cluster and s >= cluster_end: + flush() + cluster, ncols = [], 0 + used = {c[2] for c in cluster if c[1] > s} + col = next(i for i in range(len(cluster) + 1) if i not in used) + cluster.append([e, u, col, 0, s]) + ncols = max(ncols, col + 1) + cluster_end = u if cluster_end is None or len(cluster) == 1 else max(cluster_end, u) + if cluster: + flush() + return placed + + +def _week_columns(monday, today, x0, x1): + """[(day, xa, xb)] for Mon..Sun; weekends narrower, today wider.""" + days = [monday + timedelta(days=i) for i in range(7)] + w = [WEEK_WEIGHT["weekend" if dd.weekday() >= 5 else "work"] + + (WEEK_WEIGHT["today_extra"] if today is not None and dd == today else 0) for dd in days] + unit, x, cols = (x1 - x0) / sum(w), x0, [] + for dd, wi in zip(days, w): + cols.append((dd, x, x + wi * unit)) + x += wi * unit + return cols + + +# ---- event details (the click-to-open info card) --------------------------------- + +def _span(a, z): + if (a.year, a.month) == (z.year, z.month): + return f"{a:%a} {_ordinal(a.day)} – {z:%a} {_ordinal(z.day)} {z:%B}" + return f"{a:%a} {_long_date(a)} – {z:%a} {_long_date(z)}" + + +def _when(ev): + """Readable date / time span for the card.""" + s, sd, end = ev["start"], ev["start"].date(), ev.get("end") + if ev.get("all_day"): + return _span(sd, end) if end and end > sd else f"{sd:%A} {_long_date(sd)}" + u = ev["_until"] + if u.date() == sd or (u.date() == sd + timedelta(days=1) and u.hour == 0 and u.minute == 0): + return f"{sd:%A} {_long_date(sd)} · {s:%H:%M} – {u:%H:%M}" + return f"{s:%a} {_ordinal(s.day)} {s:%b} {s:%H:%M} – {u:%a} {_ordinal(u.day)} {u:%b} {u:%H:%M}" + + +class _Details: + """Per-page registry: every clickable event gets an index (data-ev="N") into + the JSON list the page embeds; dash.js opens the card from it.""" + + cfg = None # set once by web.create_app (for Edit links) + + def __init__(self): + self.items, self._ids = [], {} + + def add(self, ev): + key = (ev.get("cal"), ev["title"], ev["start"]) + if key not in self._ids: + self._ids[key] = len(self.items) + if is_birthday(ev): + name, year = birthday_name(ev), birthday_year(ev) + title, icon = name, "🎂" + extra = f"turns {ev['start'].year - int(year)}" if year else "" + else: + title, icon, extra = ev["title"], ev.get("icon"), "" + link = edit_link(ev, self.cfg) if self.cfg else None + self.items.append({"title": title, "icon": icon, "colour": _colour(ev), + "cal": ev.get("cal_name") or "", "when": _when(ev), "extra": extra, + "loc": ev.get("loc", ""), "desc": ev.get("desc", ""), "url": ev.get("url", ""), + "edit": link[1] if link else "", "edit_label": link[0] if link else "", + "local_uid": ev.get("uid", "") if ev.get("cal") == LOCAL_CAL else ""}) + return self._ids[key] + + +# ---- small helpers ------------------------------------------------------------ + +def _pct(h): + """Hour of day -> % from the top of a timeline box.""" + return round(hour_to_y(h, 0, 100), 3) + + +def _hours(dt, day0): + return (dt - day0).total_seconds() / 3600 + + +def _colour(ev): + return ev.get("cal_color") or THEME["fg"] + + +# ---- timeline (day view + every week column) ----------------------------------- + +def _grid(): + """Hour lines (every hour) and labels (none inside the compressed night).""" + night = [(a, b) for a, b, w in SCALE if w < 0.5] + lines = [_pct(h) for h in range(25)] + labels = [{"top": _pct(h), "text": f"{h:02d}"} for h in range(24) + if not any(a < h < b for a, b in night)] + return lines, labels + + +def _bands(cfg, day): + out = [] + for key, label in BANDS: + for a, z in _band(cfg, key, day): + out.append({"top": _pct(a), "height": round(_pct(z) - _pct(a), 3), "label": label}) + return out + + +def _now_pct(day, now): + """Where "now" falls in a day column: >100 = all past, <0 = all future.""" + if day < now.date(): + return 101.0 + if day > now.date(): + return -1.0 + return _pct(_hours(now, datetime.combine(day, datetime.min.time()))) + + +def _timeline_blocks(timed, day, now, tl_px, size, reg): + """Positioned blocks for one day column. `tl_px` (the timeline's height in + design px, wall layout at 1920×1080) only decides which blocks get a smaller label.""" + day0 = datetime.combine(day, datetime.min.time()) + now_p = _now_pct(day, now) + out = [] + for e, u, col, n, s in place_blocks(timed, day0): + top, bot = _pct(_hours(s, day0)), _pct(_hours(u, day0)) + colour = _colour(e) + tint = _mix(THEME["card"], colour, PAST_TINT) + if bot <= now_p: + state, split = "past", None + elif top >= now_p: + state, split = "future", None + else: # spans "now": tint above, colour below + state, split = "live", round((now_p - top) / (bot - top) * 100, 2) + px = (bot - top) / 100 * tl_px + fs = size if px >= size + 3 else int(px) - 2 + label_on_tint = state == "past" or (state == "live" and (now_p - top) / 100 * tl_px >= fs + 3) + out.append({ + "top": top, "height": round(bot - top, 3), + "left": round(col / n * 100, 3), "width": round(100 / n, 3), + "colour": colour, "tint": tint, "state": state, "split": split, + "ink": colour if label_on_tint else _ink_on(colour), + "font": fs if fs >= 10 else None, + "time": f"{e['start']:%H:%M}", "icon": e.get("icon"), "title": e["title"], + "id": reg.add(e), + }) + return out + + +def _birthdays(upcoming, reg): + bdays = [e for e in upcoming if is_birthday(e)] + people = [] + for ev in bdays[:2]: + when = _long_date(ev["start"].date()) + if len(when) > 11: # '4th November' -> '4th Nov' (column width) + when = f"{_ordinal(ev['start'].day)} {ev['start']:%b}" + people.append({"when": when, "name": birthday_name(ev), "year": birthday_year(ev), + "colour": ev.get("cal_color") or THEME["bday"], "id": reg.add(ev)}) + cake = (bdays[0].get("cal_color") if bdays else None) or THEME["bday"] + return {"cake": cake, "people": people} + + +def _next_event(upcoming, name, reg): + ev = next((e for e in upcoming if e.get("cal_name") == name), None) + if ev is None: + return {"empty": f"No upcoming {name}"} + sd, end = ev["start"].date(), ev.get("end") + if end and end > sd: + when = fmt_range(sd, end) + (f" {end:%B}" if (sd.year, sd.month) == (end.year, end.month) else "") + else: + when = _long_date(sd) + ("" if ev.get("all_day") else f" {ev['start']:%H:%M}") + return {"when": when, "icon": ev.get("icon"), "title": ev["title"], "colour": _colour(ev), + "id": reg.add(ev)} + + +def _upcoming(upcoming, today, shown, reg, height=399): + """Grouped one-column list, cut where it would overflow skips only what the side cards already show (shown_on_cards).""" + rows, y, last = [], 46, None + for orig, ev in upcoming_list(upcoming, today, shown): + day = ev["start"].date() + gap = last is not None and day != last + y += 8 if gap else 0 + if y + 26 > height - 12: + break + title = ev["title"] + if ev.get("end") and ev["end"] > day: + title += f" (until {_ordinal(ev['end'].day)} {ev['end']:%b})" + rows.append({"date": _day_label(day, ordinal=True) if day != last else "", + "time": "" if ev.get("all_day") else f"{ev['start']:%H:%M}", + "icon": ev.get("icon"), "title": title, "colour": _colour(ev), "gap": gap, + "id": reg.add(orig)}) + last = day + y += 42 + return rows + + +def _day_view(store, events, now, reg): + today = now.date() + day0 = datetime.combine(today, datetime.min.time()) + day1 = day0 + timedelta(days=1) + todays = [e for e in events if e["start"] < day1 and e["_until"] > day0 and not is_birthday(e)] + allday = [e for e in todays if _is_allday(e)] + timed = [e for e in todays if e not in allday] + pills = [] + for e in allday[:MAX_PILLS]: + rng = fmt_range(e["start"].date(), e["end"]) if e.get("end") and e["end"] > e["start"].date() else "" + pills.append({"range": rng, "icon": e.get("icon"), "title": e["title"], + "colour": _colour(e), "ink": _ink_on(_colour(e)), "id": reg.add(e)}) + more = max(0, len(allday) - MAX_PILLS) + lines, labels = _grid() + # timeline height in design px (wall layout at 1920×1080; box 16..1064, pills from +104) + top = 16 + 104 + 40 * len(pills) + (30 if more else 0) + 14 + tl_px = (1064 - 18) - top + return { + "weekday": now.strftime("%A"), "date": _long_date(today), "iso": today.isoformat(), + "pills": pills, "more": more, + "lines": lines, "labels": labels, "bands": _bands(store.cfg, today), + "blocks": _timeline_blocks(timed, today, now, tl_px, 19, reg), + "now": _now_pct(today, now), + } + + +def home(store): + """The calendar's parts of the web Home: birthdays + next-event cards (side), Upcoming + (up), the day view (day), and the info cards' data they point at (details).""" + now = datetime.now() + today = now.date() + with store.lock: + events = mine(store.cal_events) + upcoming = get_calendar(store) + cards = tuple((store.cfg.get("calendar") or {}).get("card_calendars", CARD_CALENDARS))[:2] + reg = _Details() + return { + "birthdays": _birthdays(upcoming, reg), + "cards": [_next_event(upcoming, n, reg) for n in cards], + "upcoming": _upcoming(upcoming, today, shown_on_cards(upcoming, cards), reg), + "day": _day_view(store, events, now, reg), + "details": reg.items, + } + + +# ---- week view -------------------------------------------------------------------- + +def week(store, offset): + now = datetime.now() + today = now.date() + monday = today - timedelta(days=today.weekday()) + timedelta(weeks=offset) + sunday = monday + timedelta(days=6) + w0 = datetime.combine(monday, datetime.min.time()) + w1 = w0 + timedelta(days=7) + weeks = mine(events_between(store, w0, w1)) # any week: on demand outside the cached window + reg = _Details() + + cols = [] + for dd, a, b in _week_columns(monday, today, 0, 100): + cols.append({"day": dd, "left": round(a, 3), "width": round(b - a, 3), + "label": f"{dd:%a}"[:2] + " " + _ordinal(dd.day), + "today": dd == today, "weekend": dd.weekday() >= 5}) + + # all-day / multi-day bars and birthdays, in lanes + bars, lanes = [], [] + for e in sorted((e for e in weeks if _is_allday(e)), + key=lambda e: (e["start"], -(e["_until"] - e["start"]).total_seconds())): + ca = (max(e["start"].date(), monday) - monday).days + cz = (min(e.get("end") or e["start"].date(), sunday) - monday).days + lane = next((i for i, last in enumerate(lanes) if last < ca), None) + if lane is None: + lanes.append(-1) + lane = len(lanes) - 1 + lanes[lane] = cz + if lane >= MAX_LANES: + continue + if is_birthday(e): + colour, icon, title = e.get("cal_color") or THEME["bday"], "🎂", birthday_name(e) + else: + colour, icon, title = _colour(e), e.get("icon"), e["title"] + past = (e.get("end") or e["start"].date()) < today + fill = _mix(THEME["card"], colour, PAST_BAR_MIX) if past else colour # past: lighter, no border + bars.append({"left": cols[ca]["left"], "width": round(cols[cz]["left"] + cols[cz]["width"] - cols[ca]["left"], 3), + "lane": lane, "icon": icon, "title": title, "colour": colour, "past": past, + "fill": fill, "ink": _ink_on(fill), "id": reg.add(e)}) + n_lanes = min(len(lanes), MAX_LANES) + + lines, labels = _grid() + tl_px = 1048 - (166 + n_lanes * 32 + 14) # timeline height in design px (1920×1080) + for c in cols: + dd = c["day"] + day0 = datetime.combine(dd, datetime.min.time()) + timed = [e for e in weeks if not _is_allday(e) and e["start"] < day0 + timedelta(days=1) + and e["_until"] > day0] + c.update(bands=_bands(store.cfg, dd), blocks=_timeline_blocks(timed, dd, now, tl_px, 17, reg), + now=_now_pct(dd, now)) + + if monday.month == sunday.month: + rng = fmt_range(monday, sunday) + f" {sunday:%B}" + else: + rng = f"{_long_date(monday)} – {_long_date(sunday)}" + return {"cw": monday.isocalendar()[1], "range": rng, "offset": offset, + "cols": cols, "bars": bars, "n_lanes": n_lanes, "lines": lines, "labels": labels, + "details": reg.items} + + +# ---- month view --------------------------------------------------------------------- + +MONTH_LANES = 2 # all-day bars per week row before they only count in "+N more" +MONTH_RANGE = (-120, 120) # how far the arrows go (data is expanded on demand) + + + +def _add_months(d, n): + y, m = divmod(d.month - 1 + n, 12) + return d.replace(year=d.year + y, month=m + 1, day=1) + + +def month(store, offset): + """Calendar month grid (Mon–Sun rows), any month (events_between expands + repeats on demand outside the cached window).""" + offset = max(MONTH_RANGE[0], min(MONTH_RANGE[1], offset)) + now = datetime.now() + today = now.date() + first = _add_months(today.replace(day=1), offset) + last = _add_months(first, 1) - timedelta(days=1) + grid0 = first - timedelta(days=first.weekday()) + grid1 = last + timedelta(days=6 - last.weekday()) + nrows = ((grid1 - grid0).days + 1) // 7 + this_monday = today - timedelta(days=today.weekday()) + events = mine(events_between(store, datetime.combine(grid0, datetime.min.time()), + datetime.combine(grid1 + timedelta(days=1), datetime.min.time()))) + reg = _Details() + + cols = [{"left": round(a, 3), "width": round(b - a, 3), "label": f"{dd:%a}", + "weekend": dd.weekday() >= 5} + for dd, a, b in _week_columns(grid0, None, 0, 100)] + row_h = (962 - 56 - 16) / nrows # design px (wall layout at 1920×1080): how many items fit + + rows = [] + for r in range(nrows): + monday = grid0 + timedelta(weeks=r) + sunday = monday + timedelta(days=6) + w0 = datetime.combine(monday, datetime.min.time()) + w1 = w0 + timedelta(days=7) + weeks = [e for e in events if e["start"] < w1 and e["_until"] > w0] + + # all-day / multi-day bars (and birthdays) in lanes + bars, lanes, hidden = [], [], [0] * 7 + for e in sorted((e for e in weeks if _is_allday(e)), + key=lambda e: (e["start"], -(e["_until"] - e["start"]).total_seconds())): + ca = (max(e["start"].date(), monday) - monday).days + cz = (min(e.get("end") or e["start"].date(), sunday) - monday).days + lane = next((i for i, l in enumerate(lanes) if l < ca), None) + if lane is None: + lanes.append(-1) + lane = len(lanes) - 1 + lanes[lane] = cz + if lane >= MONTH_LANES: + for c in range(ca, cz + 1): + hidden[c] += 1 + continue + if is_birthday(e): + colour, icon, title = e.get("cal_color") or THEME["bday"], "🎂", birthday_name(e) + else: + colour, icon, title = _colour(e), e.get("icon"), e["title"] + past = (e.get("end") or e["start"].date()) < today + fill = _mix(THEME["card"], colour, PAST_BAR_MIX) if past else colour # past: lighter, no border + bars.append({"left": cols[ca]["left"], + "width": round(cols[cz]["left"] + cols[cz]["width"] - cols[ca]["left"], 3), + "lane": lane, "icon": icon, "title": title, "colour": colour, "past": past, + "fill": fill, "ink": _ink_on(fill), "id": reg.add(e)}) + n_lanes = min(len(lanes), MONTH_LANES) + + cells = [] + for c in range(7): + dd = monday + timedelta(days=c) + day0 = datetime.combine(dd, datetime.min.time()) + timed = sorted((e for e in weeks if not _is_allday(e) and e["start"] < day0 + timedelta(days=1) + and e["_until"] > day0), key=lambda e: e["start"]) + fits = max(0, int((row_h - 34 - n_lanes * 26 - 4) // 24)) + extra = hidden[c] + shown = timed + if len(timed) + (1 if extra else 0) > fits: + shown = timed[:max(0, fits - 1)] + more = len(timed) - len(shown) + extra + cells.append({ + "num": f"{dd.day} {dd:%b}" if dd.day == 1 else str(dd.day), "iso": dd.isoformat(), + "today": dd == today, "out": dd.month != first.month, "past": dd < today, + "left": cols[c]["left"], "width": cols[c]["width"], + "week": (monday - this_monday).days // 7, + "evs": [{"time": f"{e['start']:%H:%M}", "icon": e.get("icon"), "title": e["title"], + "colour": _colour(e), "past": e["_until"] <= now, "id": reg.add(e)} + for e in shown], + "more": more, + }) + rows.append({"top": round(r * 100 / nrows, 3), "height": round(100 / nrows, 3), "lanes": n_lanes, + "bars": bars, "cells": cells}) + + cw0, cw1 = grid0.isocalendar()[1], grid1.isocalendar()[1] + return {"title": f"{first:%B %Y}", "sub": f"CW {cw0} – {cw1}", "offset": offset, + "current": offset == 0, "can_prev": offset > MONTH_RANGE[0], "can_next": offset < MONTH_RANGE[1], + "cols": cols, "rows": rows, "details": reg.items} + + +# ---- reminders (the web pages ding + open the event card) ------------------------------- + +REMIND_AHEAD = timedelta(hours=24) # schedule what fires in the next 24 h +REMIND_LATE = timedelta(minutes=10) # still show a reminder this long after it fired + + +def reminders(store): + """Reminders (VALARM) firing soon, for dash.js: [{key, at (epoch ms), card}]. One + that already fired is still returned until the event starts (at least REMIND_LATE), + so opening the page a bit late still shows it. Dismissals live in the browser.""" + now = datetime.now() + with store.lock: + events = mine(store.cal_events) + out = [] + for e in events: + for fire in e.get("alarms") or (): + if not (now - max(REMIND_LATE, e["start"] - fire) <= fire <= now + REMIND_AHEAD): + continue + reg = _Details() + card = reg.items[reg.add(e)] + out.append({"key": f"{e.get('cal')}|{e['title']}|{e['start']:%Y%m%d%H%M}|{fire:%Y%m%d%H%M}", + "at": int(fire.timestamp() * 1000), "card": card}) + return sorted(out, key=lambda r: r["at"]) + + +def demo_reminder(store): + """A fake reminder for the next upcoming event (?demo-reminder; dash.js times it).""" + up = get_calendar(store) + if not up: + return [] + reg = _Details() + card = reg.items[reg.add(up[0])] + now = datetime.now() + return [{"key": f"demo|{now:%H%M%S}", "at": int((now.timestamp() + 3) * 1000), "card": card}] diff --git a/dashboard/plugins/cycle/__init__.py b/dashboard/plugins/cycle/__init__.py new file mode 100644 index 0000000..d9e61d6 --- /dev/null +++ b/dashboard/plugins/cycle/__init__.py @@ -0,0 +1,140 @@ +"""Cycle tracker: mark the days you have your period; the rest is worked out. + + /cycle status ring + one button (today on / off), the month — every past + day has a period toggle and a note button — with predicted and + (optional) fertile days, history (?m=N other months) + /cycle/history every period (lengths, flow, pain; 12 a page, ?p=N), summary tiles, a printable summary + for a doctor (last 12 months, flags); /cycle/export.csv every logged day + /cycle/api/… JSON writes (same-origin only, like the core's) + +Data: dash_data/cycle/cycle.db (SQLite, see db.py) — plain for now. Never shown on +the wall screens; only on its own page. +""" +import csv +import io +import os +from contextlib import closing +from datetime import date + +from flask import Response, abort, jsonify, render_template, request + +from . import db, views + +PER_PAGE = 12 # History ▸ Every period + +META = { + "title": "Cycle tracker", + "glyph": "💧", + "glyph_color": "#ff6b7a", + "glyph_svg": {"viewBox": "2 5 20 24", "d": "M12 5.6L18.72 12.28A9.5 9.5 0 1 1 5.28 12.28Z"}, # the calendar's droplet + "description": "Tap the days you have your period. Cycle and period lengths, " + "the next periods and (if you want) the fertile window are worked out from that.", + "links": [{"label": "Open the tracker", "href": "/cycle"}, {"label": "History", "href": "/cycle/history"}], + "settings": [ + {"key": "cycle_length", "label": "Usual cycle length (days)", "type": "number", "default": 28, + "min": 15, "max": 60, "integer": True, + "help": "Used until two periods are logged; then your own average takes over."}, + {"key": "period_length", "label": "Usual period length (days)", "type": "number", "default": 5, + "min": 1, "max": 15, "integer": True}, + {"key": "show_fertile", "label": "Show the estimated fertile window and ovulation", "type": "bool", + "default": False, "help": "A textbook estimate (ovulation 14 days before a period) — not contraception."}, + ], + "sync": {"cycle.db": {"day": {"key": "'day:' || NEW.day"}}}, # one row per day (sync.py / syncdb.py) +} + + +def register(ctx): + bp = ctx.blueprint("/cycle") + ctx.warm("/cycle", "/cycle/history") # kept built in the background (pluginhost) + ctx.nav("Cycle", "/cycle") + here = os.path.dirname(os.path.abspath(__file__)) + + @bp.context_processor + def asset_version(): # cache-buster for cycle.css / .js + st = os.path.join(here, "static") + return {"asset_v": "%x" % int(max(os.path.getmtime(os.path.join(st, f)) for f in os.listdir(st)))} + + def con(): # one connection per request, closed after + return closing(db.connect(ctx.data_path("cycle.db"))) + + def version(): # Health caches pages with our blocks on them + return ctx.data_version("cycle.db") + + def summary(): # Health ▸ Overview: the cycle card / tile + with con() as c: + return views.summary(db.period_days(c), ctx.settings, calc=db.calculated_days(c)) + + def report_part(): # Health's report page: the doctor summary + with con() as c: + v = views.history(db.period_days(c), db.all_logs(c), ctx.settings) + return render_template("cycle/_report.html", d=v["doctor"], has=bool(v["rows"])) + + # a section of Health (a tab there, no nav button of its own; Health's + menu: today's log) + # — still its own plugin: own on / off, data, settings; Health off → Health's tab row shows just this + ctx.inside("health", add=("Period / day log", "/cycle#log"), report=lambda days: report_part(), + blocks=[{"id": "cycle.card", "kind": "card", "label": "Cycle", "w": 33, + "render": lambda: render_template("cycle/_ovcard.html", s=summary()), "version": version}, + {"id": "cycle.tile", "kind": "tile", "label": "Cycle day · next period", "w": 20, + "href": "/cycle", "render": lambda: render_template("cycle/_ovtile.html", s=summary()), + "version": version}]) + + def body(): + if not ctx.same_origin(): + abort(403) + return request.get_json(silent=True) or {} + + @bp.route("/", strict_slashes=False) + @ctx.cached_page("cycle.db") + def index(): + try: + offset = max(-240, min(24, int(request.args.get("m", 0)))) + except ValueError: + offset = 0 + with con() as c: + v = views.page(db.period_days(c), lambda a, z: db.logs_between(c, a, z), ctx.settings, offset, + calc=db.calculated_days(c)) + return render_template("cycle/index.html", v=v, s=ctx.settings, page="cycle", tab="calendar", + tags=db.TAGS, pain_len=db.PAIN_LEN) + + @bp.route("/history") + @ctx.cached_page("cycle.db") + def history(): + with con() as c: + v = views.history(db.period_days(c), db.all_logs(c), ctx.settings) + now = views.page(db.period_days(c), lambda a, z: db.logs_between(c, a, z), ctx.settings, 0, + calc=db.calculated_days(c)) # the left column (ring, today button) + try: # "Every period": PER_PAGE a page, newest first (?p=N) + pg = max(1, int(request.args.get("p", 1))) + except ValueError: + pg = 1 + pages = max(1, -(-len(v["rows"]) // PER_PAGE)) + pg = min(pg, pages) + rows = v["rows"][(pg - 1) * PER_PAGE:pg * PER_PAGE] + return render_template("cycle/history.html", v=v, now=now, page="cycle", tab="history", + rows=rows, pg=pg, pages=pages) + + @bp.route("/export.csv") + def export_csv(): # every logged day, for keeping or a doctor + names = {k: v for g in db.TAGS.values() for k, v in g.items()} + with con() as c: + logs = db.all_logs(c) + buf = io.StringIO() + w = csv.writer(buf) + w.writerow(["date", "period", "flow (1-5)", "pain (1-5)", "pain length", "symptoms", "mood", "sex", "note", "source"]) + for d in sorted(logs): + l = logs[d] + pick = lambda g: "; ".join(names[t] for t in l["tags"] if t in db.TAGS[g]) + w.writerow([d.isoformat(), "yes" if l["period"] else "", l["flow"] or "", l["pain"] or "", + db.PAIN_LEN.get(l["pain_len"], ""), pick("symptoms"), pick("mood"), pick("sex"), l["note"], + l["source"] or "local"]) + return Response("\ufeff" + buf.getvalue(), mimetype="text/csv", # BOM: Excel / LibreOffice read UTF-8 + headers={"Content-Disposition": f'attachment; filename="cycle-{date.today()}.csv"'}) + + @bp.route("/api/day", methods=["POST"]) + def api_day(): # {day, + any of period, flow, pain, pain_len, tags, note}; the rest stay + d = body() + with con() as c: + try: + return jsonify(ok=db.save_day(c, d)) + except db.Invalid as e: + return jsonify(error=str(e), field=e.field), 400 diff --git a/dashboard/plugins/cycle/db.py b/dashboard/plugins/cycle/db.py new file mode 100644 index 0000000..a970419 --- /dev/null +++ b/dashboard/plugins/cycle/db.py @@ -0,0 +1,189 @@ +"""Cycle tracker storage: one SQLite file (dash_data/cycle/cycle.db). + +Only what you log is stored: per **day**, whether it was a period day, its flow +(1–5, kept when the day is unmarked so it comes back), pain (1–5 + how long), tags +(symptoms, mood, sex — the vocabulary is TAGS) and a note. A period is a run of period days (views.py groups them); cycle +lengths, predictions and the fertile window are all computed on read, so fixing +a day fixes every number. + +Plain on purpose for now; all reads and writes go through this module, so +encrypting it later only changes this file. +""" +import os +import sqlite3 +import threading +from datetime import date, datetime, timedelta + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS day ( + day TEXT PRIMARY KEY, -- YYYY-MM-DD + period INTEGER NOT NULL DEFAULT 0, + note TEXT NOT NULL DEFAULT '', + updated TEXT NOT NULL +); +""" +COLUMNS = { # added after v1 (ALTER TABLE on first connect) + "flow": "INTEGER", # 1 (spotting-light) … 5 (very heavy); NULL = not set + "pain": "INTEGER", # 1 … 5 + "pain_len": "TEXT", # a PAIN_LEN key + "tags": "TEXT NOT NULL DEFAULT ''", # comma-separated TAGS keys + "source": "TEXT", # where the day came from: a SOURCES key; NULL = logged here +} +# key: (symbol, label). Shown small in a day's corner + in History; hover = the label. +SOURCES = { + "xiaomi": ("⌚", "Imported from Xiaomi (Mi Fitness)"), + "mymonthlycycles": ("📱", "Imported from My Monthly Cycles"), + "calculated": ("≈", "Calculated: not logged, placed between the periods around it"), +} +LOCAL = "Logged here" +PAIN_LEN = {"0-1": "under 1 h", "1-3": "1–3 h", "3-6": "3–6 h", "6-24": "6–24 h"} +TAGS = { + "symptoms": {"spotting": "Spotting", "headache": "Headache", "backache": "Backache", + "tiredness": "Tiredness", "bloating": "Bloating", "breasts": "Tender breasts", + "acne": "Acne", "nausea": "Nausea", "cravings": "Cravings", + "stomach": "Upset stomach", "sleep": "Poor sleep", "dizzy": "Dizziness"}, + "mood": {"happy": "Happy", "calm": "Calm", "energetic": "Energetic", "sensitive": "Sensitive", + "irritable": "Irritable", "anxious": "Anxious", "sad": "Sad", "swings": "Mood swings", + "stressed": "Stressed", "unmotivated": "Unmotivated"}, + "sex": {"sex_prot": "Sex, protected", "sex_unprot": "Sex, unprotected", "drive": "Sex drive", + "drive_low": "Low sex drive", "solo": "Masturbation", "sex_pain": "Pain during sex"}, +} +ALL_TAGS = {k for g in TAGS.values() for k in g} +MAX_OPEN = 7 # v1 migration: an open period becomes at most this many days +_init_lock = threading.Lock() +_ready = set() + + +class Invalid(ValueError): + def __init__(self, field, msg): + super().__init__(msg) + self.field = field + + +def connect(path): + """A connection for one request (sqlite3 connections don't cross threads).""" + con = sqlite3.connect(path, timeout=10) + con.row_factory = sqlite3.Row + if path not in _ready: + with _init_lock: + con.executescript(SCHEMA) + have = {r[1] for r in con.execute("PRAGMA table_info(day)")} + for col, typ in COLUMNS.items(): + if col not in have: + con.execute(f"ALTER TABLE day ADD COLUMN {col} {typ}") + con.commit() + _migrate_v1(con) + _ready.add(path) + os.chmod(path, 0o600) + return con + + +def _migrate_v1(con): + """v1 stored periods as start/end and notes apart: expand them into days, once. + The old tables stay as period_v1 / note_v1 (a backup; nothing reads them).""" + tables = {r[0] for r in con.execute("SELECT name FROM sqlite_master WHERE type='table'")} + if "period" not in tables: + return + t, today = now(), date.today() + for r in con.execute("SELECT start, end FROM period").fetchall(): + a = date.fromisoformat(r["start"]) + z = date.fromisoformat(r["end"]) if r["end"] else min(today, a + timedelta(days=MAX_OPEN - 1)) + while a <= z: + con.execute("INSERT INTO day (day, period, updated) VALUES (?, 1, ?) " + "ON CONFLICT(day) DO UPDATE SET period=1", (a.isoformat(), t)) + a += timedelta(days=1) + if "note" in tables: + for r in con.execute("SELECT day, text FROM note").fetchall(): + con.execute("INSERT INTO day (day, note, updated) VALUES (?, ?, ?) " + "ON CONFLICT(day) DO UPDATE SET note=excluded.note", (r["day"], r["text"], t)) + con.execute("ALTER TABLE note RENAME TO note_v1") + con.execute("ALTER TABLE period RENAME TO period_v1") + con.commit() + + +def now(): + return datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + +def _day(v): + try: + d = date.fromisoformat(str(v or "").strip()) + except ValueError: + raise Invalid("day", "Not a valid day.") + if d > date.today(): + raise Invalid("day", "That day hasn't happened yet.") + return d + + +# ---- reads --------------------------------------------------------------------------- + +def period_days(con): + """Every period day, oldest first: [date].""" + return [date.fromisoformat(r[0]) for r in con.execute("SELECT day FROM day WHERE period=1 ORDER BY day")] + + +def calculated_days(con): + return {date.fromisoformat(r[0]) for r in con.execute("SELECT day FROM day WHERE source='calculated'")} + + +def all_logs(con): + return logs_between(con, date(1900, 1, 1), date.today()) + + +def logs_between(con, a, z): + """{date: {period, flow, pain, pain_len, tags: [..], note, source}} for a <= day <= z.""" + return {date.fromisoformat(r["day"]): {"period": bool(r["period"]), "flow": r["flow"], "pain": r["pain"], + "pain_len": r["pain_len"], "tags": [t for t in r["tags"].split(",") if t], + "note": r["note"], "source": r["source"]} + for r in con.execute("SELECT * FROM day WHERE day BETWEEN ? AND ?", (a.isoformat(), z.isoformat()))} + + +# ---- writes -------------------------------------------------------------------------- + +def _scale(v, field): + if v in (None, "", 0): + return None + try: + n = int(v) + except (TypeError, ValueError): + raise Invalid(field, "Pick 1 to 5.") + if not 1 <= n <= 5: + raise Invalid(field, "Pick 1 to 5.") + return n + + +def save_day(con, d): + """Update the fields present in d ({day, period?, flow?, pain?, pain_len?, tags?, note?}); + the rest stay. A day with nothing left is deleted (its flow counts as something).""" + day = _day(d.get("day")).isoformat() + vals = {} + if "period" in d: + vals["period"] = 1 if d["period"] else 0 + if "flow" in d: + vals["flow"] = _scale(d["flow"], "flow") + if "pain" in d: + vals["pain"] = _scale(d["pain"], "pain") + if "pain_len" in d: + v = d["pain_len"] or None + if v is not None and v not in PAIN_LEN: + raise Invalid("pain_len", "Pick one of the lengths.") + vals["pain_len"] = v + if "tags" in d: + tags = d["tags"] if isinstance(d["tags"], list) else [] + bad = [t for t in tags if t not in ALL_TAGS] + if bad: + raise Invalid("tags", f"Unknown: {', '.join(map(str, bad))}.") + vals["tags"] = ",".join(t for g in TAGS.values() for t in g if t in tags) # stable order + if "note" in d: + vals["note"] = str(d["note"] or "").strip()[:2000] + if not vals: + return False + vals["updated"] = now() + cols = ", ".join(vals) + con.execute(f"INSERT INTO day (day, {cols}) VALUES (?, {', '.join('?' * len(vals))}) " + f"ON CONFLICT(day) DO UPDATE SET {', '.join(f'{c}=excluded.{c}' for c in vals)}", + (day, *vals.values())) + con.execute("DELETE FROM day WHERE day=? AND period=0 AND note='' AND flow IS NULL AND pain IS NULL " + "AND pain_len IS NULL AND tags=''", (day,)) + con.commit() + return True diff --git a/dashboard/plugins/cycle/static/cycle.css b/dashboard/plugins/cycle/static/cycle.css new file mode 100644 index 0000000..af6b8a8 --- /dev/null +++ b/dashboard/plugins/cycle/static/cycle.css @@ -0,0 +1,229 @@ +/* Cycle tracker — on top of dash.css (its tokens, header, .ec-box dialogs). Real px. */ +/* period, fertile colours (on :root: the day dialog sits outside .page-cycle) */ +:root { --pc: #ff6b7a; --fc: var(--cool); } +.page-cycle { display: flex; flex-direction: column; gap: 14px; font-size: 15px; } +.cy { display: grid; grid-template-columns: minmax(280px, 380px) minmax(0, 1fr); gap: 16px; align-items: start; } +.cy-now, .cy-cal { background: var(--card); border-radius: 14px; padding: 18px 20px; } +/* left column (both pages): the status box, the Calendar | History switch under it */ +.cy-side { display: flex; flex-direction: column; gap: 12px; min-width: 0; } +.cy-seg.seg { height: 46px; } +.cy-seg.seg a { flex: 1; width: auto; font-size: 16px; } +.cy-main { display: flex; flex-direction: column; gap: 14px; min-width: 0; } + +/* ---- status: ring + one button ----------------------------------------------------- */ +.cy-now { display: flex; flex-direction: column; align-items: center; gap: 12px; text-align: center; } +.cy-ring { position: relative; width: min(260px, 70vw); aspect-ratio: 1; } +.cy-ring svg { width: 100%; height: 100%; display: block; } +.cy-ring circle, .cy-ring path { fill: none; stroke-width: 9; stroke-linecap: round; } +.cy-track { stroke: #262d3b; } +.cy-arc-p { stroke: var(--pc); } +.cy-arc-f { stroke: var(--fc); opacity: .75; } +.cy-ring .cy-dot { fill: var(--fg); stroke: var(--card); stroke-width: 3; } +.cy-mid { position: absolute; inset: 18%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; } +.cy-mid b { font: 700 34px/1.1 "DejaVu Web", sans-serif; } +.cy-mid b.cy-sm { font-size: 20px; } +.cy-mid span { color: var(--muted); font-size: 14px; } +.cy-cday { color: var(--muted); margin-top: -4px; } +.cy-go { border: 0; border-radius: 10px; padding: 11px 22px; background: var(--accent); color: var(--bg); + font: 700 16px "DejaVu Web", sans-serif; cursor: pointer; } +.cy-go.off { background: #262d3b; color: var(--fg); font-weight: 400; } +.cy-go:disabled { opacity: .5; cursor: wait; } + +.cy-err { margin: 0; color: #ff7a7a; } .cy-err:empty { display: none; } +.cy-stats { display: flex; flex-wrap: wrap; justify-content: center; gap: 8px 22px; margin: 4px 0 0; } +.cy-stats div { display: flex; flex-direction: column; gap: 2px; } +.cy-stats dt { color: var(--dim); font-size: 12px; text-transform: uppercase; } +.cy-stats dd { margin: 0; } + +/* ---- month ------------------------------------------------------------------------- */ +.cy-dows, .cy-grid { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)); gap: 4px; } +.cy-dows span { text-align: center; color: var(--muted); font-size: 13px; padding-bottom: 6px; } +.cy-dows span.weekend { color: var(--dim); } +.cy-d { position: relative; aspect-ratio: 1.25; min-height: 44px; border-radius: 8px; background: #1b1f29; + display: flex; align-items: center; justify-content: center; font-size: 16px; cursor: pointer; + user-select: none; -webkit-user-select: none; } +.cy-d:hover:not(.future) { background: #222837; } +.cy-d:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.cy-d.busy { opacity: .6; cursor: wait; } +.cy-n { position: relative; width: 2.1em; height: 2.1em; line-height: 2.1em; text-align: center; border-radius: 50%; box-sizing: border-box; } +.cy-d.out { opacity: .4; } +.cy-d.future { cursor: default; background: #171b24; color: var(--muted); } +.cy-d.today { box-shadow: inset 0 0 0 2px var(--accent); } +.cy-d.today .cy-n { font-weight: 700; color: var(--accent); } +/* period day: the number in a droplet (filled = logged, dashed = predicted) */ +.cy-drop { position: absolute; left: 50%; top: 50%; width: 2.5em; height: 3em; transform: translate(-50%, -58.3%); overflow: visible; } /* round part centred on the number */ +.cy-drop path { fill: var(--pc); } +.cy-d.on { background: color-mix(in srgb, var(--pc) 16%, #1b1f29); } +.cy-d.on:hover { background: color-mix(in srgb, var(--pc) 22%, #1b1f29); } +.cy-d.on .cy-n { color: var(--bg); font-weight: 700; } +.cy-d.pred .cy-drop path { fill: none; stroke: var(--pc); stroke-width: 1.5; stroke-dasharray: 2.6 2; stroke-linejoin: round; } +.cy-d.fertile, .cy-d.ovul { background: color-mix(in srgb, var(--fc) 10%, #1b1f29); } +.cy-d.fertile:hover, .cy-d.ovul:hover { background: color-mix(in srgb, var(--fc) 16%, #1b1f29); } +.cy-d.ovul .cy-n { box-shadow: inset 0 0 0 2px var(--fc); } +/* note: a small pencil, top right — faint until there's a note (or hover on a mouse) */ +.cy-nb { position: absolute; top: 3px; right: 3px; width: 26px; height: 26px; padding: 0; border: 0; border-radius: 6px; + background: none; color: #343b4a; font: 14px/26px "Symbola Web", "DejaVu Web"; cursor: pointer; } +.cy-d:hover .cy-nb { color: var(--muted); } +.cy-nb:hover { color: var(--fg) !important; background: #2c3343; } +.cy-nb.has { color: var(--fg); } +/* where the day came from (import / calculated): small, bottom left; hover = label */ +.cy-src-t { position: absolute; left: 6px; bottom: 4px; font: 15px/1 "Symbola Web", "DejaVu Web"; font-variant-emoji: text; + color: var(--muted); cursor: help; } +.cy-d.on .cy-src-t { color: rgba(255, 255, 255, .55); } +/* calculated (estimated) days: greyed — they weren't logged */ +.cy-d.on.calc { background: color-mix(in srgb, var(--pc) 6%, #1b1f29); } +.cy-d.on.calc .cy-drop path { fill: color-mix(in srgb, var(--pc) 30%, #5a6070); } +.cy-d.on.calc .cy-n { color: #c3c8d4; font-weight: 400; } +.cy-hist tr.calc td, .cy-hist tr.calc a { color: var(--dim); } +.cy-src-h { font: 15px "Symbola Web", "DejaVu Web"; font-variant-emoji: text; color: var(--dim); cursor: help; } +/* flow picker on a period day: 5 droplets, small to big, filled up to the chosen one (hover + previews up to the pointed one); on hover (mouse) all show, else only the filled ones */ +.cy-f { border: 0; background: none; padding: 1px; cursor: pointer; line-height: 0; } +.cy-f svg { width: calc(var(--s) * 20px); height: calc(var(--s) * 24px); } +.cy-f path { fill: #3a4254; } +.cy-f.lit path { fill: var(--pc); } +.cy-fl { position: absolute; left: 0; right: 0; bottom: 3px; display: flex; justify-content: center; align-items: flex-end; gap: 3px; } +.cy-d.on .cy-fl .cy-f path { fill: rgba(255, 255, 255, .22); } +.cy-d.on .cy-fl .cy-f.lit path { fill: var(--pc); } +.cy-fl .cy-f:not(.lit) { visibility: hidden; } +@media (hover: hover) { .cy-d:hover .cy-fl .cy-f { visibility: visible; } } +@media (hover: none), (max-width: 599px) { .cy-fl { display: none; } } +.cy-fl:has(.cy-f:nth-child(1):hover) .cy-f:nth-child(-n+1) path, .cy-flows:has(.cy-f:nth-child(1):hover) .cy-f:nth-child(-n+1) path { fill: color-mix(in srgb, var(--pc) 75%, #fff) !important; } +.cy-fl:has(.cy-f:nth-child(2):hover) .cy-f:nth-child(-n+2) path, .cy-flows:has(.cy-f:nth-child(2):hover) .cy-f:nth-child(-n+2) path { fill: color-mix(in srgb, var(--pc) 75%, #fff) !important; } +.cy-fl:has(.cy-f:nth-child(3):hover) .cy-f:nth-child(-n+3) path, .cy-flows:has(.cy-f:nth-child(3):hover) .cy-f:nth-child(-n+3) path { fill: color-mix(in srgb, var(--pc) 75%, #fff) !important; } +.cy-fl:has(.cy-f:nth-child(4):hover) .cy-f:nth-child(-n+4) path, .cy-flows:has(.cy-f:nth-child(4):hover) .cy-f:nth-child(-n+4) path { fill: color-mix(in srgb, var(--pc) 75%, #fff) !important; } +.cy-fl:has(.cy-f:nth-child(5):hover) .cy-f:nth-child(-n+5) path, .cy-flows:has(.cy-f:nth-child(5):hover) .cy-f:nth-child(-n+5) path { fill: color-mix(in srgb, var(--pc) 75%, #fff) !important; } + + +/* symbols for some tags (sex, mood, spotting, tired, headache), top left */ +.cy-sy { position: absolute; top: 6px; left: 8px; right: 32px; display: flex; gap: 4px; overflow: hidden; + font: 15px/1 "Symbola Web", "DejaVu Web"; font-variant-emoji: text; color: var(--muted); pointer-events: none; } +.cy-sy svg, .cy-legend .sy svg { width: 10px; height: 12px; vertical-align: -1px; } +.cy-sy svg path, .cy-legend .sy svg path { fill: var(--pc); } +.cy-d.on .cy-sy { color: var(--fg); } +.cy-legend i.sy { width: auto; height: auto; border-radius: 0; font: normal 14px/1 "Symbola Web", "DejaVu Web"; font-variant-emoji: text; color: var(--fg); } + +.cy-legend { display: flex; flex-wrap: wrap; gap: 6px 18px; margin-top: 12px; color: var(--muted); font-size: 13px; } +.cy-legend span { display: inline-flex; align-items: center; gap: 7px; } +.cy-legend i { width: 12px; height: 12px; border-radius: 50%; box-sizing: border-box; } +.cy-legend .p { background: var(--pc); border-radius: 50% 0 50% 50%; transform: rotate(-45deg); } +.cy-legend .pred { border: 2px dashed var(--pc); border-radius: 50% 0 50% 50%; transform: rotate(-45deg); } +.cy-legend .fertile { border-radius: 3px; background: color-mix(in srgb, var(--fc) 35%, #1b1f29); } +.cy-legend .ovul { border: 2px solid var(--fc); } +.cy-legend .nt { width: auto; height: auto; font: normal 13px "Symbola Web", "DejaVu Web"; color: var(--fg); } + +/* ---- header tabs (Calendar | History) ------------------------------------------------ */ +.cy-seg a { width: auto !important; padding: 0 calc(var(--k) * 26); } + +/* ---- history page ------------------------------------------------------------------ */ +.cy-empty { padding: 18px 20px; border-radius: 14px; background: var(--card); color: var(--muted); } +.cy-empty a, .cy-hist a { color: var(--cool); } +.cy-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; } +.cy-tiles > div { background: var(--card); border-radius: 14px; padding: 14px 18px; display: flex; flex-direction: column; gap: 4px; } +.cy-tiles span { color: var(--dim); font-size: 13px; text-transform: uppercase; } +.cy-tiles b { font-size: 24px; } .cy-tiles small { color: var(--muted); } +.cy-card { background: var(--card); border-radius: 14px; padding: 16px 20px; overflow-x: auto; } +.cy-card h2 { margin: 0; font: 700 18px "DejaVu Web", sans-serif; } +.cy-card h2 small { color: var(--dim); font-weight: 400; font-size: 14px; margin-left: 8px; } +.cy-hist h2 { margin-bottom: 8px; } +/* Every period: 12 a page (?p=N#periods), the pager top right and under the table */ +.cy-hhead { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 8px; } +.cy-pager { display: flex; flex-wrap: wrap; gap: 4px; } +.cy-pager .cy-mini { text-decoration: none; min-width: 34px; text-align: center; } +.cy-pager .cy-mini.on { background: var(--accent); color: var(--bg); } +.cy-pager .cy-mini.off { opacity: .35; pointer-events: none; } +.cy-hfoot { display: flex; justify-content: flex-end; margin-top: 10px; } +.cy-dhead { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 12px; } +.cy-dact { display: flex; gap: 8px; flex-wrap: wrap; } +.cy-mini { border: 0; border-radius: 8px; padding: 6px 12px; background: #262d3b; color: var(--fg); cursor: pointer; + font: 400 14px "DejaVu Web", sans-serif; } +.cy-mini:hover { color: var(--accent); } +.cy-dl { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 8px 22px; margin: 0; } +.cy-dl dt { color: var(--muted); } .cy-dl dd { margin: 0; } +.cy-flags { margin-top: 14px; padding: 10px 16px; border-radius: 10px; background: #2a2416; border-left: 4px solid var(--accent); } +.cy-flags h3 { margin: 0 0 6px; font: 700 15px "DejaVu Web", sans-serif; color: var(--accent); } +.cy-flags ul { margin: 0; padding-left: 20px; line-height: 1.5; } +.cy-ok { margin: 14px 0 0; color: #7fd6a3; } +.cy-fine { margin: 12px 0 0; color: var(--dim); font-size: 13px; } +.cy-hist table { width: 100%; border-collapse: collapse; font-size: 14.5px; } +.cy-hist th { text-align: left; font-weight: 400; font-size: 13px; color: var(--dim); padding: 6px 10px; border-bottom: 1px solid #262c39; } +.cy-gap { color: var(--dim); } +.cy-hist td { padding: 7px 10px; border-bottom: 1px solid #1f2430; white-space: nowrap; } + +/* ---- day dialog (looks like the new-event form) ------------------------------------ */ +.cy-modal[hidden] { display: none !important; } +.cy-modal { position: fixed; inset: 0; z-index: 10; display: flex; align-items: center; justify-content: center; } +.cy-box { --ec: var(--pc); display: flex; flex-direction: column; gap: 14px; } +.cy-ftitle { font: 700 22px "DejaVu Web", sans-serif; margin-right: 34px; } +.cy-box input, .cy-box textarea { font: 16px "DejaVu Web", sans-serif; color: var(--fg); background: #1d222d; + border: 1px solid #2c3343; border-radius: 8px; padding: 7px 10px; box-sizing: border-box; min-width: 0; color-scheme: dark; } +.cy-box textarea { resize: vertical; line-height: 1.4; } +.cy-box :focus { outline: 2px solid var(--accent); outline-offset: -1px; } +.cy-sec { display: flex; flex-direction: column; gap: 8px; } +.cy-sec h3 { margin: 0; font: 400 12.5px "DejaVu Web", sans-serif; color: var(--dim); text-transform: uppercase; letter-spacing: .04em; } +.cy-row { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 14px; } +.cy-chips { display: flex; flex-wrap: wrap; gap: 6px; } +.cy-chip { border: 0; border-radius: 8px; padding: 6px 12px; background: #262d3b; color: var(--muted); cursor: pointer; + font: 14px "DejaVu Web", sans-serif; } +.cy-chip:hover { color: var(--fg); } +.cy-chip.sel { background: #2a2416; color: var(--accent); box-shadow: inset 0 0 0 1px rgba(255, 179, 58, .45); } +.cy-pon.sel { background: color-mix(in srgb, var(--pc) 22%, #1b1f29); color: var(--fg); box-shadow: inset 0 0 0 1px var(--pc); } +.cy-flows { display: flex; align-items: flex-end; gap: 4px; } +.cy-flows .cy-f svg { width: calc(var(--s) * 22px); height: calc(var(--s) * 26.4px); } +.cy-flows.dim { opacity: .55; } +.cy-flabel, .cy-plabel { color: var(--muted); font-size: 14px; } +.cy-scale { display: flex; gap: 4px; } +.cy-scale button { width: 36px; height: 32px; border: 0; border-radius: 7px; background: #262d3b; color: var(--muted); cursor: pointer; + font: 700 14px "DejaVu Web", sans-serif; } +.cy-scale button:hover { color: var(--fg); } +.cy-scale button.sel { background: var(--warm); color: var(--bg); } +.cy-scale button.sel:nth-child(n+4) { background: var(--pc); } +.cy-box textarea { width: 100%; } +.cy-actions { display: flex; align-items: center; justify-content: flex-end; gap: 14px; flex-wrap: wrap; } +.cy-ferr { flex: 1; color: #ff7a7a; font-size: 15px; min-width: 120px; } +.cy-save { padding: 9px 18px; border: 0; border-radius: 10px; cursor: pointer; font: 700 16px "DejaVu Web", sans-serif; } +.cy-save { background: var(--accent); color: var(--bg); } .cy-save:disabled { opacity: .5; cursor: wait; } + + +/* ---- narrow ------------------------------------------------------------------------ */ +@media (max-width: 799px) { + .cy { grid-template-columns: minmax(0, 1fr); } +} +@media (max-width: 499px) { + .cy-now, .cy-cal, .cy-card { padding: 14px 12px; } + .cy-dl { grid-template-columns: minmax(0, 1fr); gap: 2px; } + .cy-dl dd { margin-bottom: 8px; } + .cy-seg a { padding: 0 10px; font-size: 13px; } +} + +/* print (doctor summary): only that card, dark text on white */ +@media print { + html, body { background: #fff !important; } + body::before { display: none; } /* the amber top line */ + body * { visibility: hidden; } + #doctor, #doctor * { visibility: visible; color: #111 !important; } + #doctor { position: absolute; left: 0; top: 0; width: 100%; box-sizing: border-box; background: #fff; padding: 4px; font-size: 12pt; } + #doctor .cy-dact { display: none; } + #doctor .cy-flags { background: #fff; border: 1px solid #999; border-left: 4px solid #555; } +} +@media (max-width: 599px) { + .cy-d { font-size: 14px; min-height: 40px; aspect-ratio: .95; border-radius: 6px; } + .cy-nb { top: 1px; right: 1px; width: 20px; height: 20px; font-size: 11px; line-height: 20px; } + .cy-sy { top: 3px; left: 3px; right: 20px; gap: 1px; font-size: 11px; } + .cy-sy svg { width: 7px; height: 9px; } + .cy-src-t { left: 3px; bottom: 2px; font-size: 11px; } + .cy-grid, .cy-dows { gap: 3px; } + .cy-dows span { font-size: 12px; } +} + + +/* ---- landscape screens: the calendar page fits the window (the weeks share the height the + header + Health's tab row leave; a day's cell gives up its fixed shape for it) ---------- */ +@media (min-width: 1000px) and (min-aspect-ratio: 5/4) { + #page.page-cycle:has(.cy-cal) { height: 100vh; box-sizing: border-box; } + .page-cycle .cy:has(.cy-cal) { flex: 1; min-height: 0; align-items: stretch; } + .cy-side { min-height: 0; overflow: auto; } + .cy-cal { display: flex; flex-direction: column; min-height: 0; } + .cy-grid { flex: 1; min-height: 0; grid-auto-rows: minmax(0, 1fr); } + .cy-d { aspect-ratio: auto; min-height: 0; } +} diff --git a/dashboard/plugins/cycle/static/cycle.js b/dashboard/plugins/cycle/static/cycle.js new file mode 100644 index 0000000..6e3debf --- /dev/null +++ b/dashboard/plugins/cycle/static/cycle.js @@ -0,0 +1,139 @@ +// Cycle tracker page (/cycle). Click a past day to mark / unmark it as a period day; on a +// period day, hovering shows its flow picker (5 droplets, small to big); its ✎ (top right) +// opens the day's log: period + flow, pain + how long, symptoms, mood, sex, note — saved +// together. The big button toggles today. After a change the page's .cy is swapped for a +// fresh server copy (everything shown is computed there), keeping the scroll position. +// /cycle#log opens today's log right away (#log=YYYY-MM-DD: that day, if it's on the page). +// No browser dialogs. +(function () { + const post = async (url, data) => { + const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw Object.assign(new Error(j.error || `Error ${r.status}`), { field: j.field }); + return j; + }; + const modal = (on) => document.body.classList.toggle("modal", on); // dash.js: keys off + const say = (m) => { const e = document.querySelector(".cy-err"); if (e) e.textContent = m || ""; }; + const FLOWS = ["very light", "light", "medium", "heavy", "very heavy"]; + const PAINS = ["mild", "noticeable", "moderate", "strong", "severe"]; + const EXCLUSIVE = [["drive", "drive_low"]]; // picking one clears the other + + async function refresh() { + const r = await fetch(location.href, { cache: "no-store" }); + const fresh = new DOMParser().parseFromString(await r.text(), "text/html").querySelector(".cy"); + if (fresh) document.querySelector(".cy").replaceWith(fresh); + } + + let busy = false; + async function saveDay(data, el) { // calendar quick edits + if (busy) return; + busy = true; el.classList.add("busy"); + try { await post("/cycle/api/day", data); await refresh(); } + catch (x) { el.classList.remove("busy"); say(x.message); } + finally { busy = false; } + } + const togglePeriod = (c) => saveDay({ day: c.dataset.day, period: !c.classList.contains("on") }, c); + + // ---- the day's log + const box = document.getElementById("cy-form"); + const form = box.querySelector("form"); + let cell = null, S = null; // the day being edited, its state + const err = (m) => { box.querySelector(".cy-ferr").textContent = m || ""; }; + const press = (el, on) => { el.classList.toggle("sel", on); el.setAttribute("aria-pressed", on ? "true" : "false"); }; + + function paint() { + press(box.querySelector(".cy-pon"), S.period); + box.querySelectorAll(".cy-flows .cy-f").forEach((b) => { + press(b, Number(b.dataset.flow) === S.flow); + b.classList.toggle("lit", Number(b.dataset.flow) <= (S.flow || 0)); // filled up to the chosen one + }); + box.querySelector(".cy-flows").classList.toggle("dim", !S.period); + box.querySelector(".cy-flabel").textContent = S.flow ? FLOWS[S.flow - 1] + (S.period ? "" : " (kept for when it's a period day)") : ""; + box.querySelectorAll("[data-pain]").forEach((b) => press(b, Number(b.dataset.pain) <= (S.pain || 0))); + box.querySelector(".cy-plabel").textContent = S.pain ? PAINS[S.pain - 1] : ""; + box.querySelectorAll("[data-len]").forEach((b) => press(b, b.dataset.len === S.pain_len)); + box.querySelectorAll("[data-tag]").forEach((b) => press(b, S.tags.has(b.dataset.tag))); + } + + function openLog(c) { + cell = c; + const log = JSON.parse(c.dataset.log || "null") || {}; + S = { period: c.classList.contains("on"), flow: log.flow || null, pain: log.pain || null, + pain_len: log.pain_len || null, tags: new Set(log.tags || []) }; + box.querySelector(".cy-ftitle").textContent = + new Date(c.dataset.day + "T12:00").toLocaleDateString("en-GB", { weekday: "short", day: "numeric", month: "short", year: "numeric" }); + form.elements.note.value = log.note || ""; + err(""); paint(); + box.hidden = false; modal(true); + box.querySelector(".cy-pon").focus(); + } + const close = () => { box.hidden = true; modal(false); }; + + box.addEventListener("click", (e) => { + if (e.target.closest(".ec-x") || e.target.classList.contains("ec-back")) return close(); + const b = e.target.closest("button"); + if (!b || !S) return; + if (b.classList.contains("cy-pon")) S.period = !S.period; + else if (b.dataset.flow) { // picking a flow makes it a period day + const n = Number(b.dataset.flow); + S.flow = S.flow === n ? null : n; + if (S.flow) S.period = true; + } else if (b.dataset.pain) { const n = Number(b.dataset.pain); S.pain = S.pain === n ? null : n; } + else if (b.dataset.len) S.pain_len = S.pain_len === b.dataset.len ? null : b.dataset.len; + else if (b.dataset.tag) { + const t = b.dataset.tag; + if (S.tags.has(t)) S.tags.delete(t); + else { S.tags.add(t); EXCLUSIVE.forEach((g) => g.includes(t) && g.forEach((o) => o !== t && S.tags.delete(o))); } + } else return; + paint(); + }); + addEventListener("keydown", (e) => { + if (box.hidden) return; + if (e.key === "Escape") close(); + if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) form.requestSubmit(); + }); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + const save = form.querySelector(".cy-save"); + save.disabled = true; + try { + await post("/cycle/api/day", { day: cell.dataset.day, period: S.period, flow: S.flow, pain: S.pain, + pain_len: S.pain_len, tags: [...S.tags], note: form.elements.note.value }); + close(); + await refresh(); + } catch (x) { err(x.message); } finally { save.disabled = false; } + }); + + // ---- the page: one listener (.cy is replaced after every change) + document.addEventListener("click", (e) => { + if (!box.hidden) return; + const go = e.target.closest(".cy-go"); + if (go) return saveDay({ day: go.dataset.day, period: go.dataset.on === "1" }, go); + const c = e.target.closest(".cy-d"); + if (!c) return; + if (e.target.closest(".cy-nb")) return openLog(c); + if (e.target.closest(".cy-src-t")) return; // the source symbol: just its tooltip + const f = e.target.closest(".cy-fl .cy-f"); // flow picker on a period day + if (f) { + const n = Number(f.dataset.flow); + return saveDay({ day: c.dataset.day, flow: f.classList.contains("sel") ? null : n }, c); + } + if (c.getAttribute("role") === "button") togglePeriod(c); + }); + document.addEventListener("keydown", (e) => { // a focused day: Enter / Space toggles it + const c = e.target.closest?.(".cy-d[role=button]"); + if (!c || e.target !== c || !(e.key === "Enter" || e.key === " ")) return; + e.preventDefault(); + togglePeriod(c); + }); + + // /cycle#log opens today's log (Health's + menu: "Period / day log"); #log=YYYY-MM-DD that day + const m = /^#log(?:=(\d{4}-\d{2}-\d{2}))?$/.exec(location.hash); + if (m) { + const t = new Date(), pad = (n) => String(n).padStart(2, "0"); + const day = m[1] || `${t.getFullYear()}-${pad(t.getMonth() + 1)}-${pad(t.getDate())}`; + history.replaceState(null, "", location.pathname + location.search); + const c = document.querySelector(`.cy-d[data-day="${day}"]`); + if (c) openLog(c); + } +})(); diff --git a/dashboard/plugins/cycle/templates/cycle/_head.html b/dashboard/plugins/cycle/templates/cycle/_head.html new file mode 100644 index 0000000..7d276ea --- /dev/null +++ b/dashboard/plugins/cycle/templates/cycle/_head.html @@ -0,0 +1,72 @@ +{# Cycle pages: the core header (⌂ 📅 … ··· ‹ title › ··· ⚙) and the left column both pages + share — status ring, the today button, averages — with the Calendar | History switch under it. #} +{% from "_header.html" import nav_btns, settings_btn, title_block, subline, section_tabs %} +{% macro head(title, sub, current=True, center_href="/cycle", prev_href=None, next_href=None, can_next=True) %} +
+ {{ nav_btns() }} + {{ title_block(title, center_href, current, prev_href, next_href, can_next=can_next, + prev_title="Previous month", next_title="Next month") }} + {{ settings_btn("cycle") }} +
+{{ subline(sub) }} +{% if plugin_host("cycle") %}{{ section_tabs(plugin_host("cycle"), "/cycle") }}{% endif %}{# inside Health: its tab row #} +{% endmacro %} + +{% macro dm(d) %}{{ d.day }} {{ d.strftime("%b") }}{% endmacro %} +{% macro wdm(d) %}{{ d.strftime("%a") }} {{ d.day }} {{ d.strftime("%b") }}{% endmacro %} + +{# v = views.page(…) (ring, status, stats, preds, today) #} +{% macro side(v) %} +{% set st = v.status %} +
+
+
+ +
+ {% if st.kind == "empty" %} + No periods yetlog the first one + {% elif st.kind == "period" %} + periodDay {{ st.day }}since {{ dm(st.since) }} + {% elif st.kind == "late" %} + period{{ st.days }} day{{ "s" if st.days != 1 }} lateexpected {{ dm(st.expected) }} + {% elif st.days == 0 %} + periodTodayexpected + {% else %} + period in{{ st.days }} day{{ "s" if st.days != 1 }}around {{ wdm(st.next) }} + {% endif %} +
+
+ {% if st.cycle_day and st.kind != "period" %}
Cycle day {{ st.cycle_day }}
{% endif %} + + {% if st.today_on %} + + {% elif st.kind == "period" %} + + {% else %} + + {% endif %} + + +
+
Cycle
{{ v.stats.cycle }} days
+
Period
{{ v.stats.period }} days
+ {% if v.preds %}
Next
{% for a, z in v.preds %}{{ dm(a) }}{{ " · " if not loop.last }}{% endfor %}
{% endif %} +
+
+ +
+{% endmacro %} + +{% macro assets() %} + +{% endmacro %} diff --git a/dashboard/plugins/cycle/templates/cycle/_ovcard.html b/dashboard/plugins/cycle/templates/cycle/_ovcard.html new file mode 100644 index 0000000..aeba575 --- /dev/null +++ b/dashboard/plugins/cycle/templates/cycle/_ovcard.html @@ -0,0 +1,46 @@ +{# Health ▸ Overview: the cycle card (views.summary, s = the summary). Health's card look; + its own small ring styles inline here (cycle.css isn't on Health's pages). #} +{% macro dm(d) %}{{ d.strftime("%a") }} {{ d.day }} {{ d.strftime("%b") }}{% endmacro %} +{% macro span(a, z) %}{% if a.month == z.month %}{{ a.day }}–{{ z.day }} {{ z.strftime("%b") }}{% else %}{{ a.day }} {{ a.strftime("%b") }} – {{ z.day }} {{ z.strftime("%b") }}{% endif %}{% endmacro %} +{% set st, fw = s.status, s.fertile %} +
+ +

{% if s.show_fertile and not s.empty %}CycleUsual cycle {{ s.stats.cycle }} days, period {{ s.stats.period }}. Fertile days are a textbook estimate (ovulation 14 days before a period) — not contraception.{% else %}Cycle{% endif %}

Calendar ›
+ {% if s.empty %}

No periods logged yet — log one.

{% else %} +
+
+ +
+ {% if st.kind == "period" %}periodDay {{ st.day }} + {% elif st.kind == "late" %}period{{ st.days }} day{{ "s" if st.days != 1 }} late + {% elif st.days == 0 %}periodTodayexpected + {% else %}period in{{ st.days }} day{{ "s" if st.days != 1 }}{% endif %} +
+
+
+
Cycle day
{{ st.cycle_day }}{% if st.kind == "period" %} · period, day {{ st.day }}{% endif %}
+
Next period
{% if st.kind == "late" %}{{ st.days }} day{{ "s" if st.days != 1 }} late (expected {{ dm(st.expected) }}){% elif s.preds %}{{ dm(s.preds[0][0]) }}{% if st.kind != "period" and st.days %} · in {{ st.days }} day{{ "s" if st.days != 1 }}{% endif %}{% endif %}
+ {% if s.show_fertile and fw %} +
Fertile
{% if fw.now %}now · until {{ dm(fw.end) }}{% else %}{{ span(fw.start, fw.end) }}{% endif %}
+
Ovulation
{% if fw.ovul_today %}around today{% else %}around {{ dm(fw.ovul) }}{% endif %}
+
Pregnancy
{% if fw.now %}possible — fertile window{% else %}less likely — outside the fertile window{% endif %}
+ {% endif %} +
+
+ {% endif %} +
diff --git a/dashboard/plugins/cycle/templates/cycle/_ovtile.html b/dashboard/plugins/cycle/templates/cycle/_ovtile.html new file mode 100644 index 0000000..cb864d9 --- /dev/null +++ b/dashboard/plugins/cycle/templates/cycle/_ovtile.html @@ -0,0 +1,9 @@ +{# Health ▸ Overview: the cycle tile (views.summary as s) — the inside of a tile. #} +{% macro dm(d) %}{{ d.strftime("%a") }} {{ d.day }} {{ d.strftime("%b") }}{% endmacro %} +{% set st, fw = s.status, s.fertile %} +Cycle +{% if s.empty %}—nothing logged +{% elif st.kind == "period" %}Period · day {{ st.day }}cycle day {{ st.cycle_day }} +{% elif st.kind == "late" %}{{ st.days }} day{{ "s" if st.days != 1 }} latecycle day {{ st.cycle_day }} +{% else %}Day {{ st.cycle_day }}period {% if st.days == 0 %}expected today{% else %}in {{ st.days }} day{{ "s" if st.days != 1 }} · {{ dm(st.next) }}{% endif %}{% endif %} +{% if not s.empty and s.show_fertile and fw and fw.now %}fertile window{% if fw.ovul_today %} · ovulation around today{% endif %}{% endif %} diff --git a/dashboard/plugins/cycle/templates/cycle/_report.html b/dashboard/plugins/cycle/templates/cycle/_report.html new file mode 100644 index 0000000..735c50d --- /dev/null +++ b/dashboard/plugins/cycle/templates/cycle/_report.html @@ -0,0 +1,17 @@ +{# Health ▸ report: the cycle tracker's part (the same summary as History ▸ For your doctor, + always its last 12 months). Uses the report's .rp-* styles. #} +{% macro dmy(x) %}{{ x.day }} {{ x.strftime("%b %Y") }}{% endmacro %} +{% macro rng(r, unit="days") %}{% if r %}{% if r[0] == r[1] %}{{ r[0] }}{% else %}{{ r[0] }}–{{ r[1] }}{% endif %} {{ unit }}{% else %}—{% endif %}{% endmacro %} +
+

Menstrual cycle self-logged, {{ dmy(d.since) }} – {{ dmy(d.today) }}

+ {% if not has %}

Nothing logged yet.

{% else %} + + + + + + + +
Last period{{ ("started " ~ dmy(d.last)) if d.last else "—" }}
Cycle length{% if d.cycle %}{{ d.cycle }} days{% else %}—{% endif %}{% if d.cycle %}range {{ rng(d.cycle_range) }}{% else %}not enough data yet{% endif %} (typical 21–35)
Period length{% if d.period %}{{ d.period }} days{% else %}—{% endif %}{% if d.period %}range {{ rng(d.period_range) }}{% endif %} (typical up to 7)
Periods logged{{ d.periods }}
Pain{% if d.pain_days %}on {{ d.pain_days }} day{{ "s" if d.pain_days != 1 }}, {{ d.pain_avg }} / 5 on average{% else %}none logged{% endif %}
Most common{% if d.symptoms %}{% for name, n in d.symptoms %}{{ name }} ({{ n }}×){{ ", " if not loop.last }}{% endfor %}{% else %}no symptoms logged{% endif %}
+ {% endif %} +
diff --git a/dashboard/plugins/cycle/templates/cycle/history.html b/dashboard/plugins/cycle/templates/cycle/history.html new file mode 100644 index 0000000..b7cab4c --- /dev/null +++ b/dashboard/plugins/cycle/templates/cycle/history.html @@ -0,0 +1,99 @@ +{% extends "base.html" %} +{% import "cycle/_head.html" as cy with context %} +{% block title %}Cycle history{% endblock %} +{% block head %}{{ cy.assets() }}{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{# Tiles, every period (views.history), and a summary for a doctor: the last 12 months, + printable on its own (Print → only that card, light, see @media print in cycle.css). #} +{% macro dm(d) %}{{ d.day }} {{ d.strftime("%b") }}{% endmacro %} +{% macro dmy(d) %}{{ d.day }} {{ d.strftime("%b %Y") }}{% endmacro %} +{% macro rng(r, unit="days") %}{% if r %}{% if r[0] == r[1] %}{{ r[0] }}{% else %}{{ r[0] }}–{{ r[1] }}{% endif %} {{ unit }}{% else %}—{% endif %}{% endmacro %} +{% set d = v.doctor %} +{% block page %} +{{ cy.head("History", "cycle", True, "/cycle/history") }} + +
+{{ cy.side(now) }} +
+ +{% if not v.rows %} +
Nothing logged yet. Mark your period days in the calendar; the history fills in from there.
+{% else %} +
+
Usual cycle{{ v.stats.cycle }} days{{ ("range " ~ rng(v.cycle_range)) if v.cycle_range else "from Settings until two periods are logged" }}
+
Usual period{{ v.stats.period }} daysaverage, recent periods count most
+
Last period{{ dm(v.last.start) }}{{ (v.today - v.last.start).days }} days ago
+
Tracked{{ v.rows | length }} period{{ "s" if v.rows | length != 1 }}{{ v.tracked }} full cycle{{ "s" if v.tracked != 1 }}
+
+ +
+
+

For your doctor {{ dmy(d.since) }} – {{ dmy(d.today) }}

+
+ + Every logged day (CSV) +
+
+
+
First day of last period
{{ dmy(d.last) if d.last else "—" }}
+
Cycle length
{% if d.cycle %}{{ d.cycle }} days on average · {{ rng(d.cycle_range) }}{% else %}not enough data yet{% endif %}
+
Period length
{% if d.period %}{{ d.period }} days on average · {{ rng(d.period_range) }}{% else %}not enough data yet{% endif %}
+
Periods logged
{{ d.periods }}
+
Pain
{% if d.pain_days %}on {{ d.pain_days }} day{{ "s" if d.pain_days != 1 }}, {{ d.pain_avg }} / 5 on average{% else %}none logged{% endif %}
+
Most common
{% if d.symptoms %}{% for name, n in d.symptoms %}{{ name }} ({{ n }}×){{ ", " if not loop.last }}{% endfor %}{% else %}no symptoms logged{% endif %}
+
+ {% if d.flags %} +
+

Worth mentioning

+
    {% for f in d.flags %}
  • {{ f }}
  • {% endfor %}
+
+ {% else %} +

Nothing unusual by the common guidelines (cycles 21–35 days, periods up to 7 days, no spotting between periods, …).

+ {% endif %} +

From self-logged data; general guidance, not a diagnosis.

+
+ +{% macro pager() %}{% if pages > 1 %} +{% endif %}{% endmacro %} +
+

Every period {{ v.rows | length }}{% if pages > 1 %} · {{ (pg - 1) * 12 + 1 }}–{{ (pg - 1) * 12 + rows | length }}{% endif %}

{{ pager() }}
+ + + + {% for h in rows %} + + + + + + {% endfor %} + +
StartedPeriodCycleHeaviest flowStrongest pain
{{ h.start.strftime("%a") }} {{ dm(h.start) }}{{ " " ~ h.start.year if h.start.year != v.today.year }}{% for y in h.sources %} {{ y.g }}{% endfor %}{{ "going on" if h.going else (h.days ~ " days") }}{% if h.cycle and h.cycle > 60 %}{{ h.cycle }} days · gap?{% else %}{{ (h.cycle ~ " days") if h.cycle else "—" }}{% endif %}{{ h.flow or "—" }}{{ (h.pain ~ " / 5") if h.pain else "—" }}
+ {% if pages > 1 %}
{{ pager() }}
{% endif %} +
+{% endif %} +
+
+{% endblock %} + +{% block scripts %} + +{% endblock %} diff --git a/dashboard/plugins/cycle/templates/cycle/index.html b/dashboard/plugins/cycle/templates/cycle/index.html new file mode 100644 index 0000000..09a5af4 --- /dev/null +++ b/dashboard/plugins/cycle/templates/cycle/index.html @@ -0,0 +1,91 @@ +{% extends "base.html" %} +{% import "cycle/_head.html" as cy with context %} +{% block title %}Cycle{% endblock %} +{% block head %}{{ cy.assets() }}{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{# Status ring + one button (today on / off), the month — click a past day to mark it a + period day (a droplet; hover shows its flow picker), its ✎ (top right) opens the day's + log (period + flow, pain, symptoms, mood, sex, note). History: history.html. + cycle.js: the buttons; after a change it swaps in .cy from a fresh copy of the page. #} +{% set st = v.status %} +{% set DROP = "M12 5.6L18.72 12.28A9.5 9.5 0 1 1 5.28 12.28Z" %} +{% set FLOWS = ["very light", "light", "medium", "heavy", "very heavy"] %} +{% macro drop(cls="") %}{% endmacro %} +{% macro flows(cur=None) %}{% for f in FLOWS %}{% endfor %}{% endmacro %} +{% macro dm(d) %}{{ d.day }} {{ d.strftime("%b") }}{% endmacro %} +{% macro wdm(d) %}{{ d.strftime("%a") }} {{ d.day }} {{ d.strftime("%b") }}{% endmacro %} +{% block page %} +{{ cy.head(v.month.strftime("%B"), v.month.year ~ " · cycle", v.offset == 0, "/cycle", + "/cycle?m=" ~ (v.offset - 1), "/cycle?m=" ~ (v.offset + 1), v.offset < 24) }} + +
+ {{ cy.side(v) }} + +
+
{% for d in v.dows %} 5 %} class="weekend"{% endif %}>{{ d }}{% endfor %}
+
+ {% for w in v.weeks %}{% for c in w %} +
+ {% if c.on or c.pred %}{{ drop("cy-drop") }}{% endif %} + {{ c.num }} + {% if c.symbols %}
{% for y in c.symbols %}{% if y.g == "spot" %}{{ drop() }}{% else %}{{ y.g }}{% endif %}{% endfor %}
{% endif %} + {% if c.source %}{{ c.source.g }}{% endif %} + {% if not c.future %}{% endif %} + {% if c.on %}
{{ flows(c.flow) }}
{% endif %} +
+ {% endfor %}{% endfor %} +
+
+ periodpredicted + {% if s.show_fertile %}fertileovulation{% endif %} + ♥sex☺☹mood{{ drop() }}spotting💤tired⚡headache + ✎log the day +
+
+ +
+{% endblock %} + +{% block scripts %} +{# day dialog (no browser dialogs) #} + + +{% endblock %} diff --git a/dashboard/plugins/cycle/views.py b/dashboard/plugins/cycle/views.py new file mode 100644 index 0000000..4193901 --- /dev/null +++ b/dashboard/plugins/cycle/views.py @@ -0,0 +1,322 @@ +"""Cycle tracker: everything shown is computed here from the logged period days (db.py). + +Periods: a run of period days; up to GAP unmarked days inside a run don't split it +(a forgotten day stays one period). The last one is "going on" while its last day is +today or yesterday. + +Calculated periods (source "calculated": estimates filling a gap in logging) are drawn +but left out of every number — lengths, flags, the doctor summary. + +Lengths: a **cycle** runs from one period's first day to the next one's; its usual +length is a weighted average of the last 12 believable ones (15–60 days): each counts +half as much per HALF_LIFE days of age, so recent cycles lead and years-old ones barely +matter. The setting until there are any. Same for period length (closed periods only). + +Predictions: next periods every usual-cycle-length days after the last one. Ovulation +is assumed 14 days before a period starts, fertile from 5 days before it to 1 after +(the usual textbook window — an estimate, not contraception). +""" +import calendar as _cal +import math +from datetime import date, timedelta + +from .db import PAIN_LEN, SOURCES, TAGS + +HISTORY = 12 # cycles averaged (at most) +HALF_LIFE = 180 # days: a cycle this much older counts half as much +MAX_CYCLE = 60 # longer "cycles" are taken as gaps in logging (averages, flags) +LUTEAL = 14 # ovulation -> next period, days +GAP = 2 # unmarked days that don't split a period + + +def _avg(xs, fallback, today): + """Weighted average of [(value, date)] — weight halves every HALF_LIFE days of age.""" + xs = xs[-HISTORY:] + if not xs: + return int(fallback) + w = [0.5 ** (max(0, (today - d).days) / HALF_LIFE) for _, d in xs] + return round(sum(v * k for (v, _), k in zip(xs, w)) / sum(w)) + + +def periods_of(days, calc=frozenset()): + """Sorted period days -> [{start, end, calc}] runs. calc = the run is made only of + calculated (estimated) days — shown, but left out of every number.""" + out = [] + for d in days: + if out and (d - out[-1]["end"]).days <= GAP + 1: + out[-1]["end"] = d + out[-1]["calc"] = out[-1]["calc"] and d in calc + else: + out.append({"start": d, "end": d, "calc": d in calc}) + return out + + +def _going(p, today): + return p["end"] >= today - timedelta(days=1) + + +def real_cycles(periods): + """[(length, start of the next period)] between consecutive periods that were both + logged (a cycle touching a calculated period isn't a measurement).""" + return [((b["start"] - a["start"]).days, b["start"]) for a, b in zip(periods, periods[1:]) + if not (a["calc"] or b["calc"])] + + +def stats(periods, s, today): + cyc = real_cycles(periods) + cycles = [c for c, _ in cyc] + ok = [(c, d) for c, d in cyc if 15 <= c <= MAX_CYCLE] + lens = [((p["end"] - p["start"]).days + 1, p["start"]) for p in periods if not _going(p, today) and not p["calc"]] + return {"cycle": _avg(ok, s["cycle_length"], today), "period": _avg(lens, s["period_length"], today), + "cycles": cycles, "from_data": bool(ok)} + + +def predict(periods, st, today, n=4): + """[(start, end)] of the next n predicted periods + days late (0 = not late).""" + if not periods: + return [], 0 + nxt = periods[-1]["start"] + timedelta(days=st["cycle"]) + late = (today - nxt).days if nxt < today else 0 + if late: # overdue: "any day now"; the one after counts from today + nxt = today + timedelta(days=st["cycle"]) + starts = [nxt + timedelta(days=k * st["cycle"]) for k in range(n)] + return [(a, a + timedelta(days=st["period"] - 1)) for a in starts], late + + +def fertile(starts): + """{date: "ovul" | "fertile"} before each given period start.""" + out = {} + for a in starts: + ov = a - timedelta(days=LUTEAL) + for k in range(-5, 2): + out[ov + timedelta(days=k)] = "fertile" + out[ov] = "ovul" + return out + + +def ring(st, cycle_day, show_fertile): + """SVG geometry of the status ring: the cycle as a circle, period + fertile arcs, today.""" + n = max(st["cycle"], cycle_day or 0, 1) + + def arc(d0, d1): # days d0..d1 (1-based, inclusive), as a path + a0, a1 = (d0 - 1) / n * 2 * math.pi, d1 / n * 2 * math.pi + x0, y0, x1, y1 = 50 * math.sin(a0), -50 * math.cos(a0), 50 * math.sin(a1), -50 * math.cos(a1) + big = 1 if a1 - a0 > math.pi else 0 + return f"M{x0:.2f} {y0:.2f}A50 50 0 {big} 1 {x1:.2f} {y1:.2f}" + + out = {"period": arc(1, min(st["period"], n))} + if show_fertile: + ov = st["cycle"] - LUTEAL + if ov - 5 > st["period"]: + out["fertile"] = arc(ov - 5, ov + 1) + if cycle_day: + a = (cycle_day - .5) / n * 2 * math.pi + out["dot"] = {"x": round(50 * math.sin(a), 2), "y": round(-50 * math.cos(a), 2)} + return out + + +# symbols on a calendar day for some tags: (tags, glyph, label); "spot" = a small droplet +SYMBOLS = [({"sex_prot", "sex_unprot"}, "♥", "had sex"), + ({"happy", "calm", "energetic"}, "☺", "good mood"), + ({"sensitive", "irritable", "anxious", "sad", "swings", "stressed", "unmotivated"}, "☹", "low mood"), + ({"spotting"}, "spot", "spotting"), + ({"tiredness"}, "💤", "tired"), + ({"headache"}, "⚡", "headache")] + + +def _source(key): + """{"g": symbol, "label"} of a day's source, None when logged here.""" + if key in SOURCES: + return {"g": SOURCES[key][0], "label": SOURCES[key][1]} + return None + + +def _cell_log(log): + """What a calendar day shows of its log: flow (droplet picker), whether the ✎ lights up, + a one-line summary (tooltip), and the whole log for the dialog (JSON).""" + if not log: + return {"flow": None, "logged": False, "summary": "", "log": None, "symbols": [], "source": None} + names = {k: v for g in TAGS.values() for k, v in g.items()} + bits = [] + if log["pain"]: + bits.append(f"pain {log['pain']}/5" + (f" ({PAIN_LEN[log['pain_len']]})" if log["pain_len"] in PAIN_LEN else "")) + bits += [names[t] for t in log["tags"] if t in names] + if log["note"]: + bits.append(log["note"]) + if log["source"] in SOURCES: + bits.append(SOURCES[log["source"]][1]) + return {"flow": log["flow"], "logged": bool(log["pain"] or log["tags"] or log["note"]), + "summary": " · ".join(bits), + "symbols": [{"g": g, "label": label} for tags, g, label in SYMBOLS if tags & set(log["tags"])], + "source": _source(log["source"]), + "log": {k: log[k] for k in ("flow", "pain", "pain_len", "tags", "note", "source")}} + + +def page(days, logs_for, s, offset, today=None, calc=frozenset()): + today = today or date.today() + marked = set(days) + periods = periods_of(days, calc) + st = stats(periods, s, today) + preds, late = predict(periods, st, today) + last = periods[-1] if periods else None + + # ---- status + status = {"kind": "empty"} + cycle_day = None + if last: + cycle_day = (today - last["start"]).days + 1 + if _going(last, today): + status = {"kind": "period", "day": cycle_day, "since": last["start"]} + elif late: + status = {"kind": "late", "days": late, "expected": last["start"] + timedelta(days=st["cycle"])} + else: + status = {"kind": "wait", "days": (preds[0][0] - today).days if preds else None, + "next": preds[0][0] if preds else None} + status["cycle_day"] = cycle_day + status["today_on"] = today in marked + + # ---- month grid (Monday first, 6 weeks max) + y, m = today.year, today.month + offset + y, m = y + (m - 1) // 12, (m - 1) % 12 + 1 + first = date(y, m, 1) + days_in = _cal.monthrange(y, m)[1] + g0 = first - timedelta(days=first.weekday()) + g1 = date(y, m, days_in) + timedelta(days=6 - date(y, m, days_in).weekday()) + + pred_days = {a + timedelta(days=k) for a, z in preds for k in range((z - a).days + 1)} + if status["kind"] == "period": # going on: the rest of its usual length, predicted + pred_days |= {last["start"] + timedelta(days=k) for k in range(st["period"]) + if last["start"] + timedelta(days=k) > last["end"]} + starts = [a for a, z in preds] + if last: # this cycle's window, also when the period is late + starts.append(last["start"] + timedelta(days=st["cycle"])) + fert = fertile(starts) if s["show_fertile"] else {} + logs = logs_for(g0, g1) + + weeks, d = [], g0 + while d <= g1: + row = [] + for _ in range(7): + on = d in marked + row.append({"iso": d.isoformat(), "num": d.day, "out": d.month != m, "today": d == today, + "future": d > today, "on": on, "pred": d in pred_days and not on, + "fert": fert.get(d) if not on else None, **_cell_log(logs.get(d))}) + d += timedelta(days=1) + weeks.append(row) + + return {"status": status, "stats": st, "preds": preds[:3], "late": late, + "ring": ring(st, cycle_day if status["kind"] != "late" else None, s["show_fertile"]) if last else None, + "month": first, "offset": offset, "weeks": weeks, "dows": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], + "today": today} + + +def summary(days, s, today=None, calc=frozenset()): + """Where you are now — for Health's Overview (the cycle card / tile): status (as on the + page), cycle day, the next periods, the ring, and (show_fertile) the fertile window that + matters now: {start, end, ovul, now} — this cycle's if it hasn't passed, else the next one's.""" + today = today or date.today() + periods = periods_of(days, calc) + st = stats(periods, s, today) + preds, late = predict(periods, st, today) + last = periods[-1] if periods else None + v = page(days, lambda a, z: {}, s, 0, today, calc) # status + ring, the same rules + fw = None + if last and s["show_fertile"]: + for a in [last["start"] + timedelta(days=st["cycle"])] + [p[0] for p in preds]: + ov = a - timedelta(days=LUTEAL) + if ov + timedelta(days=1) >= today: # the first window not yet over + fw = {"start": ov - timedelta(days=5), "end": ov + timedelta(days=1), "ovul": ov, + "now": ov - timedelta(days=5) <= today <= ov + timedelta(days=1), "ovul_today": ov == today} + break + return {"status": v["status"], "stats": st, "preds": preds[:3], "late": late, "ring": v["ring"], + "fertile": fw, "show_fertile": s["show_fertile"], "today": today, "empty": not last} + + +# ---- history page ---------------------------------------------------------------------- + +FLOW_NAMES = ["very light", "light", "medium", "heavy", "very heavy"] +DOCTOR_MONTHS = 12 + + +def _spread(xs): + return (min(xs), max(xs)) if xs else None + + +def flags(periods, cycles, logs, today): + """Things worth mentioning to a doctor (common guidance, not a diagnosis): [text].""" + out = [] + recent = [c for c in cycles if c <= MAX_CYCLE][-6:] # longer = a gap in logging, not a cycle + short = [c for c in recent if c < 21] + long_ = [c for c in recent if c > 35] + if len(short) >= 2: + out.append(f"{len(short)} of the last {len(recent)} cycles were shorter than 21 days.") + if len(long_) >= 2: + out.append(f"{len(long_)} of the last {len(recent)} cycles were longer than 35 days.") + if len(recent) >= 3 and max(recent) - min(recent) > 7: + out.append(f"Cycle length varies a lot: {min(recent)}–{max(recent)} days.") + done = [p for p in periods if not _going(p, today)][-6:] + longp = [p for p in done if (p["end"] - p["start"]).days + 1 > 7] + if longp: + out.append(f"{len(longp)} of the last {len(done)} periods lasted more than 7 days.") + heavy = [p for p in done if sum(1 for d, l in logs.items() if p["start"] <= d <= p["end"] and (l["flow"] or 0) >= 4) >= 3] + if heavy: + out.append(f"{len(heavy)} of the last {len(done)} periods had 3 or more heavy days.") + since = today - timedelta(days=90) + spot = [d for d, l in logs.items() if d >= since and "spotting" in l["tags"] and not l["period"]] + if spot: + out.append(f"Spotting between periods on {len(spot)} day{'s' if len(spot) != 1 else ''} in the last 3 months.") + strong = [d for d, l in logs.items() if d >= since and (l["pain"] or 0) >= 4] + if len(strong) >= 3: + out.append(f"Strong pain (4–5 of 5) on {len(strong)} days in the last 3 months.") + if periods and (today - periods[-1]["start"]).days > 90: + out.append(f"No period for {(today - periods[-1]['start']).days} days.") + return out + + +def history(days, logs, s, today=None): + """/cycle/history: tiles, every period (newest first), the doctor summary.""" + today = today or date.today() + calc = {d for d, l in logs.items() if l.get("source") == "calculated"} + periods = periods_of(days, calc) + real = [p for p in periods if not p["calc"]] + st = stats(periods, s, today) + names = {k: v for g in TAGS.values() for k, v in g.items()} + + rows = [] + for i, p in enumerate(periods): + nxt = periods[i + 1]["start"] if i + 1 < len(periods) else None + inside = [l for d, l in logs.items() if p["start"] <= d <= p["end"]] + flow = max((l["flow"] or 0 for l in inside if l["period"]), default=0) + pain = max((l["pain"] or 0 for l in inside), default=0) + srcs = [_source(k) for k in sorted({l.get("source") for l in inside if l["period"] and l.get("source")})] + rows.append({"start": p["start"], "end": p["end"], "going": _going(p, today), "sources": srcs, "calc": p["calc"], + "days": (p["end"] - p["start"]).days + 1, "cycle": (nxt - p["start"]).days if nxt else None, + "flow": FLOW_NAMES[flow - 1] if flow else "", "pain": pain}) + rows.reverse() + + # doctor: the last DOCTOR_MONTHS months + since = today - timedelta(days=DOCTOR_MONTHS * 30) + dp = [p for p in real if p["start"] >= since] + dcycles = [c for c, d in real_cycles(periods) if d >= since and c <= MAX_CYCLE and d - timedelta(days=c) >= since] + dlens = [(p["end"] - p["start"]).days + 1 for p in dp if not _going(p, today)] + dlogs = {d: l for d, l in logs.items() if d >= since} + counts = {} + for l in dlogs.values(): + for t in l["tags"]: + if t in TAGS["symptoms"] or t in TAGS["mood"]: + counts[t] = counts.get(t, 0) + 1 + pain_days = [l["pain"] for l in dlogs.values() if l["pain"]] + doctor = { + "since": max(since, dp[0]["start"]) if dp else since, "today": today, + "last": real[-1]["start"] if real else None, + "periods": len(dp), + "cycle": round(sum(dcycles) / len(dcycles)) if dcycles else None, "cycle_range": _spread(dcycles), + "period": round(sum(dlens) / len(dlens)) if dlens else None, "period_range": _spread(dlens), + "symptoms": sorted(((names[t], n) for t, n in counts.items()), key=lambda x: -x[1])[:10], + "pain_days": len(pain_days), "pain_avg": round(sum(pain_days) / len(pain_days), 1) if pain_days else None, + "flags": flags(real, st["cycles"], logs, today), + } + ok = [c for c in st["cycles"] if 15 <= c <= MAX_CYCLE][-6:] + return {"stats": st, "rows": rows, "doctor": doctor, "today": today, + "cycle_range": _spread(ok), "tracked": len(st["cycles"]), + "last": real[-1] if real else None} diff --git a/dashboard/plugins/food/__init__.py b/dashboard/plugins/food/__init__.py new file mode 100644 index 0000000..f7ebbef --- /dev/null +++ b/dashboard/plugins/food/__init__.py @@ -0,0 +1,488 @@ +"""Food diary: what you ate, per meal, against your daily targets. + + /food a day (?d=YYYY-MM-DD): the week strip, the meals with their foods, + energy ring + nutrient bars, the describe box (a local language model + turns "2 eggs and toast for breakfast" into entries to confirm) + /food/history energy per day / week stacked by macro, averages, most eaten (?r=1m|3m|1y|all) + /food/foods My foods: your own food database (values per 100 g, portions) and your meals + (made of other foods: the meal builder) — add, edit, delete + /food/export.csv every entry + /food/api/… JSON writes + the food suggestions (same-origin only, like the core's); + api/archive = every Open Food Facts product, searched on the sync server + (its /v1/food/search, with this dashboard's sync token); api/product keeps + a picked one (food.db `product`, synced) + +Data: dash_data/food/food.db (the diary, SQLite, see db.py; Lifesum entries come in with +Health's Health Connect import) + foods.db (the food database, read-only: fdc.py builds it +from USDA FoodData Central, fooddb.py reads it). The energy target comes from Health's +energy estimate (ctx.ask("health", "energy"), views.plan). A section of Health, like the cycle tracker. Never shown on the +wall screens. +""" +import csv +import io +import json +import os +import re +import urllib.parse +from contextlib import closing +from datetime import date, timedelta + +from flask import Response, abort, jsonify, render_template, request + +from . import db, fooddb, parse, sugar, views + +META = { + "title": "Food diary", + "glyph": "🍴", + "glyph_color": "#7fd6a3", + "description": "Log what you eat per meal — by hand, from foods you had before, or by describing it " + "(a local language model fills in the rest). Energy and nutrients against your targets.", + "links": [{"label": "Open the diary", "href": "/food"}, {"label": "History", "href": "/food/history"}], + "settings": [ + {"key": "goal_rate", "label": "Weight goal", "type": "select", "default": 0.0, "options": views.RATES, + "help": "Sets the energy target: your usual day in Health minus what that rate needs (1 kg ≈ 7700 kcal). " + "The box above shows the numbers."}, + {"key": "kcal_target", "label": "Energy per day (kcal) — your own", "type": "number", "default": 0, + "min": 0, "max": 6000, "integer": True, "help": "0 = the calculated target (above). Any other number replaces it."}, + {"key": "macro_preset", "label": "Protein / carbs / fat", "type": "select", "default": "balanced", + "options": [[k, f"{p[0]}" + (f" — {p[1]} / {p[2]} / {p[3]} %" if p[1] else " — the three fields below")] + for k, p in views.PRESETS.items()]}, + {"key": "custom_protein", "label": "Custom: protein (% of the energy)", "type": "number", "default": 25, + "min": 5, "max": 60, "integer": True}, + {"key": "custom_carbs", "label": "Custom: carbs (%)", "type": "number", "default": 45, + "min": 5, "max": 80, "integer": True}, + {"key": "custom_fat", "label": "Custom: fat (%)", "type": "number", "default": 30, + "min": 10, "max": 70, "integer": True, "help": "The three should add up to 100."}, + {"key": "fiber_min", "label": "Fibre, at least (g)", "type": "number", "default": 25, + "min": 0, "max": 100, "integer": True}, + {"key": "sugar_max", "label": "Sugar, at most (g)", "type": "number", "default": 50, + "min": 0, "max": 300, "integer": True}, + {"key": "sodium_max", "label": "Sodium, at most (mg)", "type": "number", "default": 2000, + "min": 0, "max": 10000, "integer": True, "help": "WHO: under 2000 mg (= 5 g salt)."}, + {"key": "use_model", "label": "Describe box (language model) on", "type": "bool", "default": True, + "help": "Off: the diary has only the form; nothing is sent to the model."}, + {"key": "model_url", "label": "Language model address (Ollama)", "type": "text", "default": "", + "max": 200, "help": "e.g. http://localhost:11434 — empty = the describe box is off."}, + {"key": "model", "label": "Model", "type": "text", "default": "qwen3:1.7b", "max": 80}, + ], + # what syncs between devices (sync.py / syncdb.py): My foods, then the diary pointing at them; + # imported entries keep their import id, a meal's ingredients ("my:ID" in recipe) travel as ids + "sync": {"food.db": { + "product": {"key": "'p:' || NEW.food_id"}, + "food": {"refs_in": {"recipe": "my:"}}, + "entry": {"key": "CASE WHEN NEW.src_id IS NOT NULL THEN 'src:' || NEW.src_id END", "refs": {"my_food_id": "food"}}, + }}, +} +PARSE_MAX = 1000 # characters in the describe box + + +def validate_settings(sec): # pluginhost: cross-field check + if sec.get("macro_preset") == "custom": + total = sum(sec.get(k) or 0 for k in ("custom_protein", "custom_carbs", "custom_fat")) + if total != 100: + return "custom_fat", f"Protein + carbs + fat make {total} %, not 100." + return None + + +def register(ctx): + # Settings ▸ Food for the phone app (the Health summary carries it as meta:food): the same targets there + ctx.provide("diet", lambda: {"goal_rate": float(ctx.settings.get("goal_rate") or 0), "split": list(views.split(ctx.settings)), + "kcal_target": int(ctx.settings.get("kcal_target") or 0), + "fiber_min": int(ctx.settings.get("fiber_min") or 25), + "sugar_max": int(ctx.settings.get("sugar_max") or 50), + "sodium_max": int(ctx.settings.get("sodium_max") or 2000)}) + bp = ctx.blueprint("/food") + ctx.warm("/food", "/food/history", "/food/foods") + ctx.nav("Food", "/food") + here = os.path.dirname(os.path.abspath(__file__)) + + @bp.context_processor + def asset_version(): # cache-buster for food.css / .js + st = os.path.join(here, "static") + return {"asset_v": "%x" % int(max(os.path.getmtime(os.path.join(st, f)) for f in os.listdir(st)))} + + def con(): # one connection per request, closed after + return closing(db.connect(ctx.data_path("food.db"))) + + foods_db = ctx.data_path("foods.db") # the food database (fdc.py builds it; read-only here) + bundled = os.path.join(here, "..", "..", "..", "app", "assets", "foods.db") + if not os.path.exists(foods_db) and os.path.exists(bundled): # run from the repo: start with the app's copy + import shutil # (install.sh does the same for /opt/dashboard) + shutil.copyfile(bundled, foods_db) + os.chmod(foods_db, 0o600) + + energy_memo = {"key": None, "val": None} + + def energy(): # Health's energy summary (weight, resting, usual day) or None + key = (ctx.ask("health", "version"), date.today()) + if energy_memo["key"] != key: + energy_memo.update(key=key, val=ctx.ask("health", "energy")) + return energy_memo["val"] + + def health_version(): # pages show targets worked out from Health's data + return ctx.ask("health", "version") + + def version(): # Health caches pages with our blocks on them + return ctx.data_version("food.db") + + def summary(): + with con() as c: + return views.summary(lambda a, z: db.entries_between(c, a, z), ctx.settings, date.today(), energy()) + + def report_part(days): + with con() as c: + r = views.report(lambda a, z: db.day_totals(c, a, z), ctx.settings, days, date.today()) + return render_template("food/_report.html", r=r) + + ctx.inside("health", add=("Food", "/food#add"), report=report_part, + blocks=[{"id": "food.card", "kind": "card", "label": "Food today", "w": 33, + "render": lambda: render_template("food/_ovcard.html", s=summary()), "version": version}, + {"id": "food.tile", "kind": "tile", "label": "Energy eaten today", "w": 20, + "href": "/food", "render": lambda: render_template("food/_ovtile.html", s=summary()), + "version": version}]) + + def body(): + if not ctx.same_origin(): + abort(403) + return request.get_json(silent=True) or {} + + def parser_on(): + return bool(ctx.settings.get("use_model") and ctx.settings.get("model_url")) + + def archive_on(): # the archive is searched through this dashboard's sync + import sync + return sync.configured() + + def common(): # what every page's dialogs need + return {"fields": db.FIELDS, "units": db.UNITS, "meals": views.MEAL_LABELS, "parser": parser_on(), + "model_off": not ctx.settings.get("use_model"), "has_db": os.path.exists(foods_db), + "archive": archive_on()} + + ctx.settings_panel("food/_settings.html", + lambda: {"p": views.plan(ctx.settings, energy()), "presets": views.presets(ctx.settings, energy()), + "e": energy(), "has_db": os.path.exists(foods_db)}) + + def added_of(c): + """entry → its added sugar (g), sugar.py — the foods it was made from looked up once per page.""" + foods, mine = {}, {} + + def food_of(fid): + if fid not in foods: + foods[fid] = db_food(c, int(fid)) + return foods[fid] + + def my_food_of(mid): + if mid not in mine: + try: + mine[mid] = db.my_food(c, int(mid)) + except (TypeError, ValueError): + mine[mid] = None + return mine[mid] + return lambda r: sugar.entry_added(r, food_of, my_food_of) + + @bp.route("/", strict_slashes=False) + @ctx.cached_page("food.db", extra=health_version) + def index(): + today = date.today() + try: + d = min(today + timedelta(days=views.AHEAD), date.fromisoformat(request.args.get("d", ""))) + except ValueError: + d = today + act = ctx.ask("health", "day", d) if d <= today else None + with con() as c: + v = views.day(lambda a, z: db.entries_between(c, a, z), lambda a, z: db.day_totals(c, a, z), + ctx.settings, d, today, energy(), act, added_of(c)) + return render_template("food/day.html", v=v, page="food", tab="day", **common()) + + @bp.route("/history") + @ctx.cached_page("food.db", extra=health_version) + def history(): + today = date.today() + with con() as c: + v = views.history(lambda a, z: db.day_totals(c, a, z), lambda a, z: db.top_foods(c, a, z), + db.first_day(c), ctx.settings, request.args.get("r"), today, energy()) + now = views.day(lambda a, z: db.entries_between(c, a, z), lambda a, z: db.day_totals(c, a, z), + ctx.settings, today, today, energy(), ctx.ask("health", "day", today), added_of(c)) # the left column + return render_template("food/history.html", v=v, now=now, page="food", tab="history", **common()) + + @bp.route("/foods") + @ctx.cached_page("food.db", extra=health_version) + def my_foods_page(): # My foods: your own food database (values per 100 g, portions) + today = date.today() + with con() as c: + foods = db.my_foods(c) + now = views.day(lambda a, z: db.entries_between(c, a, z), lambda a, z: db.day_totals(c, a, z), + ctx.settings, today, today, energy(), ctx.ask("health", "day", today), added_of(c)) # the left column + return render_template("food/foods.html", foods=foods, now=now, page="food", tab="foods", **common()) + + @bp.route("/export.csv") + def export_csv(): + with con() as c: + rows = db.entries_between(c, "0000-01-01", "9999-12-31") + cols = ["day", "time", "meal", "name", "amount", "unit", "grams"] + list(db.FIELDS) + db.NUTRIENTS + ["note", "source", "food_id", "my_food_id"] + buf = io.StringIO() + w = csv.writer(buf) + w.writerow(cols) + for r in rows: + w.writerow(["" if r[k] is None else (round(r[k], 2) if isinstance(r[k], float) else r[k]) for k in cols]) + return Response("\ufeff" + buf.getvalue(), mimetype="text/csv", # BOM: Excel / LibreOffice read UTF-8 + headers={"Content-Disposition": f'attachment; filename="food-{date.today()}.csv"'}) + + def db_food(c, fid): + """A food of the database: foods.db's, else a product kept from the archive.""" + return fooddb.food(foods_db, fid) or db.product(c, fid) + + def resolve(c, ref): + """'my:ID' → one of My foods, 'usda:ID' → the food database's (or a kept product); None if unknown.""" + kind, _, fid = str(ref or "").partition(":") + if not fid.isdigit(): + return None + return db.my_food(c, int(fid)) if kind == "my" else db_food(c, int(fid)) if kind == "usda" else None + + def archive(params): + """GET the sync server's /v1/food/search → its items (RuntimeError: not set up / unreachable).""" + import sync + st = sync.load_state() + if not sync.configured(st): + raise RuntimeError("Sync isn't set up on this dashboard — the archive is searched through it.") + q = urllib.parse.urlencode({k: v for k, v in params.items() if v}) + try: + return sync.call(st, "GET", "/v1/food/search?" + q).get("items", []) + except OSError: + raise RuntimeError("The sync server can't be reached.") + + def lookup(c, name): + """The describe box: the likeliest of My foods (every word in its name), else the database's.""" + mine = db.my_foods(c, name, limit=1) + return mine[0] if mine else fooddb.best(foods_db, name) + + def ref_of(e): + return f"my:{e['my_food_id']}" if e.get("my_food_id") else f"usda:{e['food_id']}" if e.get("food_id") else None + + @bp.route("/api/foods") + def api_foods(): # ?q= → {recent, mine, db, products} — the form's suggestions (a barcode: its product) + q = request.args.get("q", "")[:60] + code = q.strip() if re.fullmatch(r"\s*\d{8,14}\s*", q) else None + with con() as c: + if code: # scanned / typed off the pack + return jsonify(recent=[], mine=[], db=[], products=fooddb.by_barcode(foods_db, code) or db.products(c, barcode=code)) + rows = db.foods(c, q, limit=5) + mine = db.my_foods(c, q, limit=8) + kept = db.products(c, q, limit=4, fold=sugar.fold) # picked from the archive before + keep = ["id", "name", "amount", "unit", "grams", "meal", "times"] + list(db.FIELDS) + recent = [dict({k: r.get(k) for k in keep}, food=ref_of(r)) for r in rows] + found = fooddb.search(foods_db, q, limit=16) # generic (USDA) and shop products (Open Food Facts) + ids = {f["id"] for f in kept} + return jsonify(recent=recent, mine=mine, db=[f for f in found if f["kind"] == "usda"][:8], + products=(kept + [f for f in found if f["kind"] == "off" and f["id"] not in ids])[:8]) + + @bp.route("/api/archive") + def api_archive(): # ?q, country, brand, nutriscore, barcode → {items} from the archive (sync server) + p = {k: request.args.get(k, "")[:60] for k in ("q", "country", "brand", "category", "nutriscore", "barcode")} + try: + items = archive(dict(p, limit=25)) + except RuntimeError as e: + return jsonify(error=str(e)), 502 + with con() as c: # ones you have here already say so + for f in items: + f["saved"] = bool(fooddb.food(foods_db, f["id"]) or db.product(c, f["id"])) + return jsonify(items=items) + + @bp.route("/api/product", methods=["POST"]) + def api_product(): # {id, barcode} — keep a product picked from the archive → {food} + d = body() + code = re.sub(r"\D", "", str(d.get("barcode") or "")) + with con() as c: + have = db_food(c, int(d.get("id") or 0)) if str(d.get("id") or "").isdigit() else None + if have: + return jsonify(food=have) + try: + found = [f for f in archive({"barcode": code}) if f.get("id") == d.get("id")] if code else [] + except RuntimeError as e: + return jsonify(error=str(e)), 502 + if not found: + return jsonify(error="The archive doesn't have that product (any more)."), 404 + try: + return jsonify(food=db.save_product(c, found[0])) + except db.Invalid as e: + return jsonify(error=str(e)), 400 + + @bp.route("/api/food") + def api_food(): # ?ref=my:ID | usda:ID → the food: per 100 g + portions (a meal: + its ingredients' foods) + with con() as c: + f = resolve(c, request.args.get("ref")) + if f and f.get("recipe"): + for i in f["recipe"]["ingredients"]: + i["f"] = resolve(c, i["food"]) # None = gone since + return jsonify(food=f) if f else (jsonify(error="That food is gone."), 404) + + def prepare(c, d): + """A submitted entry → (columns to save, food to write or None), nothing written yet. + With `food` (a ref) and/or `edit` ({name, per100, portions, note} — the food's values, + changed or new), the entry's numbers are worked out here: values per 100 g × the grams + of amount × unit. edit + a USDA food = a new food in My foods (a copy); edit + one of + My foods = that food changed; edit alone = a new food. Without either: the numbers + come as typed (older entries, the describe box's estimates).""" + food = resolve(c, d["food"]) if d.get("food") else None + if d.get("food") and not food: + raise db.Invalid("name", "That food is gone — pick it again.") + edit = d.get("edit") + if edit and food and food.get("recipe"): + raise db.Invalid("name", "That's a meal — change it with Edit meal.") + if not (food or edit): + return dict(d, food_id=None, my_food_id=None), None + f = food + if edit: + try: + v = db.clean_food(edit, base=food) + except db.Invalid as e: + raise db.Invalid("food." + e.field, str(e)) + f = {"name": v["name"], "per100": {k: v[k] for k in db.FOOD_COLS}, "portions": json.loads(v["portions"])} + try: + amount = float(str(d.get("amount") or "").replace(",", ".")) + except ValueError: + amount = None + g, label = fooddb.portion(f, amount, d.get("unit") or "g") + if not g: + raise db.Invalid("amount", "How much — amount and unit?") + n = fooddb.nutrients(f, g) + e = {k: d.get(k) for k in ("id", "day", "time", "meal", "note")} + e.update({k: n[k] for k in db.FIELDS}, name=f["name"], amount=amount, unit=label, grams=round(g, 2), + food_id=food["id"] if food and food["kind"] != "my" and not edit else None, + my_food_id=food["id"] if food and food["kind"] == "my" else None) + db.clean(e) # day, meal … checked before anything is written + extra = {k: n[k] for k in db.NUTRIENTS} + return dict(e, _extra=extra), ((edit, food) if edit else None) + + def commit(c, prep, source): + e, write = prep + extra = e.pop("_extra", None) + if write: + edit, food = write + mine = food if food and food["kind"] == "my" else None + e["my_food_id"] = db.save_food(c, edit, base=food, fid=mine["id"] if mine else None) + return db.save(c, e, source=source, extra=extra) + + @bp.route("/api/entry", methods=["POST"]) + def api_entry(): # {id?, food?, edit?, from?, day, time, meal, amount, unit, note (+ name, kcal … without a food)} + d = body() + with con() as c: + try: + return jsonify(ok=True, id=commit(c, prepare(c, d), "manual")) + except db.Invalid as e: + return jsonify(error=str(e), field=e.field), 400 + + @bp.route("/api/entries", methods=["POST"]) + def api_entries(): # {items: [entry, …]} — the describe box's confirmed list, all or nothing + items = body().get("items") or [] + if not isinstance(items, list) or not items: + return jsonify(error="Nothing to save."), 400 + with con() as c: + try: + preps = [] + for i, it in enumerate(items): + try: + p = prepare(c, it) + db.clean(p[0]) + preps.append(p) + except db.Invalid as e: + raise db.Invalid(f"{i}.{e.field}", str(e)) + ids = [commit(c, p, "parsed") for p in preps] + except db.Invalid as e: + return jsonify(error=str(e), field=e.field), 400 + return jsonify(ok=True, ids=ids) + + @bp.route("/api/myfood", methods=["POST"]) + def api_myfood(): # {id?, name, per100, portions, note} — My foods page + d = body() + with con() as c: + try: + fid = int(d["id"]) if d.get("id") else None + base = db.my_food(c, fid) if fid else None + if fid and not base: + raise db.Invalid("name", "That food is gone.") + if base and base.get("recipe"): + raise db.Invalid("name", "That's a meal — change it with Edit meal.") + return jsonify(ok=True, id=db.save_food(c, d, base=base, fid=fid)) + except db.Invalid as e: + return jsonify(error=str(e), field="food." + e.field), 400 + + @bp.route("/api/meal", methods=["POST"]) + def api_meal(): # {id?, name, ingredients, done_grams, portions, note, replace?, log?} — the meal builder + # replace = [entry ids] (a meal made of entries already logged) + log = {day, meal, time}: + # those entries become one entry of the meal, its whole weight — the day's numbers stay the same + d = body() + with con() as c: + try: + fid = int(d["id"]) if d.get("id") else None + if fid and not db.my_food(c, fid): + raise db.Invalid("name", "That meal is gone.") + ids = [int(x) for x in (d.get("replace") or [])] + if ids: + if any(not db.entry(c, x) for x in ids): + raise db.Invalid("replace", "Some of those entries are gone — reload the page.") + log = d.get("log") or {} + db.clean(dict(log, name="-", kcal=0)) # day / meal / time valid before anything is written + fid = db.save_meal(c, d, lambda ref: resolve(c, ref), fid) + eid = None + if ids: + eid = commit(c, prepare(c, {**{k: log.get(k) for k in ("day", "meal", "time")}, "food": f"my:{fid}", + "amount": 1, "unit": "whole meal", "note": ""}), "manual") + for x in ids: + db.delete(c, x) + return jsonify(ok=True, id=fid, ref=f"my:{fid}", entry=eid) # entry: the one replacing them + except db.Invalid as e: + return jsonify(error=str(e), field=e.field), 400 + except (TypeError, ValueError): + return jsonify(error="Which entries?"), 400 + + @bp.route("/api/myfood/delete", methods=["POST"]) + def api_myfood_delete(): # {id} — hidden; entries made from it keep their numbers + try: + fid = int(body().get("id")) + except (TypeError, ValueError): + return jsonify(error="Which food?"), 400 + with con() as c: + db.delete_food(c, fid) + return jsonify(ok=True) + + @bp.route("/api/entry/delete", methods=["POST"]) + def api_delete(): # {id} + try: + eid = int(body().get("id")) + except (TypeError, ValueError): + return jsonify(error="Which entry?"), 400 + with con() as c: + db.delete(c, eid) + return jsonify(ok=True) + + @bp.route("/api/entry/move", methods=["POST"]) + def api_move(): # {id, meal} — dragged into another meal + d = body() + try: + eid = int(d.get("id")) + except (TypeError, ValueError): + return jsonify(error="Which entry?"), 400 + with con() as c: + try: + db.move(c, eid, d.get("meal")) + except db.Invalid as e: + return jsonify(error=str(e), field=e.field), 400 + return jsonify(ok=True) + + @bp.route("/api/parse", methods=["POST"]) + def api_parse(): # {text} → {items} to confirm; nothing saved + text = str(body().get("text") or "").strip()[:PARSE_MAX] + if not text: + return jsonify(error="Write what you ate first."), 400 + if not ctx.settings.get("use_model"): + return jsonify(error="The describe box is switched off — Settings ▸ Food."), 503 + with con() as c: + known = [f["name"] for f in db.foods(c, limit=40)] + try: + items = parse.parse(text, ctx.settings, known, lambda n: db.match(c, n), lambda n: lookup(c, n)) + except parse.Unavailable as e: + return jsonify(error=str(e)), 503 + if not items: + return jsonify(error="No food found in that — try naming the foods."), 422 + return jsonify(items=items) diff --git a/dashboard/plugins/food/db.py b/dashboard/plugins/food/db.py new file mode 100644 index 0000000..4241671 --- /dev/null +++ b/dashboard/plugins/food/db.py @@ -0,0 +1,527 @@ +"""Food diary storage: dash_data/food/food.db. + +One `entry` per food logged: day, time, meal, name, the portion as typed (amount + unit, +e.g. 2 "pcs", 150 "g", 1 "slice, regular" — empty for imports, Lifesum exports no portions), +the food database's food it came from + grams (`food_id`, `grams`; foods.db), energy + the main +nutrients as columns (g, except kcal and the mg ones), everything else Health Connect knows +in `micros` (JSON, its field names → value in g), a note. `source`: "manual" (the form), +"parsed" (the describe box, after you confirmed it) or the app an import came from +("lifesum"); `src_id` makes a re-import replace — so editing or deleting an imported entry +lasts only until the next import of that export. An entry made from a food keeps its numbers +(worked out on save from the food's values per 100 g × grams): changing the food later +doesn't change what you ate then. + +My foods (`food`): your own food database — values per 100 g (FOOD_COLS), household portions +(JSON [{label, grams}]), `based_on` = the USDA food it was copied from (fdc_id + name); a +**meal** (soup, a salad you make) is one too, with `recipe` = its ingredients (save_meal works +its values per 100 g out of them). Entries +point at one with `my_food_id` (or at a USDA food with `food_id`). Deleting one only hides it +(`gone`): entries keep pointing at it. `sugar_kind` (added / dairy / natural, NULL = estimated): +how its sugar counts when the estimate (sugar.py) gets it wrong. + +Products (`product`): shop products picked from the Open Food Facts archive on the sync server +(not in the local foods.db) — kept here as they came (`data`, fooddb's shape), so entries made from +them (`food_id` = OFF_ID + barcode, like foods.db's products) find them again everywhere. Synced, +keyed by that id. + +health/hc.py imports Health Connect nutrition (Lifesum) through import_health_connect. +""" +import json +import os +import sqlite3 +from datetime import datetime, timedelta, timezone + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS entry ( + id INTEGER PRIMARY KEY, + day TEXT NOT NULL, -- YYYY-MM-DD + time TEXT, -- HH:MM, when known + meal TEXT, -- breakfast / lunch / dinner / snack + name TEXT NOT NULL DEFAULT '', + kcal REAL, + protein REAL, carbs REAL, sugar REAL, fiber REAL, + fat REAL, sat_fat REAL, mono_fat REAL, poly_fat REAL, trans_fat REAL, + sodium_mg REAL, cholesterol_mg REAL, potassium_mg REAL, + micros TEXT NOT NULL DEFAULT '{}', + source TEXT NOT NULL, -- e.g. "lifesum" (via Health Connect), "manual", "parsed" + src_id TEXT UNIQUE, + amount REAL, -- the portion as typed: 2 (pcs), 150 (g), 1 (slice, regular) … + unit TEXT, + note TEXT NOT NULL DEFAULT '', + food_id INTEGER, -- the food database's food it was taken from (foods.db, fdc_id) + grams REAL, -- how much of it, when known + my_food_id INTEGER -- or: one of My foods (food.id) +); +CREATE INDEX IF NOT EXISTS entry_day ON entry (day); +CREATE TABLE IF NOT EXISTS food ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + kcal REAL, protein REAL, carbs REAL, sugar REAL, fiber REAL, -- per 100 g + fat REAL, sat_fat REAL, mono_fat REAL, poly_fat REAL, trans_fat REAL, + sodium_mg REAL, cholesterol_mg REAL, potassium_mg REAL, + portions TEXT NOT NULL DEFAULT '[]', -- [{"label": "cup", "grams": 150}, …] + based_on INTEGER, -- the USDA food (fdc_id) it was copied from + based_on_name TEXT, + note TEXT NOT NULL DEFAULT '', + created TEXT NOT NULL, + updated TEXT NOT NULL, + gone INTEGER NOT NULL DEFAULT 0, -- deleted: hidden, entries still point at it + recipe TEXT, -- a meal: {"ingredients": [{food, name, amount, unit, grams}], "done_grams"} + sugar_kind TEXT -- added / dairy / natural: how its sugar counts (NULL = estimated, sugar.py) +); +CREATE TABLE IF NOT EXISTS product ( + id INTEGER PRIMARY KEY, + food_id INTEGER NOT NULL UNIQUE, -- off.OFF_ID + barcode: the id in foods.db / the archive (= entry.food_id) + name TEXT NOT NULL, + brand TEXT NOT NULL DEFAULT '', + barcode TEXT, + data TEXT NOT NULL, -- the product as fooddb / the archive give it (per100, portions, sugars_in …), JSON + added TEXT NOT NULL +); +""" +ADDED = {"amount": "REAL", "unit": "TEXT", "note": "TEXT NOT NULL DEFAULT ''", # columns newer than the first food.db + "food_id": "INTEGER", "grams": "REAL", "my_food_id": "INTEGER"} +FOOD_ADDED = {"recipe": "TEXT", "sugar_kind": "TEXT"} # columns newer than the first `food` table +SUGAR_KINDS = ("added", "dairy", "natural") # My foods' sugar_kind (sugar.py) + +MEAL_KEYS = ("breakfast", "lunch", "dinner", "snack") +AHEAD = 60 # days ahead an entry may be (planning) — views.AHEAD +MEALS = {1: "breakfast", 2: "lunch", 3: "dinner", 4: "snack"} # Health Connect meal_type +# column → Health Connect field (g; *1000 for the _mg ones) +MAIN = {"protein": "protein", "carbs": "total_carbohydrate", "sugar": "sugar", "fiber": "dietary_fiber", + "fat": "total_fat", "sat_fat": "saturated_fat", "mono_fat": "monounsaturated_fat", + "poly_fat": "polyunsaturated_fat", "trans_fat": "trans_fat", "sodium_mg": "sodium", + "cholesterol_mg": "cholesterol", "potassium_mg": "potassium"} +SKIP = {"row_id", "uuid", "last_modified_time", "client_record_id", "client_record_version", "device_info_id", + "app_info_id", "start_time", "start_zone_offset", "end_time", "end_zone_offset", "local_date", "meal_type", + "meal_name", "energy", "energy_from_fat", "dedupe_hash", "recording_method", "device_data_provider_id", + "local_date_time_start_time", "local_date_time_end_time"} +# what the form edits: column → (label, unit, max); kcal first +# (in the form's two columns: protein | fibre, carbs | sugar, fat | saturated, sodium) +FIELDS = {"kcal": ("Energy", "kcal", 10000), "protein": ("Protein", "g", 1000), "fiber": ("Fibre", "g", 500), + "carbs": ("Carbs", "g", 1000), "sugar": ("of which sugar", "g", 1000), "fat": ("Fat", "g", 1000), + "sat_fat": ("of which saturated", "g", 1000), "sodium_mg": ("Sodium", "mg", 50000)} +NUTRIENTS = [k for k in MAIN if k not in FIELDS] # kept as they are, not edited +FOOD_COLS = ["kcal", "protein", "carbs", "sugar", "fiber", "fat", "sat_fat", "mono_fat", "poly_fat", "trans_fat", + "sodium_mg", "cholesterol_mg", "potassium_mg"] # = fdc.COLS (per 100 g) +UNITS = ("g", "ml", "pcs", "slice", "cup", "tbsp", "tsp", "portion") +REUSE = ("manual", "parsed") # entries worth offering again; imports (Lifesum) are too rough — kept, never reused +_REUSE_SQL = f"source IN ({', '.join(repr(x) for x in REUSE)})" + + +class Invalid(ValueError): + def __init__(self, field, msg): + super().__init__(msg) + self.field = field + + +def connect(path): + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + con = sqlite3.connect(path, timeout=10) + con.row_factory = sqlite3.Row + con.executescript(SCHEMA) + for table, added in (("entry", ADDED), ("food", FOOD_ADDED)): + have = {r[1] for r in con.execute(f"PRAGMA table_info({table})")} + for col, decl in added.items(): + if col not in have: + con.execute(f"ALTER TABLE {table} ADD COLUMN {col} {decl}") + os.chmod(path, 0o600) + return con + + +def _row(r): + d = dict(r) + d["micros"] = json.loads(d["micros"] or "{}") + return d + + +def entries_between(con, a, z): + """Entries a ≤ day ≤ z (ISO strings), in the order they were logged (the time of day isn't + asked any more — older entries may still have one).""" + return [_row(r) for r in con.execute( + "SELECT * FROM entry WHERE day BETWEEN ? AND ? ORDER BY day, id", (a, z))] + + +def day_totals(con, a, z): + """{day: {kcal, protein, …, n}} for a ≤ day ≤ z — the days with anything logged.""" + cols = list(FIELDS) + ["fat", "mono_fat", "poly_fat"] + cols = list(dict.fromkeys(cols)) + out = {} + for r in con.execute(f"SELECT day, COUNT(*) AS n, {', '.join(f'SUM({c}) AS {c}' for c in cols)} " + "FROM entry WHERE day BETWEEN ? AND ? GROUP BY day", (a, z)): + out[r["day"]] = dict(r) + return out + + +def first_day(con): + r = con.execute("SELECT MIN(day) FROM entry").fetchone() + return r[0] + + +def entry(con, eid): + r = con.execute("SELECT * FROM entry WHERE id = ?", (eid,)).fetchone() + return _row(r) if r else None + + +def foods(con, q="", limit=12): + """Foods eaten before, for the form's suggestions: one per name (the latest portion of it), + the most eaten first; q matches anywhere in the name. Only your own entries (REUSE).""" + rows = con.execute( + "SELECT e.*, n.times FROM entry e JOIN (SELECT LOWER(TRIM(name)) AS k, MAX(id) AS last, COUNT(*) AS times " + f"FROM entry WHERE name != '' AND {_REUSE_SQL} GROUP BY k) n ON e.id = n.last " + "WHERE LOWER(e.name) LIKE ? ORDER BY (LOWER(e.name) LIKE ?) DESC, n.times DESC, e.day DESC LIMIT ?", + (f"%{q.strip().lower()}%", f"{q.strip().lower()}%", limit)) + return [_row(r) for r in rows] + + +def match(con, name): + """Your latest entry of exactly this food (case and spaces ignored; REUSE sources), or None.""" + r = con.execute(f"SELECT * FROM entry WHERE LOWER(TRIM(name)) = ? AND {_REUSE_SQL} ORDER BY day DESC, id DESC LIMIT 1", + (name.strip().lower(),)).fetchone() + return _row(r) if r else None + + +def top_foods(con, a, z, limit=12): + return [dict(r) for r in con.execute( + "SELECT MIN(name) AS name, COUNT(*) AS times, AVG(kcal) AS kcal, SUM(kcal) AS total FROM entry " + "WHERE day BETWEEN ? AND ? AND name != '' GROUP BY LOWER(TRIM(name)) ORDER BY times DESC, total DESC LIMIT ?", + (a, z, limit))] + + +def _num(d, k, hi, lo=0): + v = d.get(k) + if v in (None, ""): + return None + try: + v = float(str(v).replace(",", ".")) + except ValueError: + raise Invalid(k, "Not a number.") + if not lo <= v <= hi: + raise Invalid(k, f"Should be {lo}–{hi}.") + return round(v, 3) + + +def clean(d): + """A submitted entry → the columns to write (raises Invalid naming the field).""" + try: + day = datetime.strptime(str(d.get("day", "")), "%Y-%m-%d").date() + except ValueError: + raise Invalid("day", "Pick a day.") + if day > datetime.now().date() + timedelta(days=AHEAD): + raise Invalid("day", f"At most {AHEAD} days ahead.") + t = (d.get("time") or "").strip() + if t: + try: + t = datetime.strptime(t, "%H:%M").strftime("%H:%M") + except ValueError: + raise Invalid("time", "Use HH:MM.") + name = " ".join(str(d.get("name") or "").split())[:120] + if not name: + raise Invalid("name", "What was it?") + meal = d.get("meal") + if meal not in MEAL_KEYS: + raise Invalid("meal", "Pick a meal.") + out = {"day": day.isoformat(), "time": t or None, "meal": meal, "name": name, + "amount": _num(d, "amount", 100000), "unit": (str(d.get("unit") or "").strip()[:60] or None), + "note": str(d.get("note") or "").strip()[:2000], "grams": _num(d, "grams", 100000)} + try: + out["food_id"] = int(d["food_id"]) if d.get("food_id") else None + out["my_food_id"] = int(d["my_food_id"]) if d.get("my_food_id") else None + except (TypeError, ValueError): + raise Invalid("food_id", "Unknown food.") + for k, (_, _, hi) in FIELDS.items(): + out[k] = _num(d, k, hi) + if out["kcal"] is None: + raise Invalid("kcal", "How much energy? A guess is fine.") + return out + + +def save(con, d, source="manual", extra=None): + """Insert (no id) or update (id) an entry; returns its id. An update keeps the source, + src_id and the nutrients the form doesn't show. extra = more columns (the food database's + other nutrients for the portion — they win over the `from` copy).""" + v = clean(d) + eid = d.get("id") + if eid: + if not entry(con, int(eid)): + raise Invalid("id", "That entry is gone.") + v.update(extra or {}) + con.execute(f"UPDATE entry SET {', '.join(f'{k} = ?' for k in v)} WHERE id = ?", (*v.values(), int(eid))) + else: + src = d.get("from") # copied from an earlier entry: keep its other nutrients, scaled + copy = {} + if src: + e = entry(con, int(src)) + if e and e["kcal"] and v["kcal"]: + f = v["kcal"] / e["kcal"] + copy = {k: round(e[k] * f, 3) for k in NUTRIENTS if e[k] is not None} + copy["micros"] = json.dumps({k: round(x * f, 4) for k, x in e["micros"].items()}) + v = {**v, **copy, **(extra or {}), "source": source} + cur = con.execute(f"INSERT INTO entry ({', '.join(v)}) VALUES ({', '.join('?' * len(v))})", tuple(v.values())) + eid = cur.lastrowid + con.commit() + return int(eid) + + +def delete(con, eid): + con.execute("DELETE FROM entry WHERE id = ?", (eid,)) + con.commit() + + +def move(con, eid, meal): + """An entry dragged into another meal (only the meal changes).""" + if meal not in MEAL_KEYS: + raise Invalid("meal", "Pick a meal.") + if not con.execute("UPDATE entry SET meal = ? WHERE id = ?", (meal, eid)).rowcount: + raise Invalid("id", "That entry is gone.") + con.commit() + + +# ---- My foods ------------------------------------------------------------------------------ + +def _food(r, uses=None): + return {"ref": f"my:{r['id']}", "kind": "my", "id": r["id"], "name": r["name"], "category": "My foods", + "per100": {c: r[c] for c in FOOD_COLS}, "portions": json.loads(r["portions"] or "[]"), + "based_on": r["based_on"], "based_on_name": r["based_on_name"], "note": r["note"], + "updated": r["updated"], "gone": bool(r["gone"]), "uses": uses, + "recipe": json.loads(r["recipe"]) if r["recipe"] else None, + "sugar_kind": r["sugar_kind"] if "sugar_kind" in r.keys() else None} + + +# ---- products picked from the archive ------------------------------------------------------------ + +PRODUCT_TEXT = {"name": 120, "category": 120, "brand": 60, "barcode": 14, "countries": 200, "nutriscore": 1, + "allergens": 400, "labels": 400, "ingredients": 1600, "sugars_in": 200} + + +def _product(d): + """A stored product → fooddb's food shape (kind "off", ref "usda:").""" + return dict(d, ref=f"usda:{d['id']}", kind="off", source="off", saved=True) + + +def clean_product(f): + """A product from the archive (sync server) → what's kept (checked: it came over the network).""" + try: + fid = int(f["id"]) + per100 = {c: (None if f["per100"].get(c) is None else float(f["per100"][c])) for c in FOOD_COLS} + portions = [{"label": str(p["label"])[:60], "grams": float(p["grams"])} for p in (f.get("portions") or [])[:6] + if 0 < float(p["grams"]) <= 10000] + except (KeyError, TypeError, ValueError, AttributeError): + raise Invalid("product", "That product came back garbled.") + if not (20_000_000_000_000 <= fid < 30_000_000_000_000) or not str(f.get("name") or "").strip(): + raise Invalid("product", "That isn't an Open Food Facts product.") + out = {k: (str(f[k])[:n] if f.get(k) is not None else None) for k, n in PRODUCT_TEXT.items()} + out.update(id=fid, per100=per100, portions=portions, + nova=int(f["nova"]) if f.get("nova") in (1, 2, 3, 4) else None, + dairy=int(f["dairy"]) if f.get("dairy") in (0, 1) else None, + added_sugar=float(f["added_sugar"]) if isinstance(f.get("added_sugar"), (int, float)) else None) + return out + + +def save_product(con, f): + """Keep a picked product (insert, or refresh when it changed) → it in fooddb's shape.""" + v = clean_product(f) + now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S") + data = json.dumps(v, ensure_ascii=False, sort_keys=True) + con.execute("INSERT INTO product (food_id, name, brand, barcode, data, added) VALUES (?, ?, ?, ?, ?, ?) " + "ON CONFLICT(food_id) DO UPDATE SET name = excluded.name, brand = excluded.brand, barcode = excluded.barcode, " + "data = excluded.data WHERE data IS NOT excluded.data", + (v["id"], v["name"], v["brand"] or "", v["barcode"], data, now)) + con.commit() + return _product(v) + + +def product(con, food_id): + r = con.execute("SELECT data FROM product WHERE food_id = ?", (food_id,)).fetchone() + return _product(json.loads(r[0])) if r else None + + +def products(con, q="", barcode=None, limit=6, fold=str.lower): + """Kept products whose name / brand has every word of q (fold: sugar.fold — no diacritics), or with that barcode.""" + if barcode: + rows = con.execute("SELECT data FROM product WHERE barcode = ?", (barcode,)).fetchall() + else: + words = fold(q).split() + rows = [r for r in con.execute("SELECT data, name, brand FROM product ORDER BY name") + if words and all(w in fold(f"{r['name']} {r['brand']}") for w in words)] + return [_product(json.loads(r["data"])) for r in rows[:limit]] + + +def my_foods(con, q="", limit=None): + """My foods (not deleted) whose name has every word of q; exact / starting matches first, + then the most used. limit None = all, by name.""" + words = [w for w in q.lower().split() if w] + where = " AND ".join(["f.gone = 0"] + ["LOWER(f.name) LIKE ?"] * len(words)) + args = [f"%{w}%" for w in words] + order = "f.name COLLATE NOCASE" if limit is None else \ + "(LOWER(f.name) = ?) DESC, (LOWER(f.name) LIKE ?) DESC, uses DESC, f.name COLLATE NOCASE" + if limit is not None: + args += [q.strip().lower(), q.strip().lower() + "%"] + rows = con.execute(f"SELECT f.*, (SELECT COUNT(*) FROM entry e WHERE e.my_food_id = f.id) AS uses FROM food f " + f"WHERE {where} ORDER BY {order}" + (" LIMIT ?" if limit else ""), + args + ([limit] if limit else [])).fetchall() + return [_food(r, r["uses"]) for r in rows] + + +def my_food(con, fid): + r = con.execute("SELECT * FROM food WHERE id = ?", (fid,)).fetchone() + return _food(r) if r else None + + +def clean_food(d, base=None): + """{name, per100: {FIELDS}, portions: [{label, grams}], note} → columns. base = the food it + starts from (a USDA one being copied, or the one being edited): the nutrients the form + doesn't show are kept from it.""" + name = " ".join(str(d.get("name") or "").split())[:120] + if not name: + raise Invalid("name", "Name the food.") + per = d.get("per100") or {} + out = {"name": name, "note": str(d.get("note") or "").strip()[:2000]} + for k, (_, _, hi) in FIELDS.items(): + out[k] = _num(per, k, hi) + if out["kcal"] is None: + raise Invalid("kcal", "Energy per 100 g — from the label.") + for k in FOOD_COLS: + if k not in FIELDS: + out[k] = (base or {}).get("per100", {}).get(k) + ps = [] + for i, p in enumerate(d.get("portions") or []): + label = " ".join(str((p or {}).get("label") or "").split())[:40] + g = _num(p or {}, "grams", 100000) + if not label and g is None: + continue + if not label or not g: + raise Invalid(f"portion.{i}", "A portion needs a name and its grams.") + if label.lower() in ("g", "ml"): + raise Invalid(f"portion.{i}", "g and ml are there already.") + ps.append({"label": label, "grams": g}) + out["portions"] = json.dumps(ps) + if "sugar_kind" in d: # the form's "Sugar counts as" (absent: left as it is) + out["sugar_kind"] = d["sugar_kind"] if d["sugar_kind"] in SUGAR_KINDS else None + return out + + +def save_food(con, d, base=None, fid=None): + """Insert (fid None) or update one of My foods; returns its id. A copy of a USDA food + remembers it (based_on). Names are unique among the foods not deleted.""" + return _write_food(con, clean_food(d, base), base, fid) + + +def _write_food(con, v, base=None, fid=None): + clash = con.execute("SELECT id FROM food WHERE LOWER(name) = ? AND gone = 0 AND id != ?", + (v["name"].lower(), fid or 0)).fetchone() + if clash: + raise Invalid("name", "You already have a food with that name in My foods — pick it, or name this one differently.") + now = datetime.now().isoformat(timespec="seconds") + if fid: + con.execute(f"UPDATE food SET {', '.join(f'{k} = ?' for k in v)}, updated = ? WHERE id = ?", (*v.values(), now, fid)) + else: + if base and base.get("kind") in ("usda", "off"): + v.update(based_on=base["id"], based_on_name=base["name"]) + v.update(created=now, updated=now) + fid = con.execute(f"INSERT INTO food ({', '.join(v)}) VALUES ({', '.join('?' * len(v))})", tuple(v.values())).lastrowid + con.commit() + return fid + + +MEAL_MAX = 40 # ingredients + + +def save_meal(con, d, resolve, fid=None): + """A meal = one of My foods made of others: {name, ingredients: [{food (ref), amount, unit} — + or, for an entry logged without a food, {fixed: {its numbers}, name, amount, unit, grams?}], + done_grams (its weight when done — soup boils down / takes on water; empty = the ingredients' + sum), portions, note}. Its values per 100 g are worked out here from the ingredients as they + are now (resolve(ref) → a food); saving again later works them out again. Portions get + "whole meal" (= its whole weight) added. Returns its id.""" + from .fooddb import nutrients, portion + name = " ".join(str(d.get("name") or "").split())[:120] + if not name: + raise Invalid("name", "Name the meal.") + rows = d.get("ingredients") or [] + if not rows: + raise Invalid("ingredients", "Add what goes into it.") + if len(rows) > MEAL_MAX: + raise Invalid("ingredients", f"At most {MEAL_MAX} ingredients.") + tot, grams, ings, unweighed = {c: None for c in FOOD_COLS}, 0.0, [], [] + for i, r in enumerate(rows): + if isinstance((r or {}).get("fixed"), dict): # an entry without a food: its numbers as logged + fx = {c: _num(r["fixed"], c, 1000000) for c in FOOD_COLS} + if fx["kcal"] is None: + raise Invalid(f"ing.{i}", "No energy on that one.") + for c, v in fx.items(): + if v is not None: + tot[c] = (tot[c] or 0) + v + g = _num(r, "grams", 100000) + if g: + grams += g + else: + unweighed.append(str(r.get("name") or "?")) + ings.append({"fixed": fx, "name": " ".join(str(r.get("name") or "").split())[:120], + "amount": _num(r, "amount", 100000), "unit": (str(r.get("unit") or "")[:60] or None), "grams": g}) + continue + f = resolve((r or {}).get("food")) + if not f: + raise Invalid(f"ing.{i}", "That food is gone — remove it and pick it again.") + if fid and f["kind"] == "my" and (f["id"] == fid or fid in _meal_ids(f)): + raise Invalid(f"ing.{i}", "A meal can't contain itself.") + amount = _num(r, "amount", 100000) + g, label = portion(f, amount, r.get("unit") or "g") + if not g: + raise Invalid(f"ing.{i}", "How much of it — amount and unit?") + for c, v in nutrients(f, g).items(): + if v is not None: + tot[c] = (tot[c] or 0) + v + grams += g + ings.append({"food": f["ref"], "name": f["name"], "amount": amount, "unit": label, "grams": round(g, 2)}) + done = _num(d, "done_grams", 1000000) + weight = done or grams + if unweighed and not done: + raise Invalid("done_grams", f"No weight for {', '.join(unweighed[:3])}{' …' if len(unweighed) > 3 else ''} — " + "weigh the meal (or guess) and enter it here.") + if not weight: + raise Invalid("done_grams", "How much does it weigh?") + v = clean_food({"name": name, "per100": {"kcal": tot["kcal"] or 0}, "portions": d.get("portions"), "note": d.get("note"), + **({"sugar_kind": d["sugar_kind"]} if "sugar_kind" in d else {})}) + ps = [p for p in json.loads(v["portions"]) if p["label"].lower() != "whole meal"] + v["portions"] = json.dumps(ps + [{"label": "whole meal", "grams": round(weight, 1)}]) + v.update({c: (round(x * 100 / weight, 3) if x is not None else None) for c, x in tot.items()}) + v["recipe"] = json.dumps({"ingredients": ings, "done_grams": done}) + return _write_food(con, v, None, fid) + + +def _meal_ids(f): + """The meals inside a meal's recipe (by id) — a meal may hold another meal, not itself.""" + return {int(i["food"].split(":")[1]) for i in ((f.get("recipe") or {}).get("ingredients") or []) + if str(i.get("food", "")).startswith("my:")} + + +def delete_food(con, fid): + con.execute("UPDATE food SET gone = 1 WHERE id = ?", (fid,)) + con.commit() + + +def _v(x): # Health Connect writes 5e-324 for "not set" + return x if isinstance(x, (int, float)) and abs(x) > 1e-300 else None + + +def import_health_connect(con, hc): + """Nutrition records → entries (source = the writing app, e.g. lifesum). Returns count.""" + hc.row_factory = sqlite3.Row + apps = {r[0]: (r[2] or r[1]).lower() for r in hc.execute("SELECT row_id, package_name, app_name FROM application_info_table")} + n = 0 + for r in hc.execute("SELECT * FROM nutrition_record_table"): + t = datetime.fromtimestamp(r["start_time"] / 1000, timezone.utc).replace(tzinfo=None) + timedelta(seconds=r["start_zone_offset"] or 0) + main = {k: _v(r[f]) for k, f in MAIN.items()} + for k in ("sodium_mg", "cholesterol_mg", "potassium_mg"): + main[k] = main[k] * 1000 if main[k] is not None else None + micros = {k: r[k] for k in r.keys() if k not in SKIP and k not in MAIN.values() and _v(r[k]) is not None} + energy = _v(r["energy"]) + con.execute(f"INSERT OR REPLACE INTO entry (day, time, meal, name, kcal, {', '.join(main)}, micros, source, src_id) " + f"VALUES (?, ?, ?, ?, ?, {', '.join('?' * len(main))}, ?, ?, ?)", + (t.date().isoformat(), t.strftime("%H:%M"), MEALS.get(r["meal_type"]), r["meal_name"] or "", + energy / 1000 if energy is not None else None, *main.values(), json.dumps(micros), + apps.get(r["app_info_id"], "health connect"), r["uuid"].hex() if r["uuid"] else None)) + n += 1 + con.commit() + return n diff --git a/dashboard/plugins/food/fdc.py b/dashboard/plugins/food/fdc.py new file mode 100644 index 0000000..5a9a9eb --- /dev/null +++ b/dashboard/plugins/food/fdc.py @@ -0,0 +1,190 @@ +"""Build the food database (dash_data/food/foods.db) from a USDA FoodData Central CSV +download (fdc.nal.usda.gov ▸ Download Datasets ▸ "Full Download of All Data Types", CSV zip): + + python3 plugins/food/fdc.py FoodData_Central_csv_2026-04-30.zip foods.db (stand-alone: no Flask needed) + python3 plugins/food/fdc.py --fped FoodData_Central_csv_2026-04-30.zip FPED_2123.csv foods.db + +Takes the generic foods only — Foundation, SR Legacy and Survey (FNDDS), ≈ 13 700 — with +their nutrients per 100 g and household portions (1 large egg = 50 g, 1 cup = …). Branded +foods (2 million, US shop products) are left out: ~1 GB and little of it sold here. +Reads the zip as it is (the CSVs unpacked are 3 GB); food_nutrient.csv is streamed, so it +needs little memory but takes a few minutes — build it on the PC, copy the file to the Pi. +The diary only reads foods.db (fooddb.py); rebuilding replaces it whole. + +--fped: the Survey (FNDDS) foods' added sugars from USDA's Food Patterns Equivalents Database for the +same FNDDS cycle (ars.usda.gov ▸ FSRG ▸ FPED ▸ FPED_2123.xls, as CSV: `soffice --headless --convert-to +csv FPED_2123.xls`; ADD_SUGARS in teaspoon equivalents per 100 g, × 4.2 g) → `added_sugar` (g / 100 g, +sugar.py uses it first). FPED doesn't count 100 % fruit juice as added; WHO does — so a food that is +mostly juice (F_JUICE ≥ half its weight) gets none here and the name rule (juice → added) decides; +so do beer and wine (WWEIA categories), whose sugar counts like juice's (sugar.py). +Run after the build (a rebuild drops it), before off.py. +""" +import csv +import io +import os +import re +import sqlite3 +import sys +import time +import zipfile + +KEEP = {"foundation_food": "foundation", "sr_legacy_food": "sr_legacy", "survey_fndds_food": "survey"} +# nutrient id → column (per 100 g). Energy: 1008, else Atwater specific (2048) / general (2047) +NUTRIENTS = {1003: "protein", 1004: "fat", 1005: "carbs", 1079: "fiber", 2000: "sugar", 1063: "sugar2", + 1258: "sat_fat", 1292: "mono_fat", 1293: "poly_fat", 1257: "trans_fat", 1093: "sodium_mg", + 1253: "cholesterol_mg", 1092: "potassium_mg", 1008: "kcal", 2048: "kcal_s", 2047: "kcal_g"} +COLS = ["kcal", "protein", "carbs", "sugar", "fiber", "fat", "sat_fat", "mono_fat", "poly_fat", "trans_fat", + "sodium_mg", "cholesterol_mg", "potassium_mg"] +SCHEMA = f""" +CREATE TABLE food ( + id INTEGER PRIMARY KEY, -- FoodData Central fdc_id + name TEXT NOT NULL, + category TEXT NOT NULL DEFAULT '', + source TEXT NOT NULL, -- foundation / sr_legacy / survey + {", ".join(c + " REAL" for c in COLS)} -- per 100 g +); +CREATE TABLE portion ( + food_id INTEGER NOT NULL, + seq INTEGER NOT NULL, + label TEXT NOT NULL, -- "large", "cup, chopped", "slice" — one of these + grams REAL NOT NULL +); +CREATE INDEX portion_food ON portion (food_id, seq); +CREATE VIRTUAL TABLE food_fts USING fts5(name, category, content='food', content_rowid='id', + tokenize='unicode61 remove_diacritics 2'); +CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT); +""" + + +def rows(z, name): + root = next(n for n in z.namelist() if n.endswith("/" + name) or n == name) + with z.open(root) as f: + yield from csv.DictReader(io.TextIOWrapper(f, encoding="utf-8", newline="")) + + +def _f(x): + try: + return float(x) + except (TypeError, ValueError): + return None + + +def portion_label(r, units): + """'1.0 / 1000 (cup) / "chopped"' → 'cup, chopped'; amount kept when it isn't 1.""" + unit = units.get(r["measure_unit_id"], "") + unit = "" if unit in ("undetermined", "") else unit + desc = (r["portion_description"] or "").strip() + mod = (r["modifier"] or "").strip() + if desc.lower().startswith(("quantity not specified", "guideline amount")) or desc.isdigit(): + return "" # survey's placeholders / codes + if desc: + label = re.sub(r"^1 (?=\D)", "", desc) # survey: "1 large" → "large", "1 cup" → "cup" + else: + label = ", ".join(x for x in (unit, mod) if x and not x.isdigit()) + amt = _f(r["amount"]) + if amt and amt != 1 and not label[:1].isdigit(): + label = f"{amt:g} {label}" + return label[:60] + + +def build(src, out): + t0 = time.time() + z = zipfile.ZipFile(src) + cats = {r["id"]: r["description"] for r in rows(z, "food_category.csv")} + wweia = {r["wweia_food_category"]: r["wweia_food_category_description"] for r in rows(z, "wweia_food_category.csv")} + survey_cat = {r["fdc_id"]: wweia.get(r["wweia_category_code"], "") for r in rows(z, "survey_fndds_food.csv")} + foods = {} + for r in rows(z, "food.csv"): + src_ = KEEP.get(r["data_type"]) + if src_: + cat = survey_cat.get(r["fdc_id"]) if src_ == "survey" else cats.get(r["food_category_id"], "") + foods[r["fdc_id"]] = {"id": int(r["fdc_id"]), "name": r["description"].strip(), "category": cat or "", + "source": src_} + print(f"{len(foods)} foods; reading nutrients …", flush=True) + wanted = {str(k): v for k, v in NUTRIENTS.items()} + n = 0 + for r in rows(z, "food_nutrient.csv"): + n += 1 + if n % 5_000_000 == 0: + print(f" {n // 1_000_000} M rows, {time.time() - t0:.0f} s", flush=True) + col = wanted.get(r["nutrient_id"]) + if col and r["fdc_id"] in foods: + v = _f(r["amount"]) + if v is not None: + foods[r["fdc_id"]][col] = v + units = {r["id"]: r["name"] for r in rows(z, "measure_unit.csv")} + portions = [] + for r in rows(z, "food_portion.csv"): + g = _f(r["gram_weight"]) + if r["fdc_id"] in foods and g and g > 0: + label = portion_label(r, units) + if label: + portions.append((int(r["fdc_id"]), int(_f(r["seq_num"]) or 0), label, g)) + for f in foods.values(): + f["kcal"] = f.get("kcal") or f.get("kcal_s") or f.get("kcal_g") + if f["kcal"] is None and any(f.get(k) is not None for k in ("protein", "carbs", "fat")): + f["kcal"] = 4 * (f.get("protein") or 0) + 4 * (f.get("carbs") or 0) + 9 * (f.get("fat") or 0) + f["sugar"] = f.get("sugar") if f.get("sugar") is not None else f.get("sugar2") + keep = [f for f in foods.values() if f.get("kcal") is not None] + tmp = out + ".tmp" + if os.path.exists(tmp): + os.remove(tmp) + con = sqlite3.connect(tmp) + con.executescript(SCHEMA) + con.executemany(f"INSERT INTO food (id, name, category, source, {', '.join(COLS)}) VALUES ({', '.join('?' * (4 + len(COLS)))})", + [(f["id"], f["name"], f["category"], f["source"], *(f.get(c) for c in COLS)) for f in keep]) + ids = {f["id"] for f in keep} + con.executemany("INSERT INTO portion VALUES (?, ?, ?, ?)", [p for p in portions if p[0] in ids]) + con.execute("INSERT INTO food_fts (rowid, name, category) SELECT id, name, category FROM food") + con.executemany("INSERT INTO meta VALUES (?, ?)", [("source", os.path.basename(src)), ("built", time.strftime("%Y-%m-%d"))]) + con.commit() + con.execute("VACUUM") + con.close() + os.replace(tmp, out) + print(f"{len(keep)} foods, {sum(1 for p in portions if p[0] in ids)} portions → {out} " + f"({os.path.getsize(out) / 1e6:.1f} MB, {time.time() - t0:.0f} s)") + + +TSP_G = 4.2 # g of sugar in a teaspoon equivalent (FPED) +JUICE_CUP_G = 248 # g of juice in a cup equivalent + + +def fped(src, fped_csv, out): + """FPED's added sugars → foods.db's survey foods (see the top).""" + z = zipfile.ZipFile(src) + code_of = {r["food_code"]: int(r["fdc_id"]) for r in rows(z, "survey_fndds_food.csv")} + con = sqlite3.connect(out) + if "added_sugar" not in {r[1] for r in con.execute("PRAGMA table_info(food)")}: + con.execute("ALTER TABLE food ADD COLUMN added_sugar REAL") + sugar = dict(con.execute("SELECT id, sugar FROM food WHERE source = 'survey'")) + # beer / wine / cider: FPED says none added; their sugar counts here like juice's (sugar.py, decided 2026-10-22) + by_name = {r[0] for r in con.execute("SELECT id FROM food WHERE source = 'survey' AND category IN ('Beer', 'Wine')")} + upd, juice, missing = [], 0, 0 + with open(fped_csv, encoding="utf-8", newline="") as f: + for r in csv.DictReader(f): + k = {re.sub(r"\s*\(.*", "", c.replace("\n", " ")).strip(): v for c, v in r.items()} # "ADD_SUGARS (tsp. eq.)" → ADD_SUGARS + fid = code_of.get(k["FOODCODE"].strip()) + if fid not in sugar: + missing += 1 + continue + if fid in by_name or (_f(k.get("F_JUICE")) or 0) * JUICE_CUP_G / 100 >= 0.5: + juice += 1 + upd.append((None, fid)) + continue + a = (_f(k.get("ADD_SUGARS")) or 0) * TSP_G + upd.append((round(min(a, sugar[fid]) if sugar[fid] is not None else a, 2), fid)) + con.executemany("UPDATE food SET added_sugar = ? WHERE id = ?", upd) + con.execute("INSERT OR REPLACE INTO meta VALUES ('fped_source', ?)", (os.path.basename(fped_csv),)) + con.commit() + con.close() + print(f"{len(upd)} survey foods: added sugars from FPED ({juice} mostly juice left to the name rule), " + f"{missing} FPED codes not in foods.db") + + +if __name__ == "__main__": + if len(sys.argv) == 5 and sys.argv[1] == "--fped": + fped(sys.argv[2], sys.argv[3], sys.argv[4]) + elif len(sys.argv) == 3: + build(sys.argv[1], sys.argv[2]) + else: + sys.exit(__doc__) diff --git a/dashboard/plugins/food/fooddb.py b/dashboard/plugins/food/fooddb.py new file mode 100644 index 0000000..7e1dfc6 --- /dev/null +++ b/dashboard/plugins/food/fooddb.py @@ -0,0 +1,160 @@ +"""The food database (dash_data/food/foods.db, built by fdc.py from USDA FoodData Central): +read-only lookups for the entry form and the describe box. Nutrients are per 100 g; +`portion` rows give household measures in grams. Missing file = no database (None / []). + + search(path, q) → foods for the form's suggestions, best first, with their portions + food(path, id) → one food + portions + by_barcode(path, c) → the products with that barcode + best(path, name) → the likeliest food for a name (the describe box) + portion(f, amount, unit) → (grams, unit label) for "2 pcs" / "1 slice" / "150 g" of it, or (None, None) + nutrients(f, grams) → its columns for that many grams + +A food here and one of My foods (db.my_foods) have the same shape: {ref ("usda:ID" / "my:ID"), +kind, id, name, category, per100: {column: value}, portions: [{label, grams}]}. foods.db holds +USDA's generic foods (fdc.py; kind "usda") and Open Food Facts' shop products (off.py; kind "off", ++ brand, barcode — ids from off.OFF_ID up); refs to both are "usda:ID" (the table's id). +""" +import os +import re +import sqlite3 + +from .fdc import COLS + +SOURCE_RANK = {"foundation": 0, "sr_legacy": 1, "survey": 2, "off": 3} + + +def _con(path): + if not os.path.exists(path): + return None + con = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=5) + con.row_factory = sqlite3.Row + return con + + +def _food(con, r): + off = r["source"] == "off" + f = {"ref": f"usda:{r['id']}", "kind": "off" if off else "usda", "id": r["id"], "name": r["name"], + "category": r["category"], "source": r["source"], + **{k: (r[k] if k in r.keys() else None) for k in ("brand", "barcode", "nutriscore", "nova", "allergens", + "labels", "ingredients", "sugars_in", "dairy", "added_sugar")}, + "per100": {c: r[c] for c in COLS}} + f["portions"] = [{"label": p["label"], "grams": p["grams"]} for p in con.execute( + "SELECT label, grams FROM portion WHERE food_id = ? ORDER BY seq, grams", (r["id"],))] + return f + + +STOP = {"with", "and", "of", "a", "an", "the", "in", "on", "some", "my"} +PLAIN = ("nfs", "raw", "whole", "plain", "regular", "fresh", "cooked", "boiled") # the generic version of a food + + +def _words(q): + return [w for w in re.findall(r"\w+", q.lower()) if (len(w) > 1 or w.isdigit()) and w not in STOP] + + +def search(path, q, limit=10): + """Every word must match (as a prefix) in the name, brand or category; ranked by: all of them in + the name (else only through the brand / category — "zuzu" → Zuzu's products), the name starts with the first word + (egg → "Egg, …" before "Eggs, …" before "Omelet …"), then plain versions first (raw, NFS, + whole … — "Egg, whole, raw" before "Egg burrito"), fewer words, FTS relevance (the name + counting most), shorter names. The same name from two sources once.""" + words = _words(q) + con = _con(path) + if not words or not con: + return [] + with con: + terms = " ".join(f'"{w}"*' for w in words) + rs = con.execute("SELECT f.*, bm25(food_fts, 10, 1) AS rank FROM food_fts JOIN food f ON f.id = food_fts.rowid " + "WHERE food_fts MATCH ? ORDER BY rank LIMIT 200", (terms,)).fetchall() + first = words[0] + def key(r): + name = r["name"].lower() + lead = re.match(r"\w+", name) + lead = lead.group(0) if lead else "" + exact = 0 if lead in (first, first + "s", first + "es") or first in (lead + "s", lead + "es") \ + else 1 if lead.startswith(first) else 2 + ws = re.findall(r"\w+", name) + in_name = 0 if all(any(x.startswith(w) for x in ws) for w in words) else 1 # else only via brand / category + plain = 0 if any(w in PLAIN for w in ws) else 1 + return (in_name, exact, plain, len(ws), round(r["rank"], 1), len(name), SOURCE_RANK.get(r["source"], 3)) + seen, out = set(), [] + for r in sorted(rs, key=key): + k = r["name"].lower() + if k not in seen: + seen.add(k) + out.append(_food(con, r)) + if len(out) >= limit: + break + return out + + +def food(path, fid): + con = _con(path) + if not con: + return None + with con: + r = con.execute("SELECT * FROM food WHERE id = ?", (fid,)).fetchone() + return _food(con, r) if r else None + + +def by_barcode(path, code): + """The products with that barcode (foods.db keeps it as on the pack, leading zeros too).""" + con = _con(path) + if not con or not code: + return [] + with con: + if "barcode" not in {r[1] for r in con.execute("PRAGMA table_info(food)")}: + return [] + return [_food(con, r) for r in con.execute("SELECT * FROM food WHERE barcode = ? OR barcode = ?", + (code, code.lstrip("0") or code))] + + +def best(path, name): + hits = search(path, name, limit=1) + return hits[0] if hits else None + + +# unit → words a portion label should have (in order of preference) +PORTION_WORDS = {"slice": ("slice, regular", "medium or regular slice", "slice"), "cup": ("cup",), + "tbsp": ("tablespoon", "tbsp"), "tsp": ("teaspoon", "tsp"), + "pcs": ("medium", "large", "piece", "whole", "item", "fruit", "small")} +MEASURES = ("cup", "oz", "fl oz", "tablespoon", "tbsp", "teaspoon", "tsp", "slice", "lb", "g", "pint", "quart") + + +# spoons every food can be measured in (ml counted as g, like the ml unit) unless it has its own +GENERIC = {"tbsp (15 ml)": 15, "tsp (5 ml)": 5} + + +def portion(f, amount, unit): + """(grams, unit label) of `amount` `unit` of the food f — the label is "g", "ml" or one of + its portions (the model's "pcs" becomes "large", "slice" → "slice, regular" …); (None, None) + when its portions don't say. ml counts as g.""" + if not amount: + return None, None + if unit in ("g", "ml"): + return amount, unit + if unit in GENERIC: + return amount * GENERIC[unit], unit + ps = f["portions"] + for p in ps: # a portion label given as the unit (the form) + if unit and p["label"] == unit: + return amount * p["grams"], p["label"] + for w in PORTION_WORDS.get(unit, ()): + for p in ps: + if p["label"].lower().startswith(w): + return amount * p["grams"], p["label"] + if unit == "pcs": # "banana", "egg": a portion that isn't a measure + for p in ps: + if not p["label"].lower().startswith(MEASURES): + return amount * p["grams"], p["label"] + if unit == "portion" and ps: + return amount * ps[0]["grams"], ps[0]["label"] + return None, None + + +def grams_for(f, amount, unit): + return portion(f, amount, unit)[0] + + +def nutrients(f, grams): + """The food's columns for that many grams (None stays None).""" + return {c: (round(v * grams / 100, 2) if v is not None else None) for c, v in f["per100"].items()} diff --git a/dashboard/plugins/food/off.py b/dashboard/plugins/food/off.py new file mode 100644 index 0000000..0e11cb7 --- /dev/null +++ b/dashboard/plugins/food/off.py @@ -0,0 +1,327 @@ +"""Add Open Food Facts products (shop products, by barcode) to the food database (foods.db, +next to the USDA foods fdc.py put there), or build the archive of every product for the sync server's +food search (server/ — GET /v1/food/…): + + python3 plugins/food/off.py en.openfoodfacts.org.products.csv.gz foods.db [food.db] (stand-alone) + python3 plugins/food/off.py --archive en.openfoodfacts.org.products.csv.gz off-archive.db + +The export: https://static.openfoodfacts.org/data/en.openfoodfacts.org.products.csv.gz +(regenerated nightly, ~1 GB; tab-separated, read compressed as it is — never unpacked). +ODbL: fine to use privately; republishing the data would need attribution + share-alike. + +Kept: products sold in COUNTRIES (FOOD_COUNTRIES, e.g. FOOD_COUNTRIES=romania,slovakia — the rest are in the +archive only: fewer foreign look-alikes in everyday search) — plus, given the diary (food.db), every product it uses +(entries, My foods copied from one, meals' ingredients) wherever it's sold — with a name and energy per 100 g (kcal, else kJ ÷ 4.184), +values in a sane range. Each: name (+ brand in `brand`, searched too), barcode, nutrients per +100 g, portions "serving" (serving_quantity) and "package" (product_quantity) in g, and what the +label / OFF say about it: `nutriscore` (a–e), `nova` (1–4: unprocessed … ultra-processed), +`allergens` and `labels` (", "-joined, English where OFF has it), `ingredients` (the pack's text, +in its language, at most INGREDIENTS_MAX characters). ids are +OFF_ID + the barcode (USDA's fdc_ids stay below it) — the same in foods.db and the archive. A rerun +replaces every source = "off" row. + +For the added-sugar estimate (sugar.py), facts kept per product: `sugars_in` = the sweet ingredients +the label lists (", "-joined; "" = its ingredients are known and none is; None = not known) — from OFF's +ingredient tags, which are English whatever the label's language (en:glucose-syrup, en:apple-juice …), +else (ingredients OFF couldn't parse) from words in the text in the languages of SWEET_TEXT; `dairy` = +OFF files it under dairy (1 / 0, None without categories); `added_sugar` = the label's added sugars, +g / 100 g, when it gives them (rare). + +The archive (archive()): every product with a name and sane numbers, whatever the country (`countries` +kept), duplicates merged — the same brand + name without the pack size + rounded kcal / P / C / F: the +most complete copy stays (RO / SK ones preferred), the others' barcodes go to `alias`. Portions inline +(JSON), FTS on name / brand / category / countries (diacritics folded). +""" +import csv +import gzip +import json +import math +import os +import re +import sqlite3 +import sys +import time + +try: + from .sugar import fold +except ImportError: # stand-alone (python3 plugins/food/off.py …) + from sugar import fold + +# the countries whose shop products go into foods.db and rank first in the archive: OFF's names, +# FOOD_COUNTRIES="romania,slovakia" (empty: none in foods.db — USDA's foods only; the archive keeps all) +HOME = {c.strip().lower().replace(" ", "-") for c in os.environ.get("FOOD_COUNTRIES", "").split(",") if c.strip()} +COUNTRIES = {"en:" + c for c in HOME} +OFF_ID = 20_000_000_000_000 # + the barcode (EAN-13 < 10^13) +COLS = ["kcal", "protein", "carbs", "sugar", "fiber", "fat", "sat_fat", "mono_fat", "poly_fat", "trans_fat", + "sodium_mg", "cholesterol_mg", "potassium_mg"] # = fdc.COLS +# column → (OFF field, factor) — OFF gives g per 100 g; the _mg ones × 1000 +FIELDS = {"protein": ("proteins_100g", 1), "carbs": ("carbohydrates_100g", 1), "sugar": ("sugars_100g", 1), + "fiber": ("fiber_100g", 1), "fat": ("fat_100g", 1), "sat_fat": ("saturated-fat_100g", 1), + "mono_fat": ("monounsaturated-fat_100g", 1), "poly_fat": ("polyunsaturated-fat_100g", 1), + "trans_fat": ("trans-fat_100g", 1), "sodium_mg": ("sodium_100g", 1000), + "cholesterol_mg": ("cholesterol_100g", 1000), "potassium_mg": ("potassium_100g", 1000)} +MAX = {"kcal": 900, "sodium_mg": 40000, "cholesterol_mg": 3000, "potassium_mg": 10000} # else 100 g +EXTRA = ("brand", "barcode", "nutriscore", "nova", "allergens", "labels", "ingredients", "sugars_in", "dairy", + "added_sugar") # columns beyond fdc's +TYPES = {"nova": "INTEGER", "dairy": "INTEGER", "added_sugar": "REAL"} # else TEXT +INGREDIENTS_MAX = 1500 +# labels worth showing (OFF's tags, en:…) → how they read here +LABELS = {"en:organic": "organic", "en:eu-organic": "organic", "en:vegan": "vegan", "en:vegetarian": "vegetarian", + "en:gluten-free": "gluten-free", "en:no-gluten": "gluten-free", "en:lactose-free": "lactose-free", + "en:no-lactose": "lactose-free", "en:no-added-sugar": "no added sugar", "en:sugar-free": "sugar-free", + "en:palm-oil-free": "palm-oil free", "en:no-palm-oil": "palm-oil free", "en:no-preservatives": "no preservatives", + "en:no-additives": "no additives", "en:no-artificial-colors": "no artificial colours", + "en:high-protein": "high protein", "en:whole-grain": "whole grain", "en:halal": "halal", "en:kosher": "kosher"} + + +def _f(x): + try: + v = float(x) + except (TypeError, ValueError): + return None + return v if v == v and v >= 0 else None # NaN / negative → none + + +def _first_brand(r): + b = (r.get("brands_en") or r.get("brands") or "").split(",")[0].strip() + return b[:60] + + +def product(r, countries=COUNTRIES): + """A CSV row → our row, or None (not sold in `countries` — None: any —, no name, no energy, odd numbers).""" + if countries is not None and not countries & set((r.get("countries_tags") or "").split(",")): + return None + name = " ".join((r.get("product_name") or r.get("generic_name") or "").split())[:120] + code = re.sub(r"\D", "", r.get("code") or "") + if not name or not code or len(code) > 13: + return None + kcal = _f(r.get("energy-kcal_100g")) + if kcal is None and _f(r.get("energy_100g")) is not None: + kcal = _f(r["energy_100g"]) / 4.184 + if kcal is None or kcal > MAX["kcal"]: + return None + out = {"id": OFF_ID + int(code), "name": name, "brand": _first_brand(r), "barcode": code, "kcal": round(kcal, 1)} + for col, (field, k) in FIELDS.items(): + v = _f(r.get(field)) + out[col] = round(v * k, 3) if v is not None and v * k <= MAX.get(col, 100) else None + macros = sum(out[c] or 0 for c in ("protein", "carbs", "fat")) + if macros > 105: # more than 100 g of macros in 100 g: a typo somewhere + return None + if out["sodium_mg"] is None and _f(r.get("salt_100g")) is not None: + out["sodium_mg"] = round(_f(r["salt_100g"]) * 400, 1) + portions = [] + sq = _f(r.get("serving_quantity")) + if sq and 1 <= sq <= 2000: + portions.append((f"serving ({(r.get('serving_size') or '').strip()[:30]})".replace(" ()", ""), sq)) + pq = _f(r.get("product_quantity")) + if pq and 1 <= pq <= 10000 and pq != sq: + portions.append((f"package ({(r.get('quantity') or '').strip()[:30]})".replace(" ()", ""), pq)) + out["portions"] = portions + cat = (r.get("main_category_en") or "").strip() + cat = "" if ":" in cat else cat[:40] # untranslated tags ("fr:yaourt …") say nothing here + out["category"] = " · ".join(x for x in (out["brand"], cat) if x) + g = (r.get("nutriscore_grade") or "").strip().lower() + out["nutriscore"] = g if g in ("a", "b", "c", "d", "e") else None + n = _f(r.get("nova_group")) + out["nova"] = int(n) if n in (1, 2, 3, 4) else None + out["allergens"] = _tags(r.get("allergens_tags")) + out["labels"] = ", ".join(dict.fromkeys(LABELS[t] for t in (r.get("labels_tags") or "").split(",") if t in LABELS)) or None + ing = " ".join((r.get("ingredients_text") or "").split()) + out["ingredients"] = (ing[:INGREDIENTS_MAX] + ("…" if len(ing) > INGREDIENTS_MAX else "")) or None + out["sugars_in"], out["dairy"], out["added_sugar"] = sugar_facts(r, out["sugar"]) + return out + + +# sweet ingredients (WHO's free sugars) by OFF's ingredient tags — "en:…" whatever the label's language +SWEET_TAG = re.compile(r"sugar|syrup|honey|dextrose|glucose|fructose|sucrose|maltose|molasses|treacle|invert|juice|" + r"nectar(?!ine)|malt-extract|agave|maple") +NOT_SWEET_TAG = re.compile(r"sugar-alcohol|sugar-free|no-added-sugar|sweetener|caramel-colo|e150|" + r"(lemon|lime|tomato|vegetable|carrot|beet|beetroot|cabbage|sauerkraut|pickle|cucumber)-juice") +# the same in the text (folded, sugar.fold) when OFF couldn't read the ingredients: EN, RO, SK / CZ, HU, PL, DE, FR, IT, ES, PT, NL +SWEET_TEXT = re.compile(r"sugar|syrup|honey|molasses|dextrose|glucose|fructose|sucrose|zahar|sirop|\bmiere\b|glucoz|fructoz|" + r"dextroz|melas|melaz|cukor|cukr|cukier|sirup|\bmed\b|glukoz|fruktoz|szirup|\bmez\b|zucker|honig|glukose|" + r"fruktose|sucre|\bmiel\b|zucchero|sciroppo|\bmiele\b|glucosio|fruttosio|destrosio|azucar|jarabe|acucar|" + r"xarope|\bmel\b|syrop|\bmiod\b|suiker|stroop|honing") +NO_SUGAR_TEXT = re.compile(r"(no|without|zero) added sugars?|sugars? free|naturally occurring sugars?|fara (adaos de )?zahar( adaugat)?|" + r"bez (pridaneho |pridanego )?cukru|bez dodatku cukru|cukormentes|hozzaadott cukor nelkul|" + r"ohne (zusatz von )?zucker(zusatz)?|zuckerfrei|sans sucres?( ajoutes?)?|senza zuccheri?( aggiunti)?|" + r"sin azucar(es)?( anadid[oa]s?)?|sem acucar(es)?( adicionad[oa]s?)?|zonder (toegevoegde )?suiker") +DAIRY_TAGS = {"en:dairies", "en:milks", "en:yogurts", "en:fermented-milk-products", "en:cheeses", "en:creams"} +NOT_DAIRY_TAGS = {"en:dairy-substitutes", "en:milk-substitutes", "en:plant-based-milk-alternatives", "en:non-dairy-yogurts", + "en:plant-based-yogurt-alternatives"} + + +def sugar_facts(r, sugar): + """(sugars_in, dairy, added_sugar) of a CSV row — see the top.""" + tags = [t.strip() for t in (r.get("ingredients_tags") or "").split(",") if t.strip()] + if tags: + sweet = [t[3:] for t in tags if t.startswith("en:") and SWEET_TAG.search(t) and not NOT_SWEET_TAG.search(t)] + sweet = [t for t in sweet if t != "added-sugar"] or sweet # OFF's parent tag, beside the real one ("sugar") + sugars_in = ", ".join(dict.fromkeys(t.replace("-", " ") for t in sweet[:6])) + elif re.search(r"[^\W\d_]{3}", r.get("ingredients_text") or ""): # words, not just "." or "60%" + text = NO_SUGAR_TEXT.sub(" ", fold(r["ingredients_text"])) + sugars_in = ", ".join(dict.fromkeys(m.group(0) for m in SWEET_TEXT.finditer(text))) + else: + sugars_in = None + cats = set((r.get("categories_tags") or "").split(",")) - {""} + dairy = (1 if cats & DAIRY_TAGS and not cats & NOT_DAIRY_TAGS else 0) if cats else None + a = _f(r.get("added-sugars_100g")) + if a is not None and (a > 100 or (sugar is not None and a > sugar * 1.05 + 0.5)): + a = None # more added than all the sugar: a typo somewhere + return sugars_in, dairy, a + + +def _tags(v): + """'en:milk,en:gluten,fr:moutarde' → 'milk, gluten, moutarde'.""" + out = [t.split(":", 1)[-1].replace("-", " ") for t in (v or "").split(",") if t.strip()] + return ", ".join(dict.fromkeys(out)) or None + + +def used(diary): + """The Open Food Facts ids the diary (food.db) uses: entries, My foods copied from one, meals' ingredients.""" + con = sqlite3.connect(f"file:{diary}?mode=ro", uri=True) + ids = {r[0] for r in con.execute("SELECT food_id FROM entry WHERE food_id >= ? UNION SELECT based_on FROM food WHERE based_on >= ?", + (OFF_ID, OFF_ID))} + for (recipe,) in con.execute("SELECT recipe FROM food WHERE recipe IS NOT NULL"): + ids |= {int(x) for x in re.findall(r'"usda:(\d+)"', recipe) if int(x) >= OFF_ID} + con.close() + return ids + + +def build(src, out_path, diary=None): + t0 = time.time() + keep = used(diary) if diary else set() # used ones stay, wherever they're sold + con = sqlite3.connect(out_path) + have = {r[1] for r in con.execute("PRAGMA table_info(food)")} + for col in EXTRA: + if col not in have: + con.execute(f"ALTER TABLE food ADD COLUMN {col} {TYPES.get(col, 'TEXT')}") + con.execute("CREATE INDEX IF NOT EXISTS food_barcode ON food (barcode)") + old = [r[0] for r in con.execute("SELECT id FROM food WHERE source = 'off'")] + con.executemany("DELETE FROM portion WHERE food_id = ?", [(i,) for i in old]) + con.execute("DELETE FROM food WHERE source = 'off'") + csv.field_size_limit(1 << 30) + n = kept = 0 + seen = set() + with gzip.open(src, "rt", encoding="utf-8", errors="replace", newline="") as f: + for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): + n += 1 + if n % 500_000 == 0: + print(f" {n // 1000}k rows, {kept} kept, {time.time() - t0:.0f} s", flush=True) + p = product(r) + if not p and keep: # sold elsewhere: only if used (the barcode says, cheaply) + code = re.sub(r"\D", "", r.get("code") or "") + p = product(r, None) if code and len(code) <= 13 and OFF_ID + int(code) in keep else None + if not p or p["id"] in seen: + continue + seen.add(p["id"]) + con.execute(f"INSERT OR REPLACE INTO food (id, name, category, source, {', '.join(EXTRA)}, {', '.join(COLS)}) " + f"VALUES (?, ?, ?, 'off', {', '.join('?' * (len(EXTRA) + len(COLS)))})", + (p["id"], p["name"], p["category"], *(p.get(c) for c in EXTRA), *(p.get(c) for c in COLS))) + con.executemany("INSERT INTO portion (food_id, seq, label, grams) VALUES (?, ?, ?, ?)", + [(p["id"], i, l, g) for i, (l, g) in enumerate(p["portions"])]) + kept += 1 + con.execute("INSERT INTO food_fts(food_fts) VALUES ('rebuild')") + con.execute("INSERT OR REPLACE INTO meta VALUES ('off_source', ?), ('off_built', ?), ('off_products', ?), ('off_countries', ?)", + (os.path.basename(src), time.strftime("%Y-%m-%d"), str(kept), " ".join(sorted(COUNTRIES)))) + missing = keep - seen + if missing: + print(f" {len(missing)} used products aren't in this export any more: {sorted(missing)[:10]}", flush=True) + con.commit() + con.execute("VACUUM") + con.close() + print(f"{n} rows read, {kept} products kept → {out_path} ({os.path.getsize(out_path) / 1e6:.1f} MB, {time.time() - t0:.0f} s)") + + +ARCHIVE = f""" +CREATE TABLE food ( + id INTEGER PRIMARY KEY, -- OFF_ID + barcode (as in foods.db) + name TEXT NOT NULL, + category TEXT NOT NULL DEFAULT '', -- brand · main category (as in foods.db) + countries TEXT NOT NULL DEFAULT '', -- "romania slovakia germany" (OFF's countries_tags without en:) + portions TEXT, -- JSON [[label, grams], …] + dkey TEXT, -- the duplicate key (build only; NULL after) + score REAL, -- how complete (the duplicate kept is the highest) + {", ".join(c + " REAL" for c in COLS)}, + {", ".join(c + " " + TYPES.get(c, "TEXT") for c in EXTRA)} +); +CREATE TABLE alias (barcode TEXT PRIMARY KEY, food_id INTEGER NOT NULL); -- the merged duplicates' barcodes +CREATE TABLE meta (k TEXT PRIMARY KEY, v TEXT); +""" +PACK = re.compile(r"\b\d+([.,]\d+)?\s*(g|gr|grams?|kg|ml|cl|dl|l|ltr|oz|lb|x|pcs?|ks|buc|db|szt|st)\b|\b\d+\s*x\b|[^\w ]") +HOME = {c.replace("-", " ") for c in HOME} # as the archive's countries column writes them + + +def _dkey(p): + name = " ".join(PACK.sub(" ", fold(p["name"])).split()) + return "|".join([fold(p["brand"]), name, *(str(round(p[c] or 0)) for c in ("kcal", "protein", "carbs", "fat"))]) + + +def _score(p, countries): + return (sum(p[c] is not None for c in COLS) + 3 * (p["ingredients"] is not None) + (p["nutriscore"] is not None) + + (p["nova"] is not None) + len(p["portions"]) + 5 * bool(HOME & countries) + p["_scans"]) + + +def archive(src, out_path): + """Every product (any country) → a new archive db at out_path (see the top).""" + t0 = time.time() + if os.path.exists(out_path): + os.remove(out_path) + con = sqlite3.connect(out_path) + con.executescript(ARCHIVE) + con.execute("CREATE UNIQUE INDEX food_dkey ON food (dkey)") + cols = ["id", "name", "category", "countries", "portions", "dkey", "score", *COLS, *EXTRA] + upsert = (f"INSERT INTO food ({', '.join(cols)}) VALUES ({', '.join('?' * len(cols))}) ON CONFLICT(dkey) DO UPDATE SET " + + ", ".join(f"{c} = excluded.{c}" for c in cols if c != "dkey") + " WHERE excluded.score > food.score") + csv.field_size_limit(1 << 30) + best, aliases, seen = {}, {}, set() # dkey → (score, barcode); dkey → [barcodes] + n = kept = 0 + with gzip.open(src, "rt", encoding="utf-8", errors="replace", newline="") as f: + for r in csv.DictReader(f, delimiter="\t", quoting=csv.QUOTE_NONE): + n += 1 + if n % 500_000 == 0: + print(f" {n // 1000}k rows, {kept} kept, {len(best)} after merging, {time.time() - t0:.0f} s", flush=True) + p = product(r, None) + if not p or p["id"] in seen: + continue + seen.add(p["id"]) + countries = {t[3:] for t in (r.get("countries_tags") or "").split(",") if t.startswith("en:")} + p["_scans"] = min(5.0, math.log10(1 + (_f(r.get("unique_scans_n")) or 0))) + k, sc = _dkey(p), _score(p, countries) + kept += 1 + old = best.get(k) + if old and sc <= old[0]: + aliases.setdefault(k, []).append(p["barcode"]) + continue + if old: + aliases.setdefault(k, []).append(old[1]) + best[k] = (sc, p["barcode"]) + con.execute(upsert, (p["id"], p["name"], p["category"], " ".join(sorted(countries))[:200], + json.dumps(p["portions"], ensure_ascii=False) if p["portions"] else None, k, sc, + *(p.get(c) for c in COLS), *(p.get(c) for c in EXTRA))) + con.executemany("INSERT OR IGNORE INTO alias VALUES (?, ?)", + ((b, OFF_ID + int(best[k][1])) for k, bs in aliases.items() for b in bs)) + con.execute("DROP INDEX food_dkey") + con.execute("UPDATE food SET dkey = NULL") + con.executescript(""" + CREATE INDEX food_barcode ON food (barcode); + CREATE VIRTUAL TABLE food_fts USING fts5(name, brand, category, countries, content='food', content_rowid='id', + tokenize='unicode61 remove_diacritics 2', prefix='2 3'); + INSERT INTO food_fts (food_fts) VALUES ('rebuild');""") + con.execute("INSERT INTO meta VALUES ('off_source', ?), ('off_built', ?), ('products', ?), ('rows_read', ?), ('aliases', ?)", + (os.path.basename(src), time.strftime("%Y-%m-%d"), str(len(best)), str(n), + str(con.execute("SELECT count(*) FROM alias").fetchone()[0]))) + con.commit() + con.execute("VACUUM") + con.close() + print(f"{n} rows read, {kept} products, {len(best)} after merging duplicates → {out_path} " + f"({os.path.getsize(out_path) / 1e6:.0f} MB, {time.time() - t0:.0f} s)") + + +if __name__ == "__main__": + if len(sys.argv) == 4 and sys.argv[1] == "--archive": + archive(sys.argv[2], sys.argv[3]) + elif len(sys.argv) in (3, 4): + build(sys.argv[1], sys.argv[2], sys.argv[3] if len(sys.argv) == 4 else None) + else: + sys.exit(__doc__) diff --git a/dashboard/plugins/food/parse.py b/dashboard/plugins/food/parse.py new file mode 100644 index 0000000..48353eb --- /dev/null +++ b/dashboard/plugins/food/parse.py @@ -0,0 +1,142 @@ +"""Describe what you ate → entries to confirm (the describe box on /food). + +A small local model behind an Ollama-style API (`model_url`, `model` in Settings ▸ Food) +turns the text into foods with portions and a rough nutrient estimate; nothing is saved +here — the page shows the items, you fix them and save. Then each item is checked against +your history (db.match): a food you logged before with the same unit takes your own +numbers, scaled to the portion (`basis` "history"); else one of My foods or the food database's +likeliest food (lookup) when its portions say how many grams that is (`basis` "my food" / +"database", `food` = the food itself — the check list computes from it —, `unit` = its portion); +else the model's estimate stays (`basis` "estimate"). Off (Unavailable) until a model URL is +set and the model is switched on (Settings ▸ Food). + + parse(text, s, known, match) -> [{name, amount, unit, meal, kcal, protein, carbs, fat, …, basis, from}] +""" +import json +import urllib.error +import urllib.request + +from . import fooddb +from .db import MEAL_KEYS, UNITS + +TIMEOUT = 180 # s; a small model on a small board is slow +SCHEMA = { + "type": "object", + "properties": {"items": {"type": "array", "items": { + "type": "object", + "properties": {"name": {"type": "string"}, "amount": {"type": "number"}, + "unit": {"type": "string", "enum": list(UNITS)}, + "meal": {"type": "string", "enum": list(MEAL_KEYS) + [""]}, + "kcal": {"type": "number"}, "protein": {"type": "number"}, + "carbs": {"type": "number"}, "fat": {"type": "number"}}, + "required": ["name", "amount", "unit", "kcal", "protein", "carbs", "fat"]}}}, + "required": ["items"]} +PROMPT = """Turn a food diary note into JSON: {{"items": [...]}}, one item per food or drink the note +mentions — never add anything it doesn't mention. The note may be in any language (often +Slovak or Romanian): always give the name in plain English, singular, the base word first, so +it can be looked up ("rožky" → "bread roll", "maslo" → "butter", "brânză" → "cheese", +"polievka" → "soup"). Each item: + name short English name ("egg", "rye bread", "coffee with milk") + amount a number; the count for pieces, else grams or ml; a usual portion if not given + unit one of: {units} + meal one of: {meals}, or "" when the note doesn't say + kcal, protein, carbs, fat your estimate for that amount (protein / carbs / fat in grams) +{known} +Example — note: "2 eggs and 50 g of bread for breakfast, an apple later" +{{"items": [ + {{"name": "egg", "amount": 2, "unit": "pcs", "meal": "breakfast", "kcal": 143, "protein": 12.6, "carbs": 0.7, "fat": 9.5}}, + {{"name": "bread", "amount": 50, "unit": "g", "meal": "breakfast", "kcal": 133, "protein": 4.5, "carbs": 25, "fat": 1.6}}, + {{"name": "apple", "amount": 1, "unit": "pcs", "meal": "snack", "kcal": 95, "protein": 0.5, "carbs": 25, "fat": 0.3}}]}} + +Note: «{text}»""" + + +class Unavailable(RuntimeError): + pass + + +def _ask(s, prompt): + url = (s.get("model_url") or "").rstrip("/") + if not url: + raise Unavailable("No language model set up yet — Settings ▸ Food.") + req = urllib.request.Request(url + "/api/chat", method="POST", headers={"Content-Type": "application/json"}, + data=json.dumps({"model": s.get("model") or "qwen3:1.7b", "stream": False, + "think": False, "format": SCHEMA, "options": {"temperature": 0}, + "messages": [{"role": "user", "content": prompt}]}).encode()) + try: + with urllib.request.urlopen(req, timeout=TIMEOUT) as r: + out = json.load(r) + except urllib.error.HTTPError as e: + raise Unavailable(f"The model answered {e.code}: {e.read()[:200].decode(errors='replace')}") + except (urllib.error.URLError, TimeoutError, OSError) as e: + raise Unavailable(f"Can't reach the model at {url} ({getattr(e, 'reason', e)}).") + got = _json(((out.get("message") or {}).get("content")) or "") + if isinstance(got, dict): # {"items": [...]}, or one food on its own + got = got.get("items", [got] if "name" in got else None) + if not isinstance(got, list): # small models sometimes skip the wrapper: a bare list is fine + raise Unavailable("The model's answer wasn't the expected JSON — try again or simplify the note.") + return got + + +def _json(text): + """The first JSON object / list in the text: not every model keeps to `format` — some + wrap the answer in ```json fences or a sentence.""" + dec = json.JSONDecoder() + for i, ch in enumerate(text): + if ch in "{[": + try: + return dec.raw_decode(text, i)[0] + except ValueError: + continue + return None + + +def _num(x): + try: + return max(0.0, float(x)) + except (TypeError, ValueError): + return None + + +FORM = ("kcal", "protein", "carbs", "sugar", "fiber", "fat", "sat_fat", "sodium_mg") + + +def parse(text, s, known, match, lookup=None): + """known = names you log most (the model is told to reuse them); match(name) → your + latest entry of that food or None; lookup(name) → the likeliest of My foods, else of the food + database, or None.""" + hint = "" + if known: + hint = ("Names this person uses — when an item IS one of these, spell it the same way (they are not\n" + "part of the note): " + "; ".join(known) + "\n") + raw = _ask(s, PROMPT.format(units=", ".join(UNITS), meals=", ".join(MEAL_KEYS), known=hint, text=text.strip())) + out = [] + for it in raw[:20]: + if not isinstance(it, dict) or not str(it.get("name") or "").strip(): + continue + item = {"name": " ".join(str(it["name"]).split())[:120], "amount": _num(it.get("amount")), + "unit": it.get("unit") if it.get("unit") in UNITS else None, + "meal": it.get("meal") if it.get("meal") in MEAL_KEYS else None, + "basis": "estimate", "from": None, "food": None, "grams": None} + for k in ("kcal", "protein", "carbs", "fat"): + v = _num(it.get(k)) + item[k] = round(v, 1) if v is not None else None + m = match(item["name"]) + if m and (m.get("my_food_id") or m.get("food_id")): # logged from a food before: use that food + item["name"], m = m["name"], None + f = item["amount"] / m["amount"] if m and m["amount"] and item["amount"] else None + if m and m["kcal"] and m["unit"] == item["unit"] and f and 0.05 <= f <= 20: # past that: a unit mix-up + for k in FORM: + item[k] = round(m[k] * f, 1) if m[k] is not None else None + item["name"], item["basis"], item["from"] = m["name"], "history", m["id"] + elif lookup: # My foods / the food database: real numbers when the portion is known + food = lookup(item["name"]) + g, label = fooddb.portion(food, item["amount"], item["unit"]) if food else (None, None) + if g: + n = fooddb.nutrients(food, g) + for k in FORM: + item[k] = round(n[k], 1) if n.get(k) is not None else None + item.update(basis="my food" if food["kind"] == "my" else "database", food=food, unit=label, + grams=round(g, 1), food_name=food["name"]) + out.append(item) + return out diff --git a/dashboard/plugins/food/static/food.css b/dashboard/plugins/food/static/food.css new file mode 100644 index 0000000..0c56c9b --- /dev/null +++ b/dashboard/plugins/food/static/food.css @@ -0,0 +1,482 @@ +/* Food diary — on top of dash.css (its tokens, header, .ec-box dialogs). Real px. */ +/* macro colours (on :root: the dialogs sit outside .page-food) */ +:root { --pr: var(--cool); --cb: var(--accent); --ft: #c792ea; --rest: #5a6275; --bad: #ff7a7a; --good: #7fd6a3; } +.page-food { display: flex; flex-direction: column; gap: 14px; font-size: 15px; } +.fd { display: grid; grid-template-columns: minmax(280px, 380px) minmax(0, 1fr); gap: 16px; align-items: start; } +.fd-now, .fd-say, .fd-meal, .fd-card { background: var(--card); border-radius: 14px; padding: 18px 20px; } +.fd-side { display: flex; flex-direction: column; gap: 12px; min-width: 0; } +.fd-main { display: flex; flex-direction: column; gap: 14px; min-width: 0; } +.fd-seg.seg { height: 46px; } +.fd-seg.seg a { flex: 1; width: auto; font-size: 16px; } +.fd-cap { margin: 0; font: 400 12.5px "DejaVu Web", sans-serif; color: var(--dim); text-transform: uppercase; letter-spacing: .04em; align-self: flex-start; } + +/* ---- the day: ring + bars ------------------------------------------------------------ */ +.fd-now { display: flex; flex-direction: column; align-items: center; gap: 14px; } +.fd-ring { position: relative; width: min(230px, 64vw); aspect-ratio: 1; } +.fd-ring svg { width: 100%; height: 100%; display: block; } +.fd-ring circle, .fd-ring path { fill: none; stroke-width: 9; stroke-linecap: round; } +.fd-track { stroke: #262d3b; } +.fd-ring.over .fd-track { stroke: #5a2630; } +.fd-arc.protein { stroke: var(--pr); } .fd-arc.carbs { stroke: var(--cb); } .fd-arc.fat { stroke: var(--ft); } .fd-arc.kcal { stroke: var(--fg); } +.fd-mid { position: absolute; inset: 18%; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 3px; text-align: center; } +.fd-mid b { font: 700 36px/1.1 "DejaVu Web", sans-serif; } +.fd-mid span { color: var(--muted); font-size: 14px; } +.fd-mid em { font-style: normal; font-size: 14px; color: var(--fg); margin-top: 4px; } +.fd-ring.over .fd-mid em { color: var(--bad); } + +.fd-macros { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; width: 100%; } +.fd-mac { display: flex; flex-direction: column; gap: 3px; min-width: 0; } +.fd-mac > span { font-size: 12px; color: var(--dim); text-transform: uppercase; } +.fd-mac b { font: 700 18px "DejaVu Web", sans-serif; white-space: nowrap; } +.fd-mac b small { font-weight: 400; font-size: 12.5px; color: var(--muted); } +.fd-mac i, .fd-more i { display: block; height: 6px; border-radius: 3px; background: #262d3b; overflow: hidden; margin-top: 2px; } +.fd-mac s, .fd-more s { display: block; height: 100%; border-radius: 3px; text-decoration: none; } +.fd-mac.protein s { background: var(--pr); } .fd-mac.carbs s { background: var(--cb); } .fd-mac.fat s { background: var(--ft); } +.fd-mac.high b { color: var(--accent); } +.fd-more { width: 100%; margin: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 10px 16px; } +.fd-more div { display: grid; grid-template-columns: 1fr auto; align-items: baseline; gap: 0 6px; min-width: 0; } +.fd-more dt { color: var(--muted); font-size: 13px; } +.fd-more dd { margin: 0; font-size: 14px; white-space: nowrap; } +.fd-more dd small { color: var(--dim); font-size: 11.5px; } +.fd-more i { grid-column: 1 / -1; height: 4px; } +.fd-more s { background: var(--muted); } +.fd-more .over dd { color: var(--bad); } .fd-more .over s { background: var(--bad); } +.fd-more i.info { background: transparent; } /* total sugar: shown, no limit (added sugar has it) */ +.fd-more .ok s { background: var(--good); } + +/* ---- add / describe ------------------------------------------------------------------- */ +.fd-say { padding: 14px; } +.fd-sayf { display: flex; flex-direction: column; gap: 10px; } +.fd-sayf textarea { width: 100%; box-sizing: border-box; resize: vertical; min-height: 70px; line-height: 1.4; + font: 15px "DejaVu Web", sans-serif; color: var(--fg); background: #1d222d; border: 0; border-radius: 8px; padding: 9px 11px; } +.fd-sayf textarea:disabled { opacity: .55; } +.fd-sayf textarea:focus { outline: 2px solid var(--accent); outline-offset: -1px; } +.fd-sayb { display: flex; gap: 10px; justify-content: space-between; align-items: center; } +.fd-add, .fd-go, .fd-save { border: 0; border-radius: 10px; padding: 9px 16px; cursor: pointer; font: 700 15px "DejaVu Web", sans-serif; } +.fd-add { background: #262d3b; color: var(--fg); font-weight: 400; } +.fd-add:hover { background: #2e3647; } +.fd-go, .fd-save { background: var(--accent); color: var(--bg); } +.fd-go:disabled, .fd-save:disabled { opacity: .5; cursor: default; } +.fd-go.busy, .fd-save.busy { cursor: wait; } +.fd-err, .fd-ferr { margin: 0; color: var(--bad); font-size: 14px; } .fd-err:empty { display: none; } +/* hover tip (the off describe button) */ +.fd-tt { position: relative; display: inline-flex; } +.fd-pop { display: none; position: absolute; right: 0; bottom: calc(100% + 8px); width: 240px; z-index: 5; padding: 9px 11px; + background: #262d3b; color: var(--fg); border-radius: 8px; font-size: 13px; line-height: 1.4; box-shadow: 0 4px 14px rgba(0, 0, 0, .4); } +.fd-tt:hover .fd-pop, .fd-tt:focus .fd-pop, .fd-tt:focus-within .fd-pop { display: block; } + +/* ---- week strip ----------------------------------------------------------------------- */ +.fd-week { display: grid; grid-template-columns: repeat(7, minmax(0, 1fr)) minmax(120px, 1.4fr); gap: 6px; + background: var(--card); border-radius: 14px; padding: 10px; } +.fd-wd { display: flex; flex-direction: column; align-items: center; gap: 4px; padding: 6px 2px; border-radius: 9px; color: var(--fg); text-decoration: none; } +a.fd-wd:hover { background: #1d222d; } +.fd-wd.sel { background: #262d3b; } +.fd-wd.today .fd-wn { color: var(--accent); font-weight: 700; } +.fd-wd.future { opacity: .4; } +.fd-wn { font-size: 13px; color: var(--muted); white-space: nowrap; } +.fd-wb { position: relative; width: 14px; height: 40px; border-radius: 4px; background: #1b1f29; overflow: hidden; } +.fd-wb s { position: absolute; left: 0; right: 0; bottom: 0; max-height: 100%; background: var(--good); opacity: .85; } +.fd-wd.over .fd-wb s { background: var(--bad); } +.fd-wd.sel .fd-wb s { opacity: 1; } +.fd-wk { font-size: 12px; color: var(--muted); min-height: 1.2em; } +.fd-wsum { display: flex; flex-direction: column; justify-content: center; align-items: flex-end; text-align: right; padding-right: 6px; color: var(--muted); font-size: 13px; } +.fd-wsum b { font: 700 20px "DejaVu Web", sans-serif; color: var(--fg); } +.fd-wsum small { color: var(--dim); font-size: 12px; } + +/* ---- meals ---------------------------------------------------------------------------- */ +/* two fixed columns (breakfast + lunch | dinner + snacks): nothing jumps when a card grows */ +.fd-meals { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; align-items: start; } +.fd-mcol { display: flex; flex-direction: column; gap: 14px; min-width: 0; } +.fd-meal { padding: 14px 16px; display: flex; flex-direction: column; gap: 8px; } +.fd-mh { display: flex; align-items: center; gap: 10px; } +.fd-mh h2 { margin: 0; font: 700 17px "DejaVu Web", sans-serif; flex: 1; } +.fd-mt { display: flex; flex-direction: column; align-items: flex-end; font-weight: 700; } +.fd-mt small { font-weight: 400; font-size: 12px; color: var(--dim); } +.fd-plus { width: 32px; height: 32px; flex: none; border: 0; border-radius: 50%; background: #262d3b; color: var(--accent); + font: 700 20px/1 "DejaVu Web", sans-serif; cursor: pointer; } +.fd-plus:hover { background: #2e3647; } +.fd-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; } +.fd-list li + li { border-top: 1px solid #222837; } +.fd-e { width: 100%; display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: 0 12px; align-items: baseline; text-align: left; + border: 0; background: none; color: var(--fg); padding: 8px 6px; border-radius: 8px; cursor: pointer; font: 15px "DejaVu Web", sans-serif; } +.fd-e:hover { background: #1d222d; } +.fd-e:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.fd-en { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fd-nt { font-style: normal; color: var(--dim); margin-left: 6px; font-size: 12px; } +.fd-ea { color: var(--muted); font-size: 13px; white-space: nowrap; } +.fd-ek { white-space: nowrap; text-align: right; min-width: 64px; } +.fd-ek small { color: var(--dim); font-size: 11.5px; } +.fd-em { grid-column: 1 / -1; color: var(--dim); font-size: 12px; } +.fd-empty { border: 1px dashed #2e3647; background: none; color: var(--dim); border-radius: 8px; padding: 10px; cursor: pointer; font: 14px "DejaVu Web", sans-serif; } +.fd-empty:hover { color: var(--fg); border-color: var(--muted); } + +/* ---- history -------------------------------------------------------------------------- */ +.fd-rbar { display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap; } +.fd-rbar h2 { margin: 0; font: 400 15px "DejaVu Web", sans-serif; color: var(--muted); } +.fd-rseg { display: flex; background: var(--card); border-radius: 10px; overflow: hidden; } +.fd-rseg a { padding: 8px 14px; color: var(--muted); text-decoration: none; font-size: 14px; } +.fd-rseg a.on { background: #262d3b; color: var(--accent); } +.fd-rseg a:not(.on):hover { background: #1d222d; color: var(--fg); } +.fd-none { background: var(--card); border-radius: 14px; padding: 22px; color: var(--muted); } +.fd-none a, .fd-mini { color: var(--cool); } +.fd-mini { font-size: 13.5px; text-decoration: none; } .fd-mini:hover { text-decoration: underline; } +.fd-tiles { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; } +.fd-tiles > div { background: var(--card); border-radius: 12px; padding: 12px 14px; display: flex; flex-direction: column; gap: 3px; } +.fd-tiles span { font-size: 12px; color: var(--dim); text-transform: uppercase; } +.fd-tiles b { font: 700 22px "DejaVu Web", sans-serif; } +.fd-tiles b em { font-style: normal; font-weight: 400; font-size: 13px; color: var(--muted); } +.fd-tiles small { color: var(--muted); font-size: 12.5px; } +.fd-tiles .ok b { color: var(--good); } .fd-tiles .over b { color: var(--bad); } +.fd-split i { display: flex; height: 10px; border-radius: 5px; overflow: hidden; margin: 8px 0 4px; } +.fd-split s, .fd-legend i { display: block; height: 100%; } +.fd-split small { display: flex; gap: 8px; white-space: nowrap; } +.fd-split small em { font-style: normal; } +.protein { --c: var(--pr); } .carbs { --c: var(--cb); } .fat { --c: var(--ft); } +.fd-split s { background: var(--c); } .fd-split em { color: var(--c); } + +.fd-chead { display: flex; align-items: baseline; justify-content: space-between; gap: 10px; flex-wrap: wrap; margin-bottom: 10px; } +.fd-chead h2 { margin: 0; font: 700 16px "DejaVu Web", sans-serif; } +.fd-legend { display: flex; gap: 12px; color: var(--muted); font-size: 12.5px; } +.fd-legend span { display: inline-flex; align-items: center; gap: 5px; } +.fd-legend i { width: 10px; height: 10px; border-radius: 3px; background: var(--c); } +.fd-legend i.tl { height: 0; border-top: 2px dashed var(--fg); border-radius: 0; background: none; } +.fd-chart { width: 100%; height: 260px; display: block; overflow: visible; } +.fd-chart rect.hit { fill: transparent; } +.fd-bar:hover rect.hit { fill: #1d222d; } +.fd-chart rect.protein { fill: var(--pr); } .fd-chart rect.carbs { fill: var(--cb); } .fd-chart rect.fat { fill: var(--ft); } .fd-chart rect.rest { fill: var(--rest); } +.fd-chart .tl { stroke: var(--fg); stroke-width: 1.5; stroke-dasharray: 6 5; vector-effect: non-scaling-stroke; opacity: .7; } +.fd-chart .base { stroke: #2e3647; stroke-width: 1; vector-effect: non-scaling-stroke; } +.fd-chart text { fill: var(--muted); font: 13px "DejaVu Web", sans-serif; text-anchor: middle; } +.fd-two { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 14px; align-items: start; } +.fd-t { width: 100%; border-collapse: collapse; font-size: 14px; } +.fd-t th, .fd-t td { padding: 6px 8px; text-align: right; border-bottom: 1px solid #222837; } +.fd-t th:first-child, .fd-t td:first-child { text-align: left; } +.fd-t thead th { color: var(--dim); font-weight: 400; font-size: 12px; text-transform: uppercase; } +.fd-avg th { text-align: left; font-weight: 400; color: var(--fg); } +.fd-avg tr.sub th { padding-left: 22px; color: var(--muted); } +.fd-t .dim { color: var(--dim); font-size: 12.5px; } + +/* ---- dialogs -------------------------------------------------------------------------- */ +.fd-modal[hidden] { display: none !important; } +.fd-modal { position: fixed; inset: 0; z-index: 10; display: flex; align-items: center; justify-content: center; } +.fd-box { --ec: var(--good); display: flex; flex-direction: column; gap: 14px; width: min(600px, 94vw); } +.fd-cbox { width: min(760px, 96vw); } +.fd-ftitle { font: 700 22px "DejaVu Web", sans-serif; color: var(--good); padding-right: 34px; } +.fd-box label { display: flex; flex-direction: column; gap: 4px; min-width: 0; } +.fd-box label > span:first-child { font-size: 12.5px; color: var(--dim); text-transform: uppercase; letter-spacing: .04em; } +.fd-box input, .fd-box select, .fd-box textarea { font: 16px "DejaVu Web", sans-serif; color: var(--fg); background: #1d222d; + border: 0; border-radius: 8px; padding: 8px 10px; min-width: 0; box-sizing: border-box; } +.fd-box select { padding: 8px 6px; } +.fd-box textarea { width: 100%; resize: vertical; line-height: 1.4; } +.fd-box :focus { outline: 2px solid var(--accent); outline-offset: -1px; } +.fd-box .bad { outline: 2px solid var(--bad); outline-offset: -1px; } +.fd-name { position: relative; } +.fd-name input { font-size: 18px; } +.fd-sugg { position: absolute; left: 0; right: 0; top: 100%; z-index: 3; margin: 4px 0 0; padding: 4px; list-style: none; background: #262d3b; + border-radius: 10px; box-shadow: 0 6px 18px rgba(0, 0, 0, .45); max-height: 280px; overflow: auto; } +.fd-sugg li { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 12px; align-items: baseline; padding: 7px 10px; border-radius: 7px; cursor: pointer; } +.fd-sugg .fd-sk { text-align: right; white-space: nowrap; font-size: 14px; } +.fd-sugg .fd-sk i { font-style: normal; color: var(--dim); font-size: 11.5px; } +.fd-sugg .fd-ss { display: flex; gap: 4px; justify-content: flex-end; align-items: center; color: var(--dim); font-size: 12px; } +.fd-sugg .fd-ss .fd-nova { padding: 0 5px; font-size: 11px; } +.fd-sugg li.on, .fd-sugg li:hover { background: #313a4d; } +.fd-sugg b { font-weight: 400; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fd-sugg small { color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.fd-sugg .new { color: var(--muted); font-style: italic; } +.fd-chips { display: flex; flex-wrap: wrap; gap: 6px; } +.fd-chip { border: 0; border-radius: 8px; padding: 6px 12px; background: #262d3b; color: var(--muted); cursor: pointer; font: 14px "DejaVu Web", sans-serif; } +.fd-chip:hover { color: var(--fg); } +.fd-chip.sel { background: #1d2a22; color: var(--good); box-shadow: inset 0 0 0 1px rgba(127, 214, 163, .45); } +.fd-row { display: flex; gap: 10px; flex-wrap: wrap; } +.fd-row label { flex: 1 1 120px; } +.fd-row .fd-amt { flex: 1.4 1 170px; } +.fd-in { display: flex; align-items: center; background: #1d222d; border-radius: 8px; min-width: 0; } +.fd-in input { flex: 1; width: 100%; background: none; } +.fd-in select { background: #262d3b; border-radius: 0 8px 8px 0; max-width: 62%; text-overflow: ellipsis; } +.fd-amt .fd-in input { min-width: 56px; } +.fd-in i { font-style: normal; color: var(--dim); font-size: 13px; padding: 0 10px 0 2px; white-space: nowrap; } +.fd-scale { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; color: var(--muted); font-size: 13.5px; } +.fd-scale[hidden] { display: none; } +.fd-nut { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px 14px; } +.fd-nut label.kc { grid-column: 1 / -1; } +.fd-nut label.kc input { font-size: 20px; font-weight: 700; } +.fd-nut label.sub > span:first-child { text-transform: none; letter-spacing: 0; padding-left: 12px; } +.fd-actions { display: flex; align-items: center; justify-content: flex-end; gap: 14px; flex-wrap: wrap; } +.fd-ferr { flex: 1; min-width: 120px; } +.fd-src { color: var(--dim); font-size: 12.5px; } +.fd-del { border: 0; border-radius: 10px; padding: 9px 14px; background: #262d3b; color: #ff9a9a; cursor: pointer; font: 15px "DejaVu Web", sans-serif; } +.fd-del.armed { background: #8a2b2b; color: #fff; } +.fd-del[hidden] { display: none; } +/* the describe box's list */ +.fd-said { margin: -6px 0 0; color: var(--muted); font-style: italic; } +.fd-items { display: flex; flex-direction: column; gap: 10px; } +.fd-item { background: #171b24; border-radius: 10px; padding: 10px; display: flex; flex-direction: column; gap: 8px; } +.fd-item.gone { display: none; } +.fd-ih { display: flex; gap: 8px; align-items: center; } +.fd-ih input { flex: 1; font-size: 16px; } +.fd-basis { font-size: 12px; padding: 3px 8px; border-radius: 6px; background: #262d3b; color: var(--muted); white-space: nowrap; } +.fd-basis.history { color: var(--good); } +.fd-rm { border: 0; background: none; color: var(--muted); cursor: pointer; font-size: 16px; padding: 4px 6px; } +.fd-rm:hover { color: var(--bad); } +.fd-ib { display: grid; grid-template-columns: 1.5fr 1.1fr repeat(4, minmax(0, 1fr)); gap: 6px; } +.fd-ib input, .fd-ib select { font-size: 14.5px; padding: 7px 6px; } +.fd-ib .fd-in i { padding: 0 6px 0 0; font-size: 11.5px; } +.fd-ctotal { color: var(--muted); } + +/* ---- narrow --------------------------------------------------------------------------- */ +@media (max-width: 1099px) { .fd-meals, .fd-two { grid-template-columns: minmax(0, 1fr); } } +@media (max-width: 799px) { + .fd { grid-template-columns: minmax(0, 1fr); } + .fd-week { grid-template-columns: repeat(7, minmax(0, 1fr)); } + .fd-wsum { grid-column: 1 / -1; flex-direction: row; justify-content: center; align-items: baseline; gap: 6px; } + .fd-ib { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} +@media (max-width: 499px) { + .fd-now, .fd-meal, .fd-card { padding: 14px 12px; } + .fd-week { padding: 6px; gap: 2px; } + .fd-wk { font-size: 10.5px; } + .fd-nut { grid-template-columns: minmax(0, 1fr); } + .fd-chart { height: 200px; } +} +.fd-add.wide { width: 100%; padding: 12px; font-size: 16px; } +.fd-sugg li.fd-sh { display: block; cursor: default; padding: 8px 10px 3px; font-size: 11.5px; color: var(--dim); text-transform: uppercase; letter-spacing: .04em; background: none; } +.fd-dbn { margin: -6px 0 0; color: var(--muted); font-size: 13px; } +.fd-dbn[hidden] { display: none; } +.fd-basis.database { color: var(--cool); } + +/* ---- the dialog's modes (food.js) ---------------------------------------------------- */ +.fd-fline { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin-top: -6px; min-height: 30px; } +.fd-fsrc { flex: 1; color: var(--muted); font-size: 13.5px; } +.fd-edit, .fd-tot, .fd-padd { border: 0; border-radius: 8px; padding: 6px 12px; background: #262d3b; color: var(--cool); cursor: pointer; font: 14px "DejaVu Web", sans-serif; } +.fd-edit:hover, .fd-tot:hover, .fd-padd:hover { background: #2e3647; } +.fd-box[data-mode="new"] .fd-edit, .fd-box[data-mode="totals"] .fd-edit, .fd-box[data-mode="foodonly"] .fd-edit { display: none; } +.fd-box:not([data-mode="new"]):not([data-mode="totals"]) .fd-tot { display: none; } +.fd-box[data-mode="foodonly"] .fd-entry, .fd-box[data-mode="foodonly"] .fd-fline { display: none; } +.fd-box[data-mode="totals"] .fd-this, .fd-box[data-mode="totals"] .fd-ports, .fd-box[data-mode="food"] .fd-ports { display: none; } /* locked: its portions are in the unit list */ +.fd-entry { display: flex; flex-direction: column; gap: 14px; } +.fd-per { border: 1px solid #262d3b; border-radius: 10px; padding: 10px 12px 12px; margin: 0; min-width: 0; display: flex; flex-direction: column; gap: 12px; } +.fd-perh { padding: 0 6px; font-size: 12.5px; color: var(--dim); text-transform: uppercase; letter-spacing: .04em; } +.fd-per:disabled { border-style: dashed; } +.fd-per:disabled input { color: var(--muted); background: #171b24; cursor: default; } +.fd-box[data-mode="edit"] .fd-per { border-color: var(--cool); } +.fd-this { display: flex; align-items: baseline; gap: 4px 12px; flex-wrap: wrap; background: #171b24; border-radius: 10px; padding: 10px 12px; } +.fd-thh { font-size: 12.5px; color: var(--dim); text-transform: uppercase; letter-spacing: .04em; } +.fd-thk { font: 700 22px "DejaVu Web", sans-serif; color: var(--good); } +.fd-thm { color: var(--muted); font-size: 13.5px; } +.fd-ports { display: flex; flex-direction: column; gap: 6px; } +.fd-pth { font-size: 12.5px; color: var(--dim); text-transform: uppercase; letter-spacing: .04em; } +.fd-pth small { text-transform: none; letter-spacing: 0; } +.fd-plist { display: flex; flex-direction: column; gap: 6px; } +.fd-prow { display: grid; grid-template-columns: minmax(0, 1.4fr) minmax(90px, 1fr) auto; gap: 6px; align-items: center; border-radius: 8px; } +.fd-prow.bad { outline: 2px solid var(--bad); } +.fd-prm { border: 0; background: none; color: var(--muted); cursor: pointer; font-size: 15px; padding: 4px 8px; } +.fd-prm:hover { color: var(--bad); } +.fd-padd { align-self: flex-start; } +.fd-copy { margin: -10px 0 0; color: var(--cool); font-size: 13.5px; } .fd-copy:empty { display: none; } +.fd-item.linked .fd-ib input[readonly] { color: var(--muted); background: #141821; } +.fd-basis.my-food { color: var(--good); } +/* My foods page */ +.fd-ft tbody tr { cursor: pointer; } +.fd-ft tbody tr:hover td { background: #1d222d; } +.fd-ft td small { display: block; color: var(--dim); font-size: 12px; } +.fd-ft td.dim { max-width: 240px; white-space: normal; } +.fd-none0 { margin: 8px 0 0; color: var(--muted); } +.fd-chead small { font-weight: 400; color: var(--dim); } + +/* ---- meals: the builder + the button ------------------------------------------------- */ +.fd-mk, .fd-sec { border: 0; border-radius: 10px; padding: 9px 14px; background: #262d3b; color: var(--good); cursor: pointer; font: 15px "DejaVu Web", sans-serif; } +.fd-mk:hover, .fd-sec:hover { background: #2e3647; } +.fd-sayb .fd-mk { margin-right: auto; } +.fd-sayb .fd-add.wide { flex: 1; width: auto; } +.fd-mbox { width: min(720px, 96vw); } +.fd-mname input { font-size: 18px; } +.fd-ings { display: flex; flex-direction: column; gap: 8px; } +.fd-ilist { display: flex; flex-direction: column; gap: 6px; } +.fd-ing { display: grid; grid-template-columns: minmax(0, 1fr) minmax(170px, 230px) 76px auto; gap: 8px; align-items: center; + background: #171b24; border-radius: 8px; padding: 6px 6px 6px 10px; } +.fd-ing.bad { outline: 2px solid var(--bad); } +.fd-iname { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fd-iname small { display: block; color: var(--dim); font-size: 11.5px; } +.fd-ing .fd-in input { min-width: 50px; } +.fd-ik { text-align: right; color: var(--muted); font-size: 14px; white-space: nowrap; } +.fd-iadd input { font-size: 15px; } +.fd-done { flex: 0 1 220px; } +.fd-mper { flex: 1; align-self: flex-end; margin: 0 0 9px; color: var(--muted); font-size: 13.5px; } +@media (max-width: 599px) { + .fd-ing { grid-template-columns: minmax(0, 1fr) auto; } + .fd-ing .fd-in { grid-column: 1; } .fd-ik { grid-column: 2; grid-row: 1; } +} +.fd-hb { display: flex; gap: 8px; flex-wrap: wrap; } +/* picking the day's entries for a meal */ +.fd-pickbar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; background: #1d2a22; border-radius: 12px; padding: 10px 14px; + box-shadow: inset 0 0 0 1px rgba(127, 214, 163, .45); } +.fd-pickbar[hidden] { display: none; } +.fd-pickbar > span { flex: 1; min-width: 200px; } +.fd-pickn { color: var(--good); } +.fd.picking .fd-e { padding-left: 34px; position: relative; } +.fd.picking .fd-e::before { content: ""; position: absolute; left: 8px; top: 10px; width: 16px; height: 16px; border-radius: 4px; + box-shadow: inset 0 0 0 2px var(--muted); } +.fd.picking .fd-e.sel { background: #1d2a22; } +.fd.picking .fd-e.sel::before { background: var(--good); box-shadow: none; } +.fd.picking .fd-e.sel::after { content: "✓"; position: absolute; left: 10px; top: 8px; font-size: 13px; color: var(--bg); font-weight: 700; } +.fd.picking .fd-plus, .fd.picking .fd-empty { visibility: hidden; } +.fd-ifix { color: var(--muted); font-size: 13.5px; } +.fd-ifix i { font-style: normal; color: var(--accent); } +.fd-repl { flex-direction: row !important; align-items: flex-start; gap: 10px !important; background: #171b24; border-radius: 10px; padding: 10px 12px; } +.fd-repl[hidden] { display: none !important; } +.fd-repl input { margin-top: 3px; } +.fd-repl span { font-size: 14px; color: var(--fg) !important; text-transform: none !important; letter-spacing: 0 !important; } + +/* ---- the day's activity (from Health) under the macros; days ahead ---------------------- */ +.fd-act { width: 100%; border-top: 1px solid #262d3b; padding-top: 12px; display: flex; flex-direction: column; gap: 7px; } +.fd-acth { display: flex; justify-content: space-between; align-items: baseline; } +.fd-acth span { font-size: 12px; color: var(--dim); text-transform: uppercase; } +.fd-actl { display: flex; flex-wrap: wrap; gap: 6px; } +.fd-actl > * { background: #1d222d; border-radius: 7px; padding: 4px 9px; font-size: 13.5px; color: var(--fg); text-decoration: none; } +.fd-actl a:hover { background: #262d3b; } +.fd-actl .dim { color: var(--dim); } +.fd-bal { display: flex; justify-content: space-between; gap: 10px; flex-wrap: wrap; font-size: 14px; color: var(--muted); } +.fd-bal b { color: var(--fg); } +.fd-bal b.neg { color: var(--good); } .fd-bal b.pos { color: var(--accent); } +.fd-wd.ahead { opacity: .7; } +.fd-wd.ahead .fd-wb { background: repeating-linear-gradient(135deg, #1b1f29 0 4px, #20252f 4px 8px); } + +/* ---- a product's extras (Open Food Facts): Nutri-Score, NOVA, allergens, labels, ingredients ---- */ +.fd-pinfo { display: flex; flex-direction: column; gap: 6px; margin-top: -6px; } +.fd-pinfo[hidden] { display: none; } +.fd-pbadges { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.fd-ns, .fd-nova { display: inline-block; border-radius: 6px; padding: 2px 8px; font: 700 12.5px "DejaVu Web", sans-serif; color: #0d1017; cursor: help; } +.fd-sugg .fd-ns { padding: 0 5px; font-size: 11px; } +.ns-a { background: #038141; color: #fff; } .ns-b { background: #85bb2f; } .ns-c { background: #fecb02; } +.ns-d { background: #ee8100; } .ns-e { background: #e63e11; color: #fff; } +.nova-1 { background: #00aa00; color: #fff; } .nova-2 { background: #ffcc00; } .nova-3 { background: #ff6600; } .nova-4 { background: #ff0000; color: #fff; } +.fd-alg { font-size: 13px; color: #ffb36b; } +.fd-lab { font-size: 13px; color: var(--good); } +.fd-ing-t summary { cursor: pointer; color: var(--cool); font-size: 13.5px; } +.fd-ing-t p { margin: 6px 0 0; color: var(--muted); font-size: 13px; line-height: 1.45; max-height: 140px; overflow: auto; } + +/* ---- the inline editor (food.js openEditor) ------------------------------------------------ */ +.fd-ie { margin-top: 6px; background: #171b24; border-radius: 10px; padding: 10px; display: flex; flex-direction: column; gap: 8px; + box-shadow: inset 0 0 0 1px #2e3647; } +.fd-list li .fd-ie { margin: 4px 0; } +.fd-ie-q { position: relative; display: flex; gap: 6px; align-items: center; } +.fd-ie-q input { flex: 1; font: 16px "DejaVu Web", sans-serif; color: var(--fg); background: #1d222d; border: 0; border-radius: 8px; padding: 9px 11px; min-width: 0; } +.fd-ie input, .fd-ie select { font: 15px "DejaVu Web", sans-serif; color: var(--fg); background: #1d222d; border: 0; border-radius: 8px; padding: 7px 9px; min-width: 0; box-sizing: border-box; } +.fd-ie :focus { outline: 2px solid var(--accent); outline-offset: -1px; } +.fd-ie .bad { outline: 2px solid var(--bad); outline-offset: -1px; } +.fd-ie-sel { display: flex; flex-direction: column; gap: 8px; } +.fd-ie[data-mode="search"] .fd-ie-sel, .fd-ie:not([data-mode="search"]) .fd-ie-q { display: none; } +.fd-ie-h { display: flex; align-items: flex-start; gap: 8px; } +.fd-ie-t { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 2px; } +.fd-ie-name { font-weight: 700; cursor: pointer; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fd-ie-name:hover { text-decoration: underline dotted; } +.fd-ie-nm { font-weight: 700; } +.fd-ie[data-mode="food"] .fd-ie-nm, .fd-ie:not([data-mode="food"]) .fd-ie-name { display: none; } +.fd-ie-src { color: var(--dim); font-size: 12px; } +.fd-ie-x { border: 0; background: none; color: var(--muted); font-size: 15px; cursor: pointer; padding: 4px 6px; } +.fd-ie-x:hover { color: var(--fg); } +.fd-ie-mac { font-size: 13.5px; color: var(--muted); } +.fd-ie-mac b { color: var(--good); font-size: 16px; } +.fd-ie[data-mode="totals"] .fd-ie-mac { display: none; } +.fd-ie-tot { display: none; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 6px; } +.fd-ie[data-mode="totals"] .fd-ie-tot { display: grid; } +.fd-ie-tot label, .fd-ie-extra label { display: flex; flex-direction: column; gap: 3px; min-width: 0; } +.fd-ie-tot label > span:first-child, .fd-ie-extra label > span:first-child { font-size: 11.5px; color: var(--dim); text-transform: uppercase; } +.fd-ie .fd-in { display: flex; align-items: center; background: #1d222d; border-radius: 8px; min-width: 0; } +.fd-ie .fd-in input { flex: 1; width: 100%; background: none; } +.fd-ie .fd-in select { background: #262d3b; border-radius: 0 8px 8px 0; max-width: 64%; } +.fd-ie .fd-in i { font-style: normal; color: var(--dim); font-size: 12px; padding: 0 8px 0 2px; } +.fd-ie-row { display: flex; gap: 8px; align-items: center; } +.fd-ie-amt { flex: 0 1 auto; } +.fd-ie .fd-ie-amt input { width: 80px; flex: none; } +.fd-ie .fd-ie-amt select { max-width: 240px; } +.fd-ie-ok { padding: 8px 18px; margin-left: auto; } +.fd-ie-per { display: none; flex-direction: column; gap: 10px; border-top: 1px dashed #2e3647; padding-top: 8px; } +.fd-ie[data-mode="edit"] .fd-ie-per, .fd-ie[data-mode="new"] .fd-ie-per { display: flex; } +.fd-ie-per label { display: flex; flex-direction: column; gap: 3px; } +.fd-ie-per label > span:first-child { font-size: 11.5px; color: var(--dim); text-transform: uppercase; } +.fd-ie-per label.sub > span:first-child { text-transform: none; padding-left: 10px; } +.fd-ie-extra { display: none; grid-template-columns: auto auto minmax(0, 1fr); gap: 8px; } +.fd-ie.more .fd-ie-extra { display: grid; } +.fd-ie-links { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; } +.fd-ie-links .fd-ie-more, .fd-ie-links .fd-ie-edit { border: 0; background: none; color: var(--cool); cursor: pointer; font: 13.5px "DejaVu Web", sans-serif; padding: 2px 4px; } +.fd-ie-links .fd-ie-more:hover, .fd-ie-links .fd-ie-edit:hover { text-decoration: underline; } +.fd-ie.more .fd-ie-more { color: var(--fg); } +.fd-ie-err { flex: 1; color: var(--bad); font-size: 13.5px; } +/* trash icon, left of Save (editing only); the first click arms it (red), the second deletes */ +.fd-ie-del { margin-left: auto; width: 36px; height: 36px; flex: none; border: 0; border-radius: 9px; background: #262d3b; + color: #ff9a9a; cursor: pointer; display: inline-flex; align-items: center; justify-content: center; } +.fd-ie-del svg { width: 18px; height: 18px; } +.fd-ie-del:hover { background: #2e3647; } +.fd-ie-del.armed { background: #8a2b2b; color: #fff; } +.fd-ie-del[hidden] { display: none; } +.fd-ie-del:not([hidden]) + .fd-ie-ok { margin-left: 0; } +.fd-sugg li.fd-snew b { color: var(--cool); } +@media (max-width: 499px) { + .fd-ie-tot { grid-template-columns: repeat(2, minmax(0, 1fr)); } + .fd-ie-extra { grid-template-columns: 1fr 1fr; } .fd-ie-nt { grid-column: 1 / -1; } +} + +/* protein / carbs / fat as coloured dots (the ring's colours; the names on hover): _head.mac, food.js macDots */ +.fd-mx { display: inline-flex; gap: 10px; align-items: center; white-space: nowrap; } +.fd-mx > span { display: inline-flex; align-items: center; gap: 4px; cursor: default; } +.fd-mx i { width: 7px; height: 7px; border-radius: 50%; background: var(--c); flex: none; } +.fd-mt small .fd-mx { gap: 8px; } +.fd-split small.fd-mx > span { color: var(--c); } + +/* ---- yesterday's foods under an empty add box (food.js openEditor → yesterday) --------------- */ +.fd-yd { display: flex; flex-direction: column; gap: 1px; } +.fd-yd[hidden], .fd-ie:not([data-mode="search"]) .fd-yd { display: none; } +.fd-ydh { font-size: 11.5px; color: var(--dim); text-transform: uppercase; letter-spacing: .03em; margin: 4px 2px 3px; } +summary.fd-ydh { cursor: pointer; } +.fd-ydo { display: flex; flex-direction: column; gap: 1px; } +.fd-ydr { display: flex; align-items: center; gap: 8px; border-radius: 8px; padding: 1px 2px 1px 8px; } +.fd-ydr:hover { background: #1d222d; } +.fd-ydp { flex: 1; min-width: 0; display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: 0 10px; align-items: baseline; + border: 0; background: none; color: var(--fg); text-align: left; padding: 6px 0; cursor: pointer; font: 14.5px "DejaVu Web", sans-serif; } +.fd-ydn { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fd-yda { color: var(--muted); font-size: 13px; white-space: nowrap; } +.fd-ydk { color: var(--muted); font-size: 13px; white-space: nowrap; } +.fd-ydadd { width: 30px; height: 30px; flex: none; border: 0; border-radius: 50%; background: #262d3b; color: var(--accent); + font: 700 18px/1 "DejaVu Web", sans-serif; cursor: pointer; } +.fd-ydadd:hover { background: #2e3647; } +.fd-ydr.done .fd-ydadd { color: var(--good); font-size: 15px; } +.fd-ydr.done .fd-ydn { color: var(--muted); } +.fd-yderr { margin: 4px 2px 0; color: var(--bad); font-size: 13.5px; } + +/* ---- dragging a logged food into another meal (food.js): the ⠿ on the row's left ------------- */ +.fd-list li { position: relative; } +.fd-grip { position: absolute; left: 0; top: 0; bottom: 0; width: 20px; z-index: 1; cursor: grab; touch-action: none; opacity: .3; } +.fd-grip::before { content: "⠿"; position: absolute; left: 3px; top: 50%; transform: translateY(-50%); font-size: 15px; color: var(--muted); } +.fd-list li:hover .fd-grip { opacity: 1; } +@media (hover: none) { .fd-grip { opacity: .7; } } +.fd-list li:has(.fd-grip) > .fd-e { padding-left: 24px; } +.fd.picking .fd-grip, .fd-list li:has(.fd-ie) .fd-grip { display: none; } +.fd.picking .fd-list li > .fd-e { padding-left: 34px; } +.fd-list li.dragging { opacity: .35; } +.fd-e.fd-drag { position: fixed; z-index: 40; pointer-events: none; background: #262d3b; box-shadow: 0 8px 24px rgba(0, 0, 0, .5); opacity: .95; } +.fd-meal.drop { box-shadow: inset 0 0 0 2px var(--accent); } +body.fd-dragging, body.fd-dragging * { cursor: grabbing !important; user-select: none; } + +/* the archive (every Open Food Facts product, on the sync server): filters + its own list under the search box */ +.fd-sugg li.fd-sext b { color: var(--cool); } +.fd-arch { margin: 6px 0 2px; } +.fd-ie:not([data-mode="search"]) .fd-arch { display: none; } +.fd-arch-f { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; } +.fd-arch-f select, .fd-arch-f input { background: #262d3b; color: inherit; border: 1px solid #39425a; border-radius: 7px; padding: 5px 8px; font: inherit; font-size: 13px; } +.fd-arch-f input { width: 9em; } +.fd-arch-x { margin-left: auto; background: none; border: 0; color: var(--muted); cursor: pointer; font: inherit; font-size: 12.5px; } +.fd-arch-s { margin: 6px 2px 0; color: var(--muted); font-size: 12.5px; min-height: 1em; } +.fd-arch-s:empty { display: none; } +.fd-arch-l { list-style: none; margin: 4px 0 0; padding: 0; max-height: 360px; overflow-y: auto; } +.fd-arch-l li { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 12px; align-items: baseline; padding: 7px 10px; border-radius: 7px; cursor: pointer; } +.fd-arch-l li:hover, .fd-arch-l li.on { background: #313a4d; } +.fd-arch-l b { font-weight: 400; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.fd-arch-l .fd-sk { text-align: right; white-space: nowrap; font-size: 14px; } +.fd-arch-l .fd-sk i { font-style: normal; color: var(--dim); font-size: 11.5px; } +.fd-arch-l small { color: var(--muted); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; } +.fd-arch-l .fd-ss { display: flex; gap: 4px; justify-content: flex-end; align-items: center; } +.fd-arch-l .fd-ns { padding: 0 5px; font-size: 11px; } +.fd-skind { display: flex; align-items: center; gap: 10px; margin-top: 8px; } +.fd-skind span { color: var(--muted); font-size: 13px; } +.fd-skind select { background: #262d3b; color: inherit; border: 1px solid #39425a; border-radius: 7px; padding: 5px 8px; font: inherit; font-size: 13px; } diff --git a/dashboard/plugins/food/static/food.js b/dashboard/plugins/food/static/food.js new file mode 100644 index 0000000..5da2893 --- /dev/null +++ b/dashboard/plugins/food/static/food.js @@ -0,0 +1,926 @@ +// Food diary pages (/food, /food/history, /food/foods). No browser dialogs. +// +// Logging happens inline (openEditor): a meal's + puts a search box at the end of its card, +// clicking a logged food turns its line into the editor. Its modes (data-mode): +// search just the box: Recent (your entries) · My foods · Food database · Products · "+ New food" +// food a picked food: the portion's numbers as text, amount + unit, Add / Save +// edit "Edit item": its values per 100 g + portions editable — saving copies it into My foods +// (one of yours: changes it); nothing is created before Save +// new a food typed in: its values per 100 g, saved to My foods with the entry +// totals an entry without a food (older ones, estimates): its numbers +// "More": day, meal, note. Enter saves; after an add the box opens again for the next food. +// The server works an entry's numbers out on save (values per 100 g × grams). Popups are left for +// the meal builder, the describe box's check list and the My foods page's food editor. After a +// change the page's .fd is swapped for a fresh server copy (scroll kept). +(function () { + const post = async (url, data) => { + const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw Object.assign(new Error(j.error || `Error ${r.status}`), { field: j.field }); + return j; + }; + const DATA = JSON.parse(document.getElementById("fd-data").textContent); + const NUT = DATA.fields; // kcal, protein, … (db.FIELDS) + const modal = (on) => document.body.classList.toggle("modal", on); // dash.js: keys off + const pad = (n) => String(n).padStart(2, "0"); + const iso = (t) => `${t.getFullYear()}-${pad(t.getMonth() + 1)}-${pad(t.getDate())}`; + const num = (v) => { const x = parseFloat(String(v).replace(",", ".")); return Number.isFinite(x) ? x : null; }; + const fmt = (x) => x == null ? "" : String(Math.round(x * 10) / 10); + const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); + // A product's extras from Open Food Facts (foods.db): Nutri-Score, NOVA group, allergens, + // labels, ingredients — badges with their meaning on hover, the ingredients folded. + const NS_TIP = "Nutri-Score: A (best) … E, per 100 g — energy, sugar, saturated fat and salt against fibre, " + + "protein, fruit / vegetables / nuts. Compares products of one kind; says nothing about how much you eat."; + const NOVA = { 1: "unprocessed or minimally processed", 2: "a cooking ingredient (oil, butter, sugar, salt)", + 3: "processed (cheese, bread, ham, pickles …)", 4: "ultra-processed: an industrial recipe with additives" }; + const nsBadge = (g) => g ? `Nutri-Score ${g.toUpperCase()}` : ""; + function productInfo(f) { + if (!f || f.kind !== "off") return ""; + const parts = [nsBadge(f.nutriscore), + f.nova ? `NOVA ${f.nova}` : "", + f.allergens ? `Contains: ${esc(f.allergens)}` : "", + f.labels ? `${esc(f.labels)}` : ""].filter(Boolean); + return (parts.length ? `
${parts.join("")}
` : "") + + (f.ingredients ? `
Ingredients

${esc(f.ingredients)}

` : ""); + } + function guessMeal(t = new Date()) { // by the clock, for a new entry + const h = t.getHours() + t.getMinutes() / 60; + return h < 10.5 ? "breakfast" : h < 15 ? "lunch" : h < 17.5 ? "snack" : h < 21.5 ? "dinner" : "snack"; + } + + // A search-as-you-type list under an input: load(q) → items (foods: {kind, per100 …}; your + // entries: {kind undefined, kcal, times …}), grouped under headings; ↑↓ Enter Esc, click. + const GROUPS = { recent: "Recent", my: "My foods", usda: "Food database", off: "Products" }; + function suggester(input, ul, { load, pick, open }) { + let items = [], on = -1, timer = null, seq = 0; + const hide = () => { ul.hidden = true; items = []; on = -1; input.setAttribute("aria-expanded", "false"); }; + function draw() { + if (!items.length) return hide(); + let head = ""; + ul.innerHTML = items.map((f, i) => { + if (f.new) return `
  • + New food “${esc(f.name)}”` + + `enter its values per 100 g — saved to My foods
  • `; + if (f.ext) return `
  • ${/^\d{8,14}$/.test(f.name) + ? `Look up barcode ${esc(f.name)} in all products…` : `Search all products for “${esc(f.name)}”…`}` + + `2 million+ from every country — Open Food Facts, through the sync server
  • `; + const g = f.kind || "recent"; + const h = g !== head ? `` : ""; + head = g; + // two lines: name | kcal, then category (small) | scores — a recent entry: its portion | how often + const kcal = f.per100 ? `${Math.round(f.per100.kcal ?? 0)} kcal / 100 g` : `${Math.round(f.kcal || 0)} kcal`; + const cat = f.per100 ? (f.recipe ? "meal" : f.kind === "my" ? "" : f.category || "") + : (f.amount != null ? `${fmt(f.amount)} ${f.unit || ""}` : ""); + const score = f.per100 ? [nsBadge(f.nutriscore), f.nova ? `NOVA ${f.nova}` : ""].join("") + : `${f.times}×`; + return h + `
  • ` + + `${esc(f.name)}${kcal}${esc(cat)}${score}
  • `; + }).join(""); + ul.hidden = false; input.setAttribute("aria-expanded", "true"); + } + async function fetchNow() { + const q = input.value.trim(), n = ++seq; + if (q.length < 2) return hide(); + try { + const got = await load(q); + if (n !== seq || !open()) return; + items = got; on = -1; draw(); + } catch (x) { hide(); } + } + input.addEventListener("input", () => { clearTimeout(timer); timer = setTimeout(fetchNow, 160); }); + input.addEventListener("keydown", (e) => { + if (ul.hidden) return; + if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + on = (on + (e.key === "ArrowDown" ? 1 : -1) + items.length) % items.length; draw(); + } else if (e.key === "Enter" && on >= 0) { e.preventDefault(); const f = items[on]; hide(); pick(f); } + else if (e.key === "Escape") { e.stopPropagation(); hide(); } + }); + input.addEventListener("blur", () => setTimeout(hide, 150)); + ul.addEventListener("mousedown", (e) => { // before the input's blur + e.preventDefault(); + const li = e.target.closest("li[data-i]"); + if (li) { const f = items[Number(li.dataset.i)]; hide(); pick(f); } + }); + return { hide }; + } + + async function refresh() { + const r = await fetch(location.href, { cache: "no-store" }); + const fresh = new DOMParser().parseFromString(await r.text(), "text/html").querySelector(".fd"); + if (fresh) document.querySelector(".fd").replaceWith(fresh); + } + const pageDay = () => document.querySelector(".fd-add")?.dataset.day || iso(new Date()); + + // ---- shared: portions, units, a food's numbers ---------------------------------------------- + const MEAS = /^(cup|oz|fl oz|tablespoon|tbsp|teaspoon|tsp|lb|g|ml|pint|quart|\d)/i; + const LABELS = { fiber: "fibre", sugar: "sugar", sat_fat: "sat. fat", sodium_mg: "sodium" }; + // protein / carbs / fat as coloured dots (the ring's colours; the names on hover) — like the templates' fd.mac + const macDots = (p, c, f) => `${[["protein", p], ["carbs", c], ["fat", f]].map(([k, x]) => + `${x == null ? "—" : fmt(x) + " g"}`).join("")}`; + function portionRow(p = {}, list) { + list.insertAdjacentHTML("beforeend", `
    ` + + `g` + + `
    `); + } + const portionsTyped = (list) => [...list.querySelectorAll(".fd-prow")].map((r) => + ({ label: r.querySelector(".fd-pl").value.trim(), grams: num(r.querySelector(".fd-pg").value) })); + // spoons for every food (ml counted as g) unless it has its own — fooddb.GENERIC on the server + const GENERIC = [["tbsp (15 ml)", 15, /^(tbsp|tablespoon|1 spoon|spoon)/i], ["tsp (5 ml)", 5, /^(tsp|teaspoon)/i]]; + const unitsOf = (ps) => [["g", "g"], ["ml", "ml (as g)"], ...ps.map((p) => [p.label, `${p.label} (${fmt(p.grams)} g)`]), + ...GENERIC.filter(([, , own]) => !ps.some((p) => own.test(p.label) || own.test(p.label.replace(/^serving \(/, "")))).map(([l]) => [l, l])]; + const unitOptions = (list) => list.map(([v, l]) => ``).join(""); + function gramsOf(amount, unit, ps) { + const a = num(amount); + if (a == null) return null; + if (unit === "g" || unit === "ml") return a; + const gen = GENERIC.find(([l]) => l === unit); + if (gen) return a * gen[1]; + const p = ps.find((x) => x.label === unit); + return p ? a * p.grams : null; + } + function macroLine(per100, g) { // "122 kcal · 126 g ●0.9 g ●28.6 g ●0.4 g fibre … · …" + if (g == null || !per100 || per100.kcal == null) return ""; + const v = (x) => x == null ? null : x * g / 100; + const rest = Object.entries(LABELS).filter(([n]) => per100[n] != null) + .map(([n, l]) => `${l} ${fmt(v(per100[n]))}${n === "sodium_mg" ? " mg" : " g"}`).join(" · "); + return `${Math.round(v(per100.kcal))} kcal · ${fmt(g)} g · ${macDots(v(per100.protein), v(per100.carbs), v(per100.fat))}` + + (rest ? ` · ${rest}` : ""); + } + function defaultPortion(f) { // a piece if it has one (large, banana …), else 100 g + if (f.recipe) { // a meal: its first own portion (a bowl …), else all of it + const own = f.portions.find((x) => x.label !== "whole meal"); + return [1, (own || f.portions[0]).label]; + } + const p = f.portions.find((x) => /^(medium|large|piece|whole)/i.test(x.label)) || f.portions.find((x) => !MEAS.test(x.label)); + return p ? [1, p.label] : [100, "g"]; + } + async function getFood(ref) { + const r = await fetch(`/food/api/food?ref=${encodeURIComponent(ref)}`); + if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || "That food is gone."); + return (await r.json()).food; + } + const refOf = (e) => e.my_food_id ? `my:${e.my_food_id}` : e.food_id ? `usda:${e.food_id}` : null; + const arm = (b) => { // Delete: the first click arms it, the second deletes + if (b.classList.contains("armed")) return true; + b.classList.add("armed"); + if (b.querySelector("svg")) b.title = "Click again to delete"; // the trash icon keeps its icon + else b.textContent = "Click again to delete"; + return false; + }; + + // ---- the inline editor: adding to a meal, changing a logged food ---------------------------- + // One at a time (ie). Opened by a meal's + (at the end of its card) or by clicking a logged + // food (in its line). The server works an entry's numbers out on save (values per 100 g × grams). + let ie = null; + function closeEditor() { + if (!ie) return; + ie.el.remove(); + ie.hidden?.forEach((x) => { x.hidden = false; }); + ie = null; + } + function openEditor({ meal, entry, food, amount, unit }) { + closeEditor(); + const sec = document.querySelector(`.fd-meal[data-meal="${entry ? entry.meal : meal}"]`) || document.querySelector(".fd-meal"); + if (!sec) return; + const el = document.getElementById("fd-ie").content.firstElementChild.cloneNode(true); + const q = (c) => el.querySelector(c); + const st = { el, mode: "search", food: null, entry: entry || null, base: null, hidden: [] }; + ie = st; + if (entry) { // in the logged food's line + const li = document.querySelector(`.fd-e[data-id="${entry.id}"]`)?.closest("li"); + const btn = li?.querySelector(".fd-e"); + if (btn) { btn.hidden = true; st.hidden.push(btn); li.appendChild(el); } else sec.appendChild(el); + } else { // at the end of the meal's card + sec.querySelectorAll(".fd-empty").forEach((x) => { x.hidden = true; st.hidden.push(x); }); + sec.appendChild(el); + } + q(".fd-ie-day").value = entry ? entry.day : pageDay(); + q(".fd-ie-meal").value = entry ? entry.meal : sec.dataset.meal || guessMeal(); + q(".fd-ie-note").value = entry ? (entry.note || "") : ""; + q(".fd-ie-ok").textContent = entry ? "Save" : "Add"; + q(".fd-ie-del").hidden = !entry; + st.sg = suggester(q(".fd-ie-in"), q(".fd-sugg"), { + load: async (text) => { + if (st.arch) return []; // the archive's own list is showing + const j = await (await fetch(`/food/api/foods?q=${encodeURIComponent(text)}`)).json(); + return [...(j.recent || []), ...(j.mine || []), ...(j.db || []), ...(j.products || []), + ...(DATA.archive && text.length >= 3 ? [{ ext: true, name: text }] : []), { new: true, name: text }]; + }, + pick: (f) => pick(f), open: () => ie === st, + }); + + // the archive: every Open Food Facts product (/food/api/archive → the sync server), with filters; the search box + // keeps searching it while open, a barcode (8–14 digits) finds that product. A pick is kept (/food/api/product). + const arch = q(".fd-arch"); + let archTimer = null, archSeq = 0; + const archHome = (c) => c.split(" ").filter(Boolean).slice(0, 3).map((x) => x[0].toUpperCase() + x.slice(1).replace(/-/g, " ")) + .join(", ") + (c.split(" ").length > 3 ? " …" : ""); + function archOpen(text) { + st.arch = true; arch.hidden = false; q(".fd-yd").hidden = true; + q(".fd-ie-in").value = text; q(".fd-ie-in").focus(); archRun(); + } + function archClose() { st.arch = false; arch.hidden = true; archSeq++; q(".fd-arch-l").innerHTML = ""; } + async function archRun() { + const text = q(".fd-ie-in").value.trim(), n = ++archSeq, s = q(".fd-arch-s"), ul = q(".fd-arch-l"); + const p = new URLSearchParams({ q: text, country: q(".fd-arch-c").value, brand: q(".fd-arch-b").value.trim(), + nutriscore: q(".fd-arch-n").value }); + if (/^\d{8,14}$/.test(text)) { p.set("barcode", text); p.delete("q"); } + s.textContent = "Searching…"; + try { + const r = await fetch(`/food/api/archive?${p}`), j = await r.json().catch(() => ({})); + if (n !== archSeq) return; + if (!r.ok) throw new Error(j.error || `Error ${r.status}`); + st.archItems = j.items; + s.textContent = j.items.length ? "" : text.length < 3 && !p.get("brand") && !p.get("country") ? "Type at least 3 letters, or pick a filter." : "Nothing found."; + ul.innerHTML = j.items.map((f, i) => `
  • ${esc(f.name)}` + + `${Math.round(f.per100.kcal ?? 0)} kcal / 100 g` + + `${esc([f.brand, archHome(f.countries || "")].filter(Boolean).join(" · "))}${f.saved ? " · ✓ you have it" : ""}` + + `${nsBadge(f.nutriscore)}
  • `).join(""); + } catch (x) { if (n === archSeq) { s.textContent = x.message; ul.innerHTML = ""; } } + } + q(".fd-ie-in").addEventListener("input", () => { if (st.arch) { clearTimeout(archTimer); archTimer = setTimeout(archRun, 300); } }); + q(".fd-ie-in").addEventListener("keydown", (e) => { if (st.arch && e.key === "Enter") { e.preventDefault(); clearTimeout(archTimer); archRun(); } }); + for (const c of [".fd-arch-c", ".fd-arch-n"]) q(c).addEventListener("change", archRun); + q(".fd-arch-b").addEventListener("input", () => { clearTimeout(archTimer); archTimer = setTimeout(archRun, 300); }); + q(".fd-arch-x").addEventListener("click", () => { archClose(); q(".fd-ie-in").focus(); }); + q(".fd-arch-l").addEventListener("click", async (e) => { + const li = e.target.closest("li[data-i]"); + if (!li) return; + const f = st.archItems[Number(li.dataset.i)]; + q(".fd-arch-s").textContent = "Keeping it…"; + try { + const j = await post("/food/api/product", { id: f.id, barcode: f.barcode }); + archClose(); useFood(j.food); + } catch (x) { q(".fd-arch-s").textContent = x.message; } + }); + if (entry && refOf(entry)) { // made from a food: that food, this portion + q(".fd-ie-name").textContent = entry.name; + q(".fd-ie-a").value = fmt(entry.amount); // shown at once; the food's numbers follow + q(".fd-ie-u").innerHTML = unitOptions([[entry.unit || "g", entry.unit || "g"]]); + el.dataset.mode = "food"; + getFood(refOf(entry)).then((f) => { if (ie === st) useFood(f, entry.amount, entry.unit); }) + .catch(() => { if (ie === st) useTotals(entry); }); + } else if (entry) useTotals(entry); + else if (food) useFood(food, amount, unit); + else { setMode("search"); yesterday(); q(".fd-ie-in").focus(); } + el.scrollIntoView({ block: "nearest" }); + + // under an empty search box: yesterday's foods (the page's day before), this meal's first and + // the other meals folded; + adds one as it was (same food, same portion), a click on the + // name picks it to change the portion first. Ones already in this meal show a ✓. + function yesterday() { + const box = q(".fd-yd"), m = q(".fd-ie-meal").value; + const all = JSON.parse(document.getElementById("fd-yday")?.textContent || "[]"); + if (!all.length) return; + const here = [...sec.querySelectorAll(".fd-e[data-entry]")].map((b) => JSON.parse(b.dataset.entry)); + const done = (e) => here.some((x) => x.name === e.name && x.amount === e.amount && x.unit === e.unit); + const row = (e) => `
    ` + + `` + + `
    `; + const mine = all.filter((e) => e.meal === m), rest = all.filter((e) => e.meal !== m); + const label = (DATA.meals[m] || "").toLowerCase(); + box.innerHTML = (mine.length ? `
    Yesterday's ${esc(label)}
    ${mine.map(row).join("")}` : "") + + (rest.length ? `
    ${mine.length ? "Rest of yesterday" : "Yesterday"} (${rest.length})${rest.map(row).join("")}
    ` : ""); + box.hidden = false; + box.onclick = async (e) => { + const r = e.target.closest(".fd-ydr"); + if (!r) return; + const y = all.find((x) => String(x.id) === r.dataset.id); + if (e.target.closest(".fd-ydp")) return pick(Object.assign({}, y, { food: refOf(y) })); + const b = e.target.closest(".fd-ydadd"); + if (!b || b.disabled) return; + const d = { day: pageDay(), meal: q(".fd-ie-meal").value, amount: y.amount, unit: y.unit, note: "" }; + if (refOf(y)) d.food = refOf(y); // the server works the numbers out again + else { d.name = y.name; d.from = y.id; NUT.forEach((k) => { if (y[k] != null) d[k] = y[k]; }); } + b.disabled = true; + try { + await post("/food/api/entry", d); + closeEditor(); + await refresh(); + openEditor({ meal: d.meal }); // the list again, this one ✓ + } catch (x) { // the editor's own error line is hidden while searching + b.disabled = false; + box.querySelector(".fd-yderr")?.remove(); + box.insertAdjacentHTML("beforeend", ``); + } + }; + } + + function setMode(m) { + st.mode = m; + el.dataset.mode = m; + const f = st.food; + q(".fd-ie-src").textContent = m === "new" ? "new food — saved to My foods" : m === "totals" ? "" : !f ? "" + : f.kind === "my" ? (f.recipe ? "meal" : "My foods") : f.kind === "off" ? [f.brand, f.barcode].filter(Boolean).join(" · ") || "product" + : "food database"; + q(".fd-ie-edit").textContent = m === "edit" ? "Undo changes" : f?.recipe ? "Edit meal" : "Edit item"; + q(".fd-ie-edit").hidden = !(m === "food" || m === "edit"); + q(".fd-copy").textContent = m !== "edit" ? "" : f.kind === "my" + ? `Saving changes “${f.name}” in My foods (past entries keep their numbers).` + : `Saving adds a copy to My foods — rename it if you like; “${f.name}” stays as it is.`; + const info = q(".fd-pinfo"); + info.innerHTML = m === "food" || m === "edit" ? productInfo(f) : ""; + info.hidden = !info.innerHTML; + units(); + show(); + } + function portionsNow() { return st.mode === "food" ? st.food.portions : portionsTyped(q(".fd-plist")).filter((p) => p.label && p.grams); } + function per100Now() { + if (st.mode === "food") return st.food.per100; + const o = {}; + el.querySelectorAll("[data-k]").forEach((i) => { o[i.dataset.k] = num(i.value); }); + return o; + } + function units(value) { // g, ml + the food's portions; totals: the usual units + const sel = q(".fd-ie-u"), v = value ?? sel.value; + const list = st.mode === "totals" ? [["", "unit"], ...DATA.units.map((u) => [u, u])] : unitsOf(portionsNow()); + sel.innerHTML = unitOptions(list); + sel.value = v || (st.mode === "totals" ? "" : "g"); + if (v && sel.value !== v) { sel.insertAdjacentHTML("beforeend", ``); sel.value = v; } + } + function show() { // the portion's numbers, as text + if (st.mode === "search" || st.mode === "totals") { q(".fd-ie-mac").innerHTML = ""; return; } + const g = gramsOf(q(".fd-ie-a").value, q(".fd-ie-u").value, portionsNow()); + q(".fd-ie-mac").innerHTML = macroLine(per100Now(), g) || `${g == null ? "amount + unit" : "its energy per 100 g below"}`; + } + function fillPer(f) { + el.querySelectorAll("[data-k]").forEach((i) => { i.value = fmt(f ? f.per100[i.dataset.k] : null); }); + q(".fd-plist").innerHTML = ""; + (f ? f.portions : []).forEach((p) => portionRow(p, q(".fd-plist"))); + } + function useFood(f, a, u) { // a picked food: its numbers as text + st.food = f; st.base = null; + q(".fd-ie-name").textContent = f.name; + q(".fd-ie-nm").value = f.name; + fillPer(f); + if (a == null) [a, u] = defaultPortion(f); + q(".fd-ie-a").value = fmt(a); + setMode("food"); + units(u); + show(); + q(".fd-ie-a").focus(); q(".fd-ie-a").select(); + } + function useTotals(e, from) { // an entry without a food (old ones, estimates) + st.food = null; st.base = e; + q(".fd-ie-name").textContent = e.name; + q(".fd-ie-nm").value = e.name; + el.querySelectorAll("[data-t]").forEach((i) => { i.value = fmt(e[i.dataset.t]); }); + q(".fd-ie-a").value = fmt(e.amount); + st.from = from ? e.id : null; + setMode("totals"); + units(e.unit || ""); + q(".fd-ie-a").focus(); + } + function startNew(name) { // a food typed in: values per 100 g + st.food = null; st.base = null; + q(".fd-ie-nm").value = name; + fillPer(null); + portionRow({}, q(".fd-plist")); + q(".fd-ie-a").value = "100"; + setMode("new"); + el.querySelector('[data-k="kcal"]').focus(); + } + async function pick(f) { + if (f.new) return startNew(f.name); + if (f.ext) return archOpen(f.name); + if (f.per100) return useFood(f); + if (f.food) { // a recent entry made from a food + try { useFood(await getFood(f.food), f.amount, f.unit); } catch (x) { err(x.message); } + } else useTotals(f, true); // a recent entry without one: its numbers + } + function err(m, field) { + q(".fd-ie-err").textContent = m || ""; + el.querySelectorAll(".bad").forEach((x) => x.classList.remove("bad")); + const f = String(field || "").replace(/^food\./, ""); + const pm = /^portion\.(\d+)$/.exec(f); + const t = pm ? el.querySelectorAll(".fd-prow")[Number(pm[1])] : f === "name" ? (st.mode === "food" ? q(".fd-ie-in") : q(".fd-ie-nm")) + : f === "amount" || f === "unit" ? q(".fd-ie-a") : f === "day" ? q(".fd-ie-day") : el.querySelector(`[data-k="${f}"], [data-t="${f}"]`); + if (t) { t.classList.add("bad"); if (t.closest(".fd-ie-extra")) el.classList.add("more"); t.focus?.(); } + } + async function save() { + const d = { meal: q(".fd-ie-meal").value, day: q(".fd-ie-day").value, amount: q(".fd-ie-a").value, + unit: q(".fd-ie-u").value, note: q(".fd-ie-note").value }; + if (st.entry) d.id = st.entry.id; + const foodData = () => { + const per100 = {}; + el.querySelectorAll("[data-k]").forEach((i) => { per100[i.dataset.k] = i.value; }); + return { name: q(".fd-ie-nm").value, per100, portions: portionsTyped(q(".fd-plist")), note: st.food?.note || "" }; + }; + if (st.mode === "search") return err("Pick a food first.", "name"); + if (st.mode === "food") d.food = st.food.ref; + else if (st.mode === "edit") { d.food = st.food.ref; d.edit = foodData(); } + else if (st.mode === "new") d.edit = foodData(); + else { // totals: the numbers typed; the rest as they were + d.name = q(".fd-ie-nm").value; + NUT.forEach((k) => { if (st.base && st.base[k] != null) d[k] = st.base[k]; }); + el.querySelectorAll("[data-t]").forEach((i) => { d[i.dataset.t] = i.value; }); + if (st.from) d.from = st.from; + } + const ok = q(".fd-ie-ok"); + ok.disabled = true; + try { + await post("/food/api/entry", d); + const again = !st.entry && d.day === pageDay() && location.pathname === "/food" ? d.meal : null; + closeEditor(); + if (d.day !== pageDay() && location.pathname === "/food") return void (location.href = `/food?d=${d.day}`); + await refresh(); + if (again) openEditor({ meal: again }); // the next food for the same meal + } catch (x) { err(x.message, x.field); ok.disabled = false; } + } + function back() { // the name clicked: search again (from it) + const inp = q(".fd-ie-in"); + inp.value = q(".fd-ie-name").textContent; + st.food = null; setMode("search"); + inp.focus(); inp.select(); + inp.dispatchEvent(new Event("input")); + } + el.addEventListener("click", async (e) => { + const b = e.target.closest("button, .fd-ie-name"); + if (!b) return; + if (b.classList.contains("fd-ie-x")) closeEditor(); + else if (b.classList.contains("fd-ie-name")) back(); + else if (b.classList.contains("fd-ie-ok")) save(); + else if (b.classList.contains("fd-ie-more")) el.classList.toggle("more"); + else if (b.classList.contains("fd-ie-edit")) { + const a = num(q(".fd-ie-a").value), u = q(".fd-ie-u").value; + if (st.mode === "edit") useFood(st.food, a, u); // undo + else if (st.food.recipe) openMeal(st.food.ref, async (ref) => { if (ie === st) useFood(await getFood(ref), a, u); }); + else { setMode("edit"); el.querySelector('[data-k="kcal"]').focus(); } + } else if (b.classList.contains("fd-padd")) { portionRow({}, q(".fd-plist")); q(".fd-plist").lastElementChild.querySelector("input").focus(); } + else if (b.classList.contains("fd-prm")) { b.closest(".fd-prow").remove(); units(); show(); } + else if (b.classList.contains("fd-ie-del") && arm(b)) { + try { await post("/food/api/entry/delete", { id: st.entry.id }); closeEditor(); await refresh(); } catch (x) { err(x.message); } + } + }); + el.addEventListener("input", (e) => { + if (e.target.closest(".fd-prow")) units(); + if (e.target.classList.contains("fd-ie-in") && st.mode !== "search") { st.food = null; setMode("search"); } + if (e.target.classList.contains("fd-ie-in") && q(".fd-yd").innerHTML) q(".fd-yd").hidden = !!e.target.value.trim(); + if (e.target.classList.contains("fd-ie-a") && st.mode === "totals" && st.base && st.from) { // a recent one: scale with it + const x = num(e.target.value) / st.base.amount; + if (st.base.amount && Number.isFinite(x)) el.querySelectorAll("[data-t]").forEach((i) => { + const v = st.base[i.dataset.t]; i.value = v == null ? "" : fmt(v * x); }); + } + show(); + }); + el.addEventListener("change", (e) => { if (e.target.classList.contains("fd-ie-u")) show(); }); + el.addEventListener("keydown", (e) => { + if (e.key === "Enter" && !e.target.closest(".fd-ie-q") && e.target.tagName !== "BUTTON") { e.preventDefault(); save(); } + if (e.key === "Escape" && !e.defaultPrevented) { e.stopPropagation(); closeEditor(); } + }); + } + + // ---- one of My foods (the My foods page): a small dialog ------------------------------------- + const box = document.getElementById("fd-form"); + const form = box.querySelector("form"); + const F = form.elements; + const plist = box.querySelector(".fd-plist"); + let onSaved = null; + function openFood(f, after) { // f null = a new one + form.reset(); ferr(""); + onSaved = after || null; + F.id.value = f ? f.id : ""; + F.name.value = f ? f.name : ""; + NUT.forEach((k) => { F[k].value = fmt(f ? f.per100[k] : null); }); + plist.innerHTML = ""; + (f ? f.portions : [{}]).forEach((p) => portionRow(p, plist)); + F.note.value = f ? (f.note || "") : ""; + F.sugar_kind.value = f ? (f.sugar_kind || "") : ""; + box.querySelector(".fd-ftitle").textContent = f ? "Edit food" : "New food"; + const del = box.querySelector(".fd-del"); + del.hidden = !f; del.classList.remove("armed"); del.textContent = "Delete"; + box.hidden = false; modal(true); + F.name.focus(); + } + const ferr = (m, field) => { + box.querySelector(".fd-ferr").textContent = m || ""; + form.querySelectorAll(".bad").forEach((e) => e.classList.remove("bad")); + const f = String(field || "").replace(/^food\./, ""), pm = /^portion\.(\d+)$/.exec(f); + const el = pm ? plist.querySelectorAll(".fd-prow")[Number(pm[1])] : F[f]; + if (el && el.classList) { el.classList.add("bad"); el.focus?.(); } + }; + const anyOpen = () => [box, check, mbox].some((x) => !x.hidden); + const close = () => { box.hidden = true; modal(anyOpen()); }; + box.addEventListener("click", async (e) => { + if (e.target.closest(".ec-x") || e.target.classList.contains("ec-back")) return close(); + const b = e.target.closest("button"); + if (!b) return; + if (b.classList.contains("fd-padd")) { portionRow({}, plist); plist.lastElementChild.querySelector("input").focus(); } + else if (b.classList.contains("fd-prm")) b.closest(".fd-prow").remove(); + else if (b.classList.contains("fd-del") && arm(b)) { + try { await post("/food/api/myfood/delete", { id: F.id.value }); close(); onSaved?.(); } catch (x) { ferr(x.message); } + } + }); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + const s = form.querySelector(".fd-save"); + s.disabled = true; + try { + const per100 = {}; + NUT.forEach((k) => { per100[k] = F[k].value; }); + await post("/food/api/myfood", { id: F.id.value || null, name: F.name.value, per100, portions: portionsTyped(plist), note: F.note.value, + sugar_kind: F.sugar_kind.value }); + close(); onSaved?.(); + } catch (x) { ferr(x.message, x.field); } + finally { s.disabled = false; } + }); + + // ---- the meal builder ------------------------------------------------------------------------ + // A meal = one of My foods made of others: ingredients (a food + amount + unit each), its weight + // when done (empty = the ingredients' sum), portions. The server works its values per 100 g out + // (/food/api/meal); "Save & log a portion" then opens the add dialog with it. + const mbox = document.getElementById("fd-meal"); + const mform = mbox.querySelector("form"); + const M = mform.elements; + const ilist = mbox.querySelector(".fd-ilist"); + const mplist = mbox.querySelector(".fd-mplist"); + let ings = [], mAfter = null, mId = null, mFrom = null; // ings: [{f (the food, null = gone), name, amount, unit} + // or {fixed: its numbers as logged, name, amount, unit, grams}]; mFrom: the day's entries it's made of + function ingGrams(r) { + if (r.fixed) return r.grams || null; + return r.f ? gramsOf(r.amount, r.unit, r.f.portions) : null; + } + function drawIngs() { + ilist.innerHTML = ings.map((r, i) => `
    ${esc(r.f ? r.f.name : r.name)}` + + `${r.fixed ? "as logged" : !r.f ? "gone — remove it" : r.f.recipe ? "meal" : r.f.kind === "my" ? "My foods" : r.f.kind === "off" ? "product" : "food database"}` + + (r.fixed ? `${r.amount != null ? esc(fmt(r.amount) + " " + (r.unit || "")) : ""}${r.grams && r.unit !== "g" ? ` (${fmt(r.grams)} g)` : ""}${r.grams ? "" : " no weight"}` + : `` + + ``) + + `
    `).join(""); + ilist.querySelectorAll(".fd-ing").forEach((row, i) => { const u = row.querySelector(".fd-iu"); if (u) u.value = ings[i].unit; }); + mtotals(); + } + function mtotals() { // per row, all together, per 100 g + const tot = {}, keys = ["kcal", "protein", "carbs", "fat"]; + let grams = 0; + let unweighed = 0; + ings.forEach((r, i) => { + const g = ingGrams(r), row = ilist.querySelectorAll(".fd-ing")[i]; + const val = (n) => r.fixed ? r.fixed[n] : g != null && r.f.per100[n] != null ? r.f.per100[n] * g / 100 : null; + const k = val("kcal"); + if (row) row.querySelector(".fd-ik").textContent = k == null ? "—" : `${Math.round(k)} kcal`; + if (g != null) grams += g; else if (r.fixed) unweighed++; + if (g == null && !r.fixed) return; + keys.forEach((n) => { const v = val(n); if (v != null) tot[n] = (tot[n] || 0) + v; }); + }); + const t = mbox.querySelector(".fd-mtot"); + t.querySelector(".fd-thk").textContent = ings.length ? `${Math.round(tot.kcal || 0)} kcal` : "—"; + t.querySelector(".fd-thm").innerHTML = ings.length + ? `${fmt(grams)} g of ingredients ${macDots(tot.protein || 0, tot.carbs || 0, tot.fat || 0)}` : "add what goes into it"; + M.done_grams.placeholder = unweighed ? "needed — some have no weight" : grams ? `${fmt(grams)} (the ingredients)` : ""; + const w = num(M.done_grams.value) || grams; + mbox.querySelector(".fd-mper").innerHTML = w && ings.length + ? `Per 100 g: ${Math.round((tot.kcal || 0) * 100 / w)} kcal ${macDots((tot.protein || 0) * 100 / w, (tot.carbs || 0) * 100 / w, (tot.fat || 0) * 100 / w)}` : ""; + } + const merr = (m, field) => { + mbox.querySelector(".fd-ferr").textContent = m || ""; + mform.querySelectorAll(".bad").forEach((e) => e.classList.remove("bad")); + const f = String(field || ""), im = /^ing\.(\d+)$/.exec(f), pm = /^portion\.(\d+)$/.exec(f); + const el = im ? ilist.querySelectorAll(".fd-ing")[Number(im[1])] : pm ? mplist.querySelectorAll(".fd-prow")[Number(pm[1])] + : f === "ingredients" ? M.q : M[f]; + if (el && el.classList) { el.classList.add("bad"); (el.querySelector?.("input") || el).focus?.(); } + }; + async function openMeal(ref, after, from) { // ref null = a new meal; after(ref): instead of refreshing; + mform.reset(); merr(""); msg.hide(); // from: entries of the day it's made of + mAfter = after || null; ings = []; mId = null; mplist.innerHTML = ""; mFrom = from || null; + const repl = mbox.querySelector(".fd-repl"); + repl.hidden = !from; + logLabel(); + if (from) { + repl.querySelector(".fd-repn").textContent = from.length; + ings = await Promise.all(from.map(async (e) => { // a food's entry → that food + its portion; else as logged + const ref = e.my_food_id ? `my:${e.my_food_id}` : e.food_id ? `usda:${e.food_id}` : null; + if (ref) { try { return { f: await getFood(ref), name: e.name, amount: e.amount, unit: e.unit }; } catch (x) { /* gone */ } } + const fixed = {}; + ["kcal", "protein", "carbs", "sugar", "fiber", "fat", "sat_fat", "mono_fat", "poly_fat", "trans_fat", + "sodium_mg", "cholesterol_mg", "potassium_mg"].forEach((k) => { fixed[k] = e[k]; }); + return { fixed, name: e.name, amount: e.amount, unit: e.unit, grams: e.grams || (e.unit === "g" || e.unit === "ml" ? e.amount : null) }; + })); + } + let f = null; + if (ref) { + try { f = await getFood(ref); } catch (x) { return; } + mId = f.id; + M.name.value = f.name; + ings = f.recipe.ingredients.map((i) => i.fixed ? { fixed: i.fixed, name: i.name, amount: i.amount, unit: i.unit, grams: i.grams } + : { f: i.f, name: i.name, amount: i.amount, unit: i.unit }); + M.done_grams.value = fmt(f.recipe.done_grams); + f.portions.filter((p) => p.label !== "whole meal").forEach((p) => portionRow(p, mplist)); + M.note.value = f.note || ""; + } + mbox.querySelector(".fd-ftitle").textContent = f ? "Edit meal" : "Make a meal"; + const del = mbox.querySelector(".fd-del"); + del.hidden = !f; del.classList.remove("armed"); del.textContent = "Delete"; + drawIngs(); + mbox.hidden = false; modal(true); + (f ? M.q : M.name).focus(); + } + function logLabel() { // with the picked entries replaced, the meal is logged already + const replacing = mFrom && M.replace.checked; + mbox.querySelector(".fd-mlog").textContent = replacing ? "Save & say how much I ate" : "Save & log a portion"; + } + M.replace.addEventListener("change", logLabel); + const closeMeal = () => { mbox.hidden = true; msg.hide(); modal(anyOpen()); }; + function logFor(es) { // the one entry replacing them: their day, most common meal, first time + const count = {}; + es.forEach((e) => { count[e.meal] = (count[e.meal] || 0) + 1; }); + const meal = Object.keys(count).sort((a, b) => count[b] - count[a])[0] || guessMeal(); + const times = es.map((e) => e.time).filter(Boolean).sort(); + return { day: es[0].day, meal, time: times[0] || "" }; + } + + // picking the day's entries for a meal ("Make a meal" on the day page) + const pickbar = () => document.querySelector(".fd-pickbar"); + const picking = () => document.querySelector(".fd")?.classList.contains("picking"); + function pickMode(on) { + const fd = document.querySelector(".fd"), bar = pickbar(); + fd.classList.toggle("picking", on); + bar.hidden = !on; + if (!on) fd.querySelectorAll(".fd-e.sel").forEach((x) => { x.classList.remove("sel"); x.setAttribute("aria-pressed", "false"); }); + pickCount(); + } + function pickCount() { + const n = document.querySelectorAll(".fd-e.sel").length, bar = pickbar(); + bar.querySelector(".fd-pickn").textContent = n ? `· ${n} picked` : ""; + bar.querySelector(".fd-pnext").disabled = !n; + } + const msg = suggester(M.q, mbox.querySelector(".fd-sugg"), { + load: async (q) => { + const j = await (await fetch(`/food/api/foods?q=${encodeURIComponent(q)}`)).json(); + return [...(j.mine || []), ...(j.db || []), ...(j.products || [])].filter((f) => !(f.kind === "my" && f.id === mId)); + }, + pick: (f) => { + const [a, u] = defaultPortion(f); + ings.push({ f, name: f.name, amount: a, unit: u }); + M.q.value = ""; + drawIngs(); + const last = ilist.lastElementChild?.querySelector(".fd-ia"); + if (last) { last.focus(); last.select(); } + }, + open: () => !mbox.hidden, + }); + ilist.addEventListener("input", (e) => { + const row = e.target.closest(".fd-ing"); + if (!row) return; + const r = ings[Number(row.dataset.i)]; + if (e.target.classList.contains("fd-ia")) r.amount = num(e.target.value); + if (e.target.classList.contains("fd-iu")) r.unit = e.target.value; + mtotals(); + }); + ilist.addEventListener("change", (e) => { + const row = e.target.closest(".fd-ing"); + if (row && e.target.classList.contains("fd-iu")) { ings[Number(row.dataset.i)].unit = e.target.value; mtotals(); } + }); + M.done_grams.addEventListener("input", mtotals); + mbox.addEventListener("click", async (e) => { + if (e.target.closest(".ec-x") || e.target.classList.contains("ec-back")) return closeMeal(); + const b = e.target.closest("button"); + if (!b) return; + if (b.classList.contains("fd-prm") && b.closest(".fd-ing")) { ings.splice(Number(b.closest(".fd-ing").dataset.i), 1); drawIngs(); } + else if (b.classList.contains("fd-prm")) b.closest(".fd-prow").remove(); + else if (b.classList.contains("fd-padd")) { portionRow({}, mplist); mplist.lastElementChild.querySelector("input").focus(); } + else if (b.classList.contains("fd-mlog")) saveMeal(true); + else if (b.classList.contains("fd-del")) { + if (!b.classList.contains("armed")) { b.classList.add("armed"); b.textContent = "Click again to delete"; return; } + try { await post("/food/api/myfood/delete", { id: mId }); closeMeal(); await refresh(); } catch (x) { merr(x.message); } + } + }); + mform.addEventListener("submit", (e) => { e.preventDefault(); saveMeal(false); }); + async function saveMeal(log) { + const btns = mform.querySelectorAll(".fd-save, .fd-mlog"); + btns.forEach((x) => { x.disabled = true; }); + try { + const j = await post("/food/api/meal", { + id: mId, name: M.name.value, done_grams: M.done_grams.value, note: M.note.value, portions: portionsTyped(mplist), + ingredients: ings.map((r) => r.fixed ? { fixed: r.fixed, name: r.name, amount: r.amount, unit: r.unit, grams: r.grams } + : { food: r.f ? r.f.ref : null, amount: r.amount, unit: r.unit }), + ...(mFrom && M.replace.checked ? { replace: mFrom.map((e) => e.id), log: logFor(mFrom) } : {}), + }); + closeMeal(); + if (log && j.entry) { // made of the day's entries: that one entry, to say how much + await refresh(); + const el = document.querySelector(`.fd-e[data-id="${j.entry}"]`); + if (el) openEditor({ entry: JSON.parse(el.dataset.entry) }); + } else if (log && !document.querySelector(".fd-meals")) location.href = `/food#add=${j.ref}`; + else if (log) { // the inline editor with the meal picked + await refresh(); + openEditor({ meal: guessMeal(), food: await getFood(j.ref) }); + } else if (mAfter) await mAfter(j.ref); + else await refresh(); + } catch (x) { merr(x.message, x.field); } + finally { btns.forEach((x) => { x.disabled = false; }); } + } + + // ---- describe → check → save all ---------------------------------------------------------- + const check = document.getElementById("fd-check"); + const cform = check.querySelector("form"); + const tpl = document.getElementById("fd-item"); + const items = check.querySelector(".fd-items"); + const cerr = (m) => { check.querySelector(".fd-ferr").textContent = m || ""; }; + function total() { + let k = 0; + items.querySelectorAll(".fd-item:not(.gone)").forEach((it) => { k += num(it.querySelector("[name=kcal]").value) || 0; }); + check.querySelector(".fd-ctotal").textContent = `${Math.round(k)} kcal together`; + } + function itemCompute(n) { // a row matched to a food: its numbers for the portion + const it = JSON.parse(n.dataset.item), f = it.food, q = (k) => n.querySelector(`[name=${k}]`); + if (!f) return; + const g = gramsOf(q("amount").value, q("unit").value, f.portions); + ["kcal", "protein", "carbs", "fat"].forEach((k) => { q(k).value = g == null || f.per100[k] == null ? "" : fmt(f.per100[k] * g / 100); }); + } + function openCheck(text, list) { + items.innerHTML = ""; cerr(""); + check.querySelector(".fd-said").textContent = `“${text}”`; + cform.elements.day.value = pageDay(); + const fallback = guessMeal(); + list.forEach((it) => { + const n = tpl.content.firstElementChild.cloneNode(true); + const q = (k) => n.querySelector(`[name=${k}]`); + q("name").value = it.name; q("amount").value = fmt(it.amount); + if (it.food) { // g, ml + the food's portions; numbers locked + q("unit").innerHTML = unitOptions(unitsOf(it.food.portions)); + ["kcal", "protein", "carbs", "fat"].forEach((k) => { q(k).readOnly = true; }); + n.classList.add("linked"); + } + q("unit").value = it.unit || ""; + q("meal").value = it.meal || fallback; + ["kcal", "protein", "carbs", "fat"].forEach((k) => { q(k).value = fmt(it[k]); }); + const b = n.querySelector(".fd-basis"); + b.textContent = { history: "your usual", database: "database", "my food": "my food", estimate: "estimate" }[it.basis] || it.basis; + b.classList.add(it.basis.replace(" ", "-")); + b.title = it.basis === "history" ? "Numbers from the last time you logged this food, scaled to the portion" + : it.food ? `${it.basis === "my food" ? "My foods" : "Food database"}: ${it.food_name} (${fmt(it.grams)} g)` : "The model's guess — check the numbers"; + n.dataset.item = JSON.stringify(it); + items.appendChild(n); + }); + total(); + check.hidden = false; modal(true); + items.querySelector("input")?.focus(); + } + const closeCheck = () => { check.hidden = true; modal(anyOpen()); }; + check.addEventListener("click", (e) => { + if (e.target.closest(".ec-x") || e.target.classList.contains("ec-back")) return closeCheck(); + const rm = e.target.closest(".fd-rm"); + if (rm) { rm.closest(".fd-item").classList.add("gone"); total(); } + }); + const onItem = (e) => { + const it = e.target.closest(".fd-item"); + if (!it) return; + const was = JSON.parse(it.dataset.item); + if (was.food && e.target.name === "name" && e.target.value !== was.name) { // renamed: not that food any more + it.classList.remove("linked"); + ["kcal", "protein", "carbs", "fat"].forEach((k) => { it.querySelector(`[name=${k}]`).readOnly = false; }); + it.dataset.item = JSON.stringify({ ...was, food: null, basis: "estimate" }); + it.querySelector(".fd-basis").textContent = "typed"; + } else if (was.food && (e.target.name === "amount" || e.target.name === "unit")) itemCompute(it); + else if (e.target.name === "amount") { // scale the numbers with the portion + const a = num(e.target.value); + if (was.amount && a) ["kcal", "protein", "carbs", "fat"].forEach((k) => { + if (was[k] != null) it.querySelector(`[name=${k}]`).value = fmt(was[k] * a / was.amount); + }); + } + total(); + }; + check.addEventListener("input", onItem); + check.addEventListener("change", onItem); + cform.addEventListener("submit", async (e) => { + e.preventDefault(); + const day = cform.elements.day.value; + const live = [...items.querySelectorAll(".fd-item:not(.gone)")]; + if (!live.length) return cerr("Nothing left to save."); + const list = live.map((it) => { + const was = JSON.parse(it.dataset.item), q = (k) => it.querySelector(`[name=${k}]`).value; + const d = { day, amount: q("amount"), unit: q("unit"), meal: q("meal") }; + if (was.food) return { ...d, food: was.food.ref }; // the server works the numbers out + Object.assign(d, { name: q("name"), kcal: q("kcal"), protein: q("protein"), carbs: q("carbs"), fat: q("fat") }); + if (was.from && d.name === was.name) d.from = was.from; // keeps that food's other nutrients + ["sugar", "fiber", "sat_fat", "sodium_mg"].forEach((k) => { // from history, scaled like kcal + if (was[k] != null && was.kcal) d[k] = was[k] * (num(d.kcal) || 0) / was.kcal; + }); + return d; + }); + const s = cform.querySelector(".fd-save"); + s.disabled = true; + try { + await post("/food/api/entries", { items: list }); + closeCheck(); + document.querySelector(".fd-sayf textarea").value = ""; + if (day !== pageDay() && location.pathname === "/food") location.href = `/food?d=${day}`; + else await refresh(); + } catch (x) { + const m = /^(\d+)\.(\w+)$/.exec(x.field || ""); + cerr(x.message); + if (m) live[Number(m[1])]?.querySelector(`[name=${m[2]}]`)?.focus(); + } finally { s.disabled = false; } + }); + + // ---- the page ------------------------------------------------------------------------------- + document.addEventListener("click", (e) => { + if (anyOpen()) return; + const t = e.target.closest(".fd-e, .fd-plus, .fd-empty, .fd-add, .fd-fr, .fd-fnew, .fd-mk, .fd-pnext, .fd-pscratch, .fd-pcancel"); + if (!t) return; + if (picking()) { // picking the day's entries for a meal + if (t.classList.contains("fd-e")) { + const on = t.classList.toggle("sel"); + t.setAttribute("aria-pressed", on ? "true" : "false"); + return pickCount(); + } + if (t.classList.contains("fd-pnext")) { + const es = [...document.querySelectorAll(".fd-e.sel")].map((x) => JSON.parse(x.dataset.entry)); + pickMode(false); + return openMeal(null, null, es); + } + if (t.classList.contains("fd-pscratch")) { pickMode(false); return openMeal(null); } + if (t.classList.contains("fd-pcancel") || t.classList.contains("fd-mk")) return pickMode(false); + return; // the rest waits + } + if (t.classList.contains("fd-mk")) { // on a day with entries: pick from them first + if (pickbar() && document.querySelector(".fd-e")) return pickMode(true); + return openMeal(null); + } + if (t.classList.contains("fd-fr")) { + const f = JSON.parse(t.dataset.food); + return f.recipe ? openMeal(f.ref) : openFood(f, refresh); + } + if (t.classList.contains("fd-fnew")) return openFood(null, refresh); + if (t.classList.contains("fd-e")) return openEditor({ entry: JSON.parse(t.dataset.entry) }); + if (!document.querySelector(".fd-meals")) return void (location.href = "/food#add"); // History / My foods: today's diary + openEditor({ meal: t.dataset.meal || guessMeal() }); + }); + document.addEventListener("submit", async (e) => { + const f = e.target.closest(".fd-sayf"); + if (!f) return; + e.preventDefault(); + const text = f.elements.text.value.trim(), go = f.querySelector(".fd-go"), err = f.querySelector(".fd-err"); + err.textContent = ""; + if (!text) { err.textContent = "Write what you ate first."; return f.elements.text.focus(); } + go.disabled = true; go.classList.add("busy"); go.textContent = "Reading…"; + try { openCheck(text, (await post("/food/api/parse", { text })).items); } + catch (x) { err.textContent = x.message; } + finally { go.disabled = false; go.classList.remove("busy"); go.textContent = "Read it"; } + }); + document.addEventListener("keydown", (e) => { + if (e.key === "Escape") { if (!mbox.hidden) closeMeal(); else if (!box.hidden) close(); else if (!check.hidden) closeCheck(); else if (picking()) pickMode(false); else closeEditor(); } + if (e.key === "Enter" && e.target.classList?.contains("fd-fr") && box.hidden) e.target.click(); // My foods rows + const t = e.target; // Ctrl+Enter in the describe box sends it + if (e.key === "Enter" && (e.ctrlKey || e.metaKey) && t.closest?.(".fd-sayf")) t.form.requestSubmit(); + }); + + // ---- dragging a logged food into another meal: grab its ⠿ (mouse or touch), drop on a meal card. + // Only the meal changes (/food/api/entry/move); Esc cancels. The page scrolls near its edges. + let drag = null; + const dropOn = (x, y) => document.elementFromPoint(x, y)?.closest('.fd-meal:not([data-meal=""])') || null; + function endDrag(ok) { + if (!drag) return; + const { li, ghost, over, entry } = drag; + drag = null; + ghost?.remove(); + li.classList.remove("dragging"); + document.body.classList.remove("fd-dragging"); + over?.classList.remove("drop"); + if (ok && over && over.dataset.meal !== entry.meal) + post("/food/api/entry/move", { id: entry.id, meal: over.dataset.meal }).then(refresh).catch(refresh); + } + document.addEventListener("pointerdown", (e) => { + const grip = e.target.closest?.(".fd-grip"); + if (!grip || e.button !== 0 || anyOpen() || picking()) return; + e.preventDefault(); + closeEditor(); + const li = grip.closest("li"), btn = li.querySelector(".fd-e"); + drag = { li, btn, entry: JSON.parse(btn.dataset.entry), x0: e.clientX, y0: e.clientY, ghost: null, over: null }; + grip.setPointerCapture(e.pointerId); + }); + document.addEventListener("pointermove", (e) => { + if (!drag) return; + if (!drag.ghost) { // a few px first, so a stray click isn't a drag + if (Math.hypot(e.clientX - drag.x0, e.clientY - drag.y0) < 5) return; + const r = drag.btn.getBoundingClientRect(); + drag.ghost = drag.btn.cloneNode(true); + drag.ghost.className = "fd-e fd-drag"; + drag.ghost.style.width = r.width + "px"; + drag.dx = drag.x0 - r.left; drag.dy = drag.y0 - r.top; + document.body.appendChild(drag.ghost); + drag.li.classList.add("dragging"); + document.body.classList.add("fd-dragging"); + } + drag.ghost.style.left = e.clientX - drag.dx + "px"; + drag.ghost.style.top = e.clientY - drag.dy + "px"; + const over = dropOn(e.clientX, e.clientY); + if (over !== drag.over) { drag.over?.classList.remove("drop"); over?.classList.add("drop"); drag.over = over; } + if (e.clientY < 50) scrollBy(0, -14); else if (e.clientY > innerHeight - 50) scrollBy(0, 14); + }); + document.addEventListener("pointerup", () => endDrag(true)); + document.addEventListener("pointercancel", () => endDrag(false)); + document.addEventListener("keydown", (e) => { if (drag && e.key === "Escape") { e.stopImmediatePropagation(); endDrag(false); } }, true); + + // /food#add opens the inline editor in the meal of the hour (Health's + menu: "Food"); + // #add=REF with that food picked (a meal just made on another page) + const addm = /^#add(?:=(.+))?$/.exec(location.hash); + if (addm && document.querySelector(".fd-meals")) { + history.replaceState(null, "", location.pathname + location.search); + if (addm[1]) getFood(decodeURIComponent(addm[1])).then((f) => openEditor({ meal: guessMeal(), food: f })).catch(() => openEditor({ meal: guessMeal() })); + else openEditor({ meal: guessMeal() }); + } +})(); diff --git a/dashboard/plugins/food/sugar.py b/dashboard/plugins/food/sugar.py new file mode 100644 index 0000000..4cbe28b --- /dev/null +++ b/dashboard/plugins/food/sugar.py @@ -0,0 +1,209 @@ +"""Added sugar, estimated: the sugars WHO's limit is about (under 10 % of the energy; WHO calls them +"free sugars") — sugar, honey and syrups added to food, plus fruit juice — not the sugar inside whole +fruit, vegetables and plain milk. The databases only give total sugar (USDA's generic foods have no +added-sugar field, Open Food Facts rarely fills one in), so each food gets a kind from its category / name: + + added all its sugar counts (juice, sweets, cakes, soft drinks, syrups, sweetened cereals, products …) + dairy only what's beyond the milk's own lactose (≈ LACTOSE g per 100 g): plain milk / yogurt 0, + a flavoured yogurt its extra + natural none counts (whole or dried fruit, vegetables, legumes, nuts, grains, meat, fish, eggs …) + +USDA's generic foods are natural unless an added / dairy rule matches (the broad SR categories Snacks, +Fast Foods, Beverages, Baby Foods go by the name words alone). Open Food Facts products (local foods.db or +the archive on the sync server — off.py writes the same columns to both): the label's own added-sugar +figure (`added_sugar`, g / 100 g) when it gives one; else natural when unprocessed (NOVA 1) or labelled +"no added sugar"; else by its ingredients when they're known (`sugars_in`: the sweet ones the label lists — +"" = none, so natural; OFF's language-independent ingredient tags, any language), dairy when OFF files it +as dairy (`dairy`); without ingredients added unless the name says dairy. Meals add up their ingredients; +entries without a food go by their name, added when it doesn't say. + +Names are matched folded (lower case, no diacritics: "zahăr" = "zahar"), with words in English, Romanian, +Slovak / Czech, Hungarian, German, Polish, French, Italian, Spanish, Portuguese. Worked out on read (never +stored), so the rules can change. The app has the same rules (dash-app lib/health/sugar.dart). +""" +import json +import os +import re +import sys + +# lower-cased letters with diacritics → plain ones (sugar.dart has the same table) +FOLD = str.maketrans({**{c: "a" for c in "áàâäãåāăą"}, **{c: "c" for c in "çčć"}, **{c: "d" for c in "ďđ"}, + **{c: "e" for c in "éèêëěęē"}, **{c: "i" for c in "íìîïī"}, **{c: "l" for c in "ľĺł"}, + **{c: "n" for c in "ňńñ"}, **{c: "o" for c in "óòôöõőø"}, **{c: "r" for c in "řŕ"}, + **{c: "s" for c in "śšşș"}, **{c: "t" for c in "ťţț"}, **{c: "u" for c in "úùûüůűū"}, + **{c: "y" for c in "ýÿ"}, **{c: "z" for c in "žźż"}, "ß": "ss", "æ": "ae", "œ": "oe"}) + + +def fold(s): + """'Zahăr Brun' → 'zahar brun' (what the word lists are matched against).""" + return (s or "").lower().translate(FOLD) + + +LACTOSE = 5.0 # g per 100 g of milk / yogurt that is the milk's own sugar (milk ≈ 4.8–5) + +ADDED_WORDS = re.compile( + r"juice|nectar(?!ine)|syrup|honey|\bjam\b|jelly|marmalade|candy|candies|chocolate|cocoa|(?`\n" + "// — don't edit; change the table and run it again. USDA category (lower case) → (kind, names going by their name).\n" + "const sugarKinds = {\n" + "\n".join(rows) + "\n};\n") + print(f"{len(rows)} categories → {path}") + + +if __name__ == "__main__": + if len(sys.argv) == 3 and sys.argv[1] == "--dart": + dart(sys.argv[2]) + else: + sys.exit("python3 plugins/food/sugar.py --dart ../app/lib/health/sugar_kinds.g.dart") diff --git a/dashboard/plugins/food/sugar_kinds.json b/dashboard/plugins/food/sugar_kinds.json new file mode 100644 index 0000000..31b1f72 --- /dev/null +++ b/dashboard/plugins/food/sugar_kinds.json @@ -0,0 +1,58 @@ +{ + "_doc": "USDA categories (SR Legacy / Foundation food groups, WWEIA categories of the Survey foods) whose sugar counts as one kind (sugar.py): \"added\" = all of it, \"dairy\" = beyond the milk's own lactose; any other category: by the food's name. {kind, except}: names matching `except` (regex) go by their name instead. Reviewed 2026-10-23. Survey foods with FPED's added sugars (foods.db added_sugar) use those first. The app's copy: lib/health/sugar_kinds.g.dart, made by `python3 plugins/food/sugar.py --dart `.", + "Apple juice": "added", + "Baby food: snacks and sweets": "added", + "Baby juice": "added", + "Baked Products": "added", + "Biscuits, muffins, quick breads": "added", + "Breakfast Cereals": { + "kind": "added", + "except": "\\bplain\\b|grits|farina|regular and quick|unsweetened" + }, + "Cakes and pies": "added", + "Candy containing chocolate": "added", + "Candy not containing chocolate": "added", + "Cereal bars": "added", + "Cheese": "dairy", + "Cheese sandwiches": "dairy", + "Citrus juice": "added", + "Cookies and brownies": "added", + "Cottage/ricotta cheese": "dairy", + "Cream and cream substitutes": "dairy", + "Cream cheese, sour cream, whipped cream": "dairy", + "Dairy and Egg Products": "dairy", + "Doughnuts, sweet rolls, pastries": "added", + "Flavored milk, lowfat": "added", + "Flavored milk, nonfat": "added", + "Flavored milk, reduced fat": "added", + "Flavored milk, whole": "added", + "Fruit drinks": "added", + "Gelatins, ices, sorbets": "added", + "Ice cream and frozen dairy desserts": "added", + "Jams, syrups, toppings": "added", + "Liquor and cocktails": "added", + "Milk shakes and other dairy drinks": "added", + "Milk, lowfat": "dairy", + "Milk, nonfat": "dairy", + "Milk, reduced fat": "dairy", + "Milk, whole": "dairy", + "Nutrition bars": "added", + "Nutritional beverages": "added", + "Other fruit juice": "added", + "Pancakes, waffles, French toast": "added", + "Plant-based milk": "dairy", + "Plant-based yogurt": "dairy", + "Pudding": "added", + "Ready-to-eat cereal, higher sugar (>21.2g/100g)": "added", + "Ready-to-eat cereal, lower sugar (=<21.2g/100g)": "added", + "Smoothies and grain drinks": "added", + "Soft drinks": "added", + "Sport and energy drinks": "added", + "Sugars and honey": "added", + "Sweets": "added", + "Tomato-based condiments": "added", + "Turnovers and other grain-based items": "added", + "Vegetable juice": "added", + "Yogurt, Greek": "dairy", + "Yogurt, regular": "dairy" +} \ No newline at end of file diff --git a/dashboard/plugins/food/templates/food/_head.html b/dashboard/plugins/food/templates/food/_head.html new file mode 100644 index 0000000..d87c72b --- /dev/null +++ b/dashboard/plugins/food/templates/food/_head.html @@ -0,0 +1,272 @@ +{# Food pages: the core header (⌂ 📅 … ··· ‹ title › ··· ⚙), Health's tab row when it lives + there, and the left column both pages share — the energy ring + nutrient bars of the day + shown, the add / describe buttons, the Day | History switch. #} +{% from "_header.html" import nav_btns, settings_btn, title_block, subline, section_tabs %} +{% macro head(title, sub, current=True, center_href="/food", prev_href=None, next_href=None, can_next=True) %} +
    + {{ nav_btns() }} + {{ title_block(title, center_href, current, prev_href, next_href, can_next=can_next, + prev_title="Day before", next_title="Day after", link_title="Today") }} + {{ settings_btn("food") }} +
    +{{ subline(sub) }} +{% if plugin_host("food") %}{{ section_tabs(plugin_host("food"), "/food") }}{% endif %}{# inside Health: its tab row #} +{% endmacro %} + +{% macro n(x, unit="") %}{% if x is none %}—{% else %}{{ "{:,.0f}".format(x).replace(",", " ") }}{% if unit %} {{ unit }}{% endif %}{% endif %}{% endmacro %} +{% macro g(x) %}{% if x is none %}—{% elif x < 10 %}{{ "%.1f" | format(x) | replace(".0", "") }}{% else %}{{ x | round | int }}{% endif %}{% endmacro %} +{# protein / carbs / fat as coloured dots (the ring's colours), the names on hover (letters were tried: dots read better) #} +{% macro mac(p, c, f) %}{% for k, x in [("protein", p), ("carbs", c), ("fat", f)] %}{{ g(x) }}{% if x is not none %} g{% endif %}{% endfor %}{% endmacro %} +{% macro day_label(d, today) %}{% if d == today %}Today{% elif (today - d).days == 1 %}Yesterday{% elif (d - today).days == 1 %}Tomorrow{% else %}{{ d.strftime("%a") }} {{ d.day }} {{ d.strftime("%b") }}{% endif %}{% endmacro %} + +{# the energy ring (views.ring) — r: the ring, size: its CSS width #} +{% macro plan_tip(p) %}{% if p.set %}Your own target (Settings ▸ Food){% if p.calc %}; calculated: {{ n(p.calc) }} kcal{% endif %}.{% elif p.calc and not p.rate %}Your usual day, to keep your weight: {{ n(p.calc) }} kcal.{% elif p.calc %}Your usual day {{ n(p.maintenance) }} kcal {{ "+" if p.rate < 0 else "−" }} {{ n(p.deficit | abs) }} for {{ "%g" | format(p.rate | abs) }} % a week{% if p.capped %} (limited){% endif %} = {{ n(p.calc) }} kcal.{% else %}Default target — Health's profile and a weight give a calculated one.{% endif %}{% endmacro %} +{% macro ring(r, p=None) %} +
    + +
    + {{ n(r.kcal) }}of {{ n(r.target) }} kcal + {% if r.left >= 0 %}{{ n(r.left) }} left{% else %}{{ n(-r.left) }} over{% endif %} +
    +
    +{% endmacro %} + +{# nutrient bars (views.bars): the three macros big, the rest small #} +{% macro bars(bs) %} +
    + {% for b in bs[:3] %} +
    + {{ b.label }}{{ g(b.v) }} / {{ b.target }} g + +
    + {% endfor %} +
    +
    + {% for b in bs[3:] %} + {% if b.kind == "info" %} +
    +
    {{ b.label }}
    {{ g(b.v) }} {{ b.unit }}
    + + {% else %} +
    +
    {{ b.label }}
    {{ g(b.v) }} / {{ "≥ " if b.kind == "min" else "≤ " if b.kind == "max" }}{{ n(b.target) }} {{ b.unit }}
    + + {% endif %} +
    + {% endfor %} +
    +{% endmacro %} + +{# the day's activity from Health (views.day: activity, balance) — under the macros #} +{% macro activity(v) %}{% set a, e = v.activity, v.activity.energy %} +
    +
    Activity{{ " so far" if v.day == v.today }}Health ›
    +
    + {% if a.steps %}{{ n(a.steps) }} steps{% endif %} + {% for w in a.workouts %}{{ w.name }} · {{ w.minutes }} min{% if w.kcal %} · {{ n(w.kcal) }} kcal{% endif %}{% endfor %} + {% if not a.workouts %}no workout{% endif %} +
    + {% if e %} +
    + Burned ≈ {{ n(e.total) }} kcal + {% if v.balance is not none %}eaten − burned {{ "+" if v.balance > 0 }}{{ n(v.balance) }}{% endif %} +
    + {% endif %} +
    +{% endmacro %} + +{# v = views.day(…) for the day shown (History: today) #} +{% macro side(v) %} +
    +
    +

    {{ day_label(v.day, v.today) }}

    + {{ ring(v.ring, v.plan) }} + {{ bars(v.bars) }} + {% if v.activity %}{{ activity(v) }}{% endif %} +
    +
    + {% if model_off %}{# the model switched off (Settings ▸ Food): just the form #} +
    + {% else %} +
    + +
    + + + {% if parser %} + {% else %}Needs a language model — set its address in Settings ▸ Food. Until then, add foods with the form.{% endif %} +
    + +
    + {% endif %} +
    + +
    +{% endmacro %} + +{% macro assets() %} + +{% endmacro %} + +{# the dialogs (no browser dialogs): one entry; the describe box's list to confirm #} +{% macro dialogs(day) %} + + +{# the inline editor (food.js InlineEditor): dropped into a meal card by its +, or into a logged food's + line when clicked. data-mode: search (just the box) · food (a picked food: its numbers as text, amount + + unit) · edit (Edit item: its values per 100 g + portions editable) · new (a food typed in) · totals + (an entry without a food: its numbers). "More": day, meal, note. #} + + + + + + + + +{% endmacro %} diff --git a/dashboard/plugins/food/templates/food/_ovcard.html b/dashboard/plugins/food/templates/food/_ovcard.html new file mode 100644 index 0000000..309e09a --- /dev/null +++ b/dashboard/plugins/food/templates/food/_ovcard.html @@ -0,0 +1,35 @@ +{# Health ▸ Overview: today's food card (views.summary as s). Health's card look; its own small + ring styles inline here (food.css isn't on Health's pages). #} +{% import "food/_head.html" as fd %} +
    + +

    Food today

    Diary ›
    + {% if not s.n %}

    Nothing logged today — add food.

    {% else %} +
    +
    + +
    {{ fd.n(s.ring.kcal) }}of {{ fd.n(s.target) }} kcal
    +
    +
    + {% for b in s.bars[:3] %} +
    {{ b.label }}
    {{ fd.g(b.v) }} / {{ b.target }} g
    + {% endfor %} +
    Left
    {% if s.ring.left >= 0 %}{{ fd.n(s.ring.left) }} kcal{% else %}{{ fd.n(-s.ring.left) }} kcal over{% endif %}
    +
    +
    + {% endif %} +
    diff --git a/dashboard/plugins/food/templates/food/_ovtile.html b/dashboard/plugins/food/templates/food/_ovtile.html new file mode 100644 index 0000000..498d1c9 --- /dev/null +++ b/dashboard/plugins/food/templates/food/_ovtile.html @@ -0,0 +1,5 @@ +{# Health ▸ Overview: today's energy tile (views.summary as s) — the inside of a tile. #} +{% import "food/_head.html" as fd %} +Eaten today +{% if not s.n %}—nothing logged +{% else %}{{ fd.n(s.ring.kcal) }} kcal{% if s.ring.left >= 0 %}{{ fd.n(s.ring.left) }} left of {{ fd.n(s.target) }}{% else %}{{ fd.n(-s.ring.left) }} over {{ fd.n(s.target) }}{% endif %}{% endif %} diff --git a/dashboard/plugins/food/templates/food/_report.html b/dashboard/plugins/food/templates/food/_report.html new file mode 100644 index 0000000..432a613 --- /dev/null +++ b/dashboard/plugins/food/templates/food/_report.html @@ -0,0 +1,18 @@ +{# Health ▸ report: the food diary's part — the average logged day over the report's range, + with reference values. Uses the report's .rp-* styles. #} +{% macro dmy(x) %}{{ x.day }} {{ x.strftime("%b %Y") }}{% endmacro %} +
    +

    Food intake self-logged, {{ dmy(r.since) }} – {{ dmy(r.today) }}

    + {% if not r.logged %}

    Nothing logged in this period.

    {% else %} + + + + + + + + + +
    Days logged{{ r.logged }} of {{ r.days }}averages below are over the logged days
    Energy{{ r.kcal }} kcal a day
    Protein{{ r.protein }} g{{ r.protein_pct }} % of the energy (typical 10–35 %)
    Carbohydrates{{ r.carbs }} g{{ r.carbs_pct }} % of the energy (typical 45–65 %)
    Fat{{ r.fat }} g{{ r.fat_pct }} % of the energy (typical 20–35 %){% if r.sat_pct is not none %} · saturated {{ r.sat_pct }} % (under 10 %){% endif %}
    Sugar{{ r.sugar }} g(added sugar under 50 g)
    Fibre{{ r.fiber }} g(at least 25 g)
    Sodium{{ r.sodium }} mg(under 2000 mg)
    + {% endif %} +
    diff --git a/dashboard/plugins/food/templates/food/_settings.html b/dashboard/plugins/food/templates/food/_settings.html new file mode 100644 index 0000000..190abdc --- /dev/null +++ b/dashboard/plugins/food/templates/food/_settings.html @@ -0,0 +1,64 @@ +{# Settings ▸ Food, above the fields: how the energy target is worked out (views.plan as p, from + Health's energy summary e), what each weight goal would give, every macro preset in grams + (views.presets). Read-only — the fields below set it. Styles inline (settings page). #} + +{% macro n(x) %}{{ "{:,.0f}".format(x).replace(",", " ") if x is not none else "—" }}{% endmacro %} +
    +
    +

    Energy target

    +
    {{ n(p.kcal) }} kcal a day{% if p.set %} — your own number{% endif %}
    + {% if p.calc %} +
    +
    Weight{% if p.weight_day %} ({{ p.weight_day.day }} {{ p.weight_day.strftime("%b") }}){% endif %}
    {{ "%g" | format(p.weight) }} kg
    +
    Resting energy (Mifflin–St Jeor)
    {{ n(p.bmr) }} kcal
    +
    Your usual day
    {{ n(p.maintenance) }} kcal
    + {% if p.rate %}
    {{ "Surplus" if p.rate < 0 else "Deficit" }} for {{ "%g" | format(p.rate | abs) }} % a week ({{ "%g" | format(p.kg_week | abs) }} kg)
    {{ "+" if p.rate < 0 else "−" }} {{ n(p.deficit | abs) }} kcal
    {% endif %} +
    Calculated target
    {{ n(p.calc) }} kcal
    +
    + {% if p.capped %}

    Limited: at most {{ n(1000) }} kcal under your usual day and never under {{ n(p.floor) }} kcal — more than that only with a doctor.

    {% endif %} + {% if p.set %}

    Your own number below replaces the calculated {{ n(p.calc) }}. Set it to 0 to use the calculation.

    {% endif %} + {% else %} +

    Can't calculate a target yet: Health needs your sex, birth date, height (Settings ▸ Health) and a weight measurement. Until then: {{ "your own number" if p.set else "2 000 kcal" }}.

    + {% endif %} +
    + + {% if p.calc %} +
    +

    Weight goals

    + + + {% for o in p.options %}{% endfor %} +
    Goalkg a weekkcal a day
    {{ o.label }}{{ "%+g" | format(-o.kg_week) if o.kg_week else "0" }}{{ n(o.kcal) }}{% if o.capped %} (limited){% endif %}
    +

    0.5–1 % of body weight a week is the usual advice for losing weight without losing much muscle; slower is easier to keep up. Your usual day comes from Health's energy estimate and moves with your weight and activity.

    +
    + {% endif %} + +
    +

    Protein / carbs / fat for {{ n(p.kcal) }} kcal

    + + + {% for s in presets %}{% endfor %} +
    Split%ProteinCarbsFat
    {{ s.label }}{{ s.pct | join("·") }}{{ s.g[0] }} g{% if s.per_kg %} {{ s.per_kg }}/kg{% endif %}{{ s.g[1] }} g{{ s.g[2] }} g
    +

    Recommended ranges: protein 10–35 %, carbs 45–65 %, fat 20–35 % of the energy. When losing weight, more protein (about 1.2–1.6 g per kg — per kg of a healthy weight if you're heavier) keeps muscle and keeps you full: Higher protein is a good start. Hover a row for what it's for.

    +
    + +
    +

    Food database

    + {% if has_db %}

    USDA FoodData Central (generic foods, ≈ 13 700, nutrients per 100 g + household portions) — the add form searches it as you type.

    + {% else %}

    Not installed: build dash_data/food/foods.db on the PC with python3 plugins/food/fdc.py <FoodData_Central_csv zip> foods.db and copy it there.

    {% endif %} +
    +
    diff --git a/dashboard/plugins/food/templates/food/day.html b/dashboard/plugins/food/templates/food/day.html new file mode 100644 index 0000000..3aa4c9c --- /dev/null +++ b/dashboard/plugins/food/templates/food/day.html @@ -0,0 +1,69 @@ +{% extends "base.html" %} +{% import "food/_head.html" as fd with context %} +{% block title %}Food{% endblock %} +{% block head %}{{ fd.assets() }}{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{# One day: the week strip (energy per day, click = that day), the meals with their foods + (click one = edit, a meal's + = add to it), left: ring + bars + the add / describe box. + food.js: the dialogs; after a save it swaps in .fd from a fresh copy of the page. #} +{% set n, g = fd.n, fd.g %} +{% macro amount(e) %}{% if e.amount is not none %}{{ g(e.amount) }}{% if e.unit %} {{ e.unit }}{% endif %}{% endif %}{% endmacro %} +{% block page %} +{{ fd.head(fd.day_label(v.day, v.today), v.day.strftime("%A ") ~ v.day.day ~ v.day.strftime(" %B %Y") ~ (" · planned" if v.future else " · food"), + v.day == v.today, "/food", "/food?d=" ~ v.prev.isoformat(), + ("/food?d=" ~ v.next.isoformat()) if v.next else None, v.next is not none) }} + +
    + {{ fd.side(v) }} + +
    + + + +
    + {% for col in [v.meals[:2], v.meals[2:]] %}
    + {% for m in col %} +
    +
    +

    {{ m.label }}

    + {% if m.rows %}{{ n(m.t.kcal) }} kcal{{ fd.mac(m.t.protein, m.t.carbs, m.t.fat) }}{% endif %} + {% if m.key %}{% endif %} +
    + {% if m.rows %} +
      + {% for e in m.rows %} +
    • {% if m.key %}{% endif %}
    • + {% endfor %} +
    + {% elif m.key %} + + {% endif %} +
    + {% endfor %} +
    {% endfor %} +
    +
    + {# the add box: yesterday's foods with a + (food.js) #} +
    +{% endblock %} + +{% block scripts %}{{ fd.dialogs(v.day.isoformat()) }}{% endblock %} diff --git a/dashboard/plugins/food/templates/food/foods.html b/dashboard/plugins/food/templates/food/foods.html new file mode 100644 index 0000000..f2f0060 --- /dev/null +++ b/dashboard/plugins/food/templates/food/foods.html @@ -0,0 +1,38 @@ +{% extends "base.html" %} +{% import "food/_head.html" as fd with context %} +{% block title %}My foods{% endblock %} +{% block head %}{{ fd.assets() }}{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{# My foods — your own food database: values per 100 g + portions (db.my_foods), meals among + them (made of other foods). Click a row = the food dialog (food.js, mode foodonly) or, for a + meal, the meal builder: change it, delete it (hidden — entries made from it + keep their numbers). New ones also come from the add dialog (a typed-in food, or a database + food after "Edit item"). Left column: today. #} +{% set n, g = fd.n, fd.g %} +{% block page %} +{{ fd.head("My foods", "your own food database · food", True, "/food/foods") }} +
    +{{ fd.side(now) }} +
    +
    +

    My foods {{ foods | length }}

    + {% if not foods %} +

    Nothing yet. Foods land here when you add one that isn't in the list (its values per 100 g, from the label), change a food from the database with Edit item, or make a meal.

    + {% else %} + + + {% for f in foods %} + + + + + + {% endfor %} +
    FoodkcalProteinCarbsFatPortionsUsed
    {{ f.name }}{% if f.recipe %}meal · {{ f.recipe.ingredients | length }} ingredient{{ "s" if f.recipe.ingredients | length != 1 }}: {{ f.recipe.ingredients | map(attribute="name") | join(", ") | truncate(70) }}{% elif f.based_on_name %}from {{ f.based_on_name }}{% endif %}{{ n(f.per100.kcal) }}{{ g(f.per100.protein) }}{{ g(f.per100.carbs) }}{{ g(f.per100.fat) }}{% for p in f.portions %}{{ p.label }} {{ g(p.grams) }} g{{ ", " if not loop.last }}{% else %}—{% endfor %}{{ f.uses or "" }}
    +

    Values per 100 g. Changing a food doesn't change entries already logged.

    + {% endif %} +
    +
    +
    +{% endblock %} +{% block scripts %}{{ fd.dialogs(now.day.isoformat()) }}{% endblock %} diff --git a/dashboard/plugins/food/templates/food/history.html b/dashboard/plugins/food/templates/food/history.html new file mode 100644 index 0000000..171ecf3 --- /dev/null +++ b/dashboard/plugins/food/templates/food/history.html @@ -0,0 +1,82 @@ +{% extends "base.html" %} +{% import "food/_head.html" as fd with context %} +{% block title %}Food history{% endblock %} +{% block head %}{{ fd.assets() }}{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{# The range (?r=): tiles (the average logged day), energy per day — per week from + views.WEEKLY_FROM days — stacked by macro with the target line, the most eaten foods. + Left column: today (views.day). #} +{% set n, g = fd.n, fd.g %} +{% macro dmy(d) %}{{ d.day }} {{ d.strftime("%b %Y") }}{% endmacro %} +{% set a = v.avg %} +{% block page %} +{{ fd.head("History", v.ranges[v.range][0] ~ " · food", True, "/food/history") }} + +
    +{{ fd.side(now) }} +
    +
    +

    {{ dmy(v.from) }} – {{ dmy(v.to) }}

    + +
    + + {% if not v.logged %} +
    Nothing logged in this range.{% if v.range != "all" %} Show everything{% endif %}
    + {% else %} +
    +
    Average day{{ n(a.kcal) }} kcaltarget {{ n(v.targets.kcal[0]) }}
    +
    Days logged{{ v.logged }} of {{ v.n_days }}{{ v.on_target }} within 10 % of the target
    +
    Protein{{ g(a.protein) }} gtarget {{ v.targets.protein[0] }} g
    +
    Fibre{{ g(a.fiber) }} gat least {{ v.targets.fiber[0] }} g
    +
    Sugar{{ g(a.sugar) }} ga logged day on average
    + {% if v.split %} +
    Energy from + {% for m in ("protein", "carbs", "fat") %}{% endfor %} + {% for m in ("protein", "carbs", "fat") %}{{ v.split[m] }}%{% endfor %}
    + {% endif %} +
    + +
    +

    Energy {{ "per week (the average logged day)" if v.chart.weekly else "per day" }}

    + proteincarbsfattarget
    + {% set c = v.chart %} + + {% for b in c.bars %} + {% if c.weekly %}{% else %}{% endif %} + {{ b.tip }} + + {% for s in b.segs %}{% endfor %} + {% if c.weekly %}{% else %}{% endif %} + {% endfor %} + + + {% for t in c.ticks %}{{ t.t }}{% endfor %} + +
    + +
    +
    +

    Most eaten

    + + + {% for f in v.top %}{% endfor %} +
    FoodTimeskcalTotal
    {{ f.name }}{{ f.times }}{{ n(f.kcal) }}{{ n(f.total) }}
    +
    +
    +

    The average logged day

    Export CSV
    + + + {% for k, l, u in [("kcal", "Energy", "kcal"), ("protein", "Protein", "g"), ("carbs", "Carbs", "g"), ("sugar", "of which sugar", "g"), ("fat", "Fat", "g"), ("sat_fat", "of which saturated", "g"), ("fiber", "Fibre", "g"), ("sodium_mg", "Sodium", "mg")] %} + {% set t = v.targets[k] %} + + {% endfor %} + +
    {{ l }}{{ g(a[k]) if u == "g" else n(a[k]) }} {{ u }}{{ {"goal": "target", "min": "at least", "max": "at most"}[t[1]] }} {{ n(t[0]) }} {{ u }}
    +
    +
    + {% endif %} +
    +
    +{% endblock %} + +{% block scripts %}{{ fd.dialogs(now.day.isoformat()) }}{% endblock %} diff --git a/dashboard/plugins/food/views.py b/dashboard/plugins/food/views.py new file mode 100644 index 0000000..0a5e027 --- /dev/null +++ b/dashboard/plugins/food/views.py @@ -0,0 +1,326 @@ +"""View models for the food pages: plain dicts, geometry computed here (the templates only draw). + + day(…) /food?d=YYYY-MM-DD: the week strip, the day's meals, totals vs targets, the ring + history(…) /food/history?r=: tiles, energy per day (or week) stacked by macro, top foods + summary(…) Health ▸ Overview: today's card / tile + report(…) Health's report page: averages over its range +""" +import math +from datetime import date, timedelta + +from .db import MEAL_KEYS + +MEAL_LABELS = {"breakfast": "Breakfast", "lunch": "Lunch", "dinner": "Dinner", "snack": "Snacks"} +KCAL_PER_G = {"protein": 4, "carbs": 4, "fat": 9} +MACROS = ("protein", "carbs", "fat") +RANGES = {"1m": ("Last 30 days", 30), "3m": ("Last 3 months", 91), "1y": ("Last year", 365), "all": ("Everything", None)} +WEEKLY_FROM = 120 # days in range: from here the chart shows weeks, not days +CHART_W, CHART_H = 1000, 240 + + +# Weight goal: % of body weight a week (negative = gain). 1 kg of body fat ≈ 7700 kcal. +RATES = [[0.0, "Keep my weight"], [0.25, "Lose 0.25 % a week — slow"], [0.5, "Lose 0.5 % a week — steady"], + [0.75, "Lose 0.75 % a week — faster"], [1.0, "Lose 1 % a week — fast"], [-0.25, "Gain 0.25 % a week"]] +KCAL_PER_KG = 7700 +MAX_DEFICIT = 1000 # kcal a day: more than this costs muscle and is hard to keep up +MIN_KCAL = {"female": 1200, "male": 1500} # below this, only with a doctor (very-low-calorie diets) +ACTIVITY_FALLBACK = 1.4 # × resting energy, while Health has under MIN_DAYS of step data +MIN_DAYS = 7 +# Macro presets: % of the energy from protein / carbs / fat. All but "lower carb" sit inside the +# Acceptable Macronutrient Distribution Ranges (IOM: protein 10–35, carbs 45–65*, fat 20–35 %). +PRESETS = {"balanced": ("Balanced", 20, 50, 30, "The middle of the recommended ranges."), + "high_protein": ("Higher protein", 30, 40, 30, "Keeps muscle while losing weight and keeps you full " + "longer — the usual advice when eating less."), + "mediterranean": ("Mediterranean", 20, 45, 35, "More fat, mostly olive oil, nuts and fish; fewer starches."), + "lower_carb": ("Lower carb", 30, 25, 45, "Below the recommended carbs — some find it easier to stay " + "full; keep the fibre up (vegetables, nuts, seeds)."), + "custom": ("Custom", None, None, None, "Your own split (Settings ▸ Food).")} + + +def plan(s, energy): + """The daily energy target and how it was worked out. energy = Health's energy summary + (ctx.ask("health", "energy"): weight, bmr, tdee, days) or None. + → {kcal, calc (None if it can't be worked out), set (the override or None), maintenance, + basis, bmr, weight, deficit, rate, capped, floor, kg_week, options: [{rate, label, kcal}]}""" + e = energy or {} + bmr, weight = e.get("bmr"), e.get("weight") + if e.get("tdee") and e.get("days", 0) >= MIN_DAYS: + maint, basis = e["tdee"], f"your average day in Health (resting + walking + workouts, {e['days']} days)" + elif bmr: + maint, basis = round(bmr * ACTIVITY_FALLBACK), f"resting energy × {ACTIVITY_FALLBACK} (not enough step data in Health yet)" + else: + maint, basis = None, None + floor = MIN_KCAL.get(e.get("sex"), 1200) + + def target(rate): + if not (maint and weight): + return None, 0, False + deficit = weight * rate / 100 * KCAL_PER_KG / 7 + capped = deficit > MAX_DEFICIT + deficit = min(deficit, MAX_DEFICIT) + kcal = maint - deficit + if kcal < floor: + kcal, capped = floor, True + return int(round(kcal / 10) * 10), round(deficit), capped + + rate = float(s.get("goal_rate") or 0) + calc, deficit, capped = target(rate) + kcal = s.get("kcal_target") or calc or 2000 + return {"kcal": kcal, "calc": calc, "set": s.get("kcal_target") or None, "maintenance": maint, "basis": basis, + "bmr": round(bmr) if bmr else None, "weight": weight, "weight_day": e.get("weight_day"), "rate": rate, + "deficit": deficit, "capped": capped, "floor": floor, + "kg_week": round(weight * rate / 100, 2) if weight else None, + "options": [{"rate": r, "label": l, "kcal": target(r)[0], "capped": target(r)[2], + "kg_week": round(weight * r / 100, 2) if weight else None} for r, l in RATES]} + + +def split(s): + """(protein, carbs, fat) % of the energy, from the preset or the custom fields.""" + p = PRESETS.get(s.get("macro_preset")) or PRESETS["balanced"] + if p[1] is None: + return (s.get("custom_protein") or 20, s.get("custom_carbs") or 50, s.get("custom_fat") or 30) + return p[1:4] + + +def targets(s, energy=None): + """Settings + Health's energy → the day's goals: {key: (value, kind)} — kind "goal" (aim + for it), "min" (at least) or "max" (at most).""" + kcal = plan(s, energy)["kcal"] + t = {"kcal": (kcal, "goal")} + for m, pct in zip(MACROS, split(s)): + t[m] = (round(kcal * pct / 100 / KCAL_PER_G[m]), "goal") + t["fiber"] = (s.get("fiber_min") or 25, "min") + t["sugar"] = (None, "info") # total sugar: shown, no limit (natural sugar counts too) + t["added_sugar"] = (round(kcal * 0.10 / 4), "max") # WHO: added ("free") sugars under 10 % of the energy (sugar.py) + t["sat_fat"] = (round(kcal * 0.10 / 9), "max") # under 10 % of the energy (WHO) + t["sodium_mg"] = (s.get("sodium_max") or 2000, "max") + return t + + +def presets(s, energy): + """Settings ▸ Food: every preset in grams for today's target (+ protein per kg).""" + kcal = plan(s, energy)["kcal"] + w = (energy or {}).get("weight") + out = [] + for k, (label, *pcts, note) in PRESETS.items(): + pcts = split(dict(s, macro_preset=k)) + g = [round(kcal * pct / 100 / KCAL_PER_G[m]) for m, pct in zip(MACROS, pcts)] + out.append({"key": k, "label": label, "pct": pcts, "g": g, "note": note, "on": (s.get("macro_preset") or "balanced") == k, + "per_kg": round(g[0] / w, 1) if w else None}) + return out + + +def _sum(rows, k): + vals = [r[k] for r in rows if r.get(k) is not None] + return sum(vals) if vals else None + + +def totals(rows): + out = {k: _sum(rows, k) for k in ("kcal", "protein", "carbs", "sugar", "fiber", "fat", "sat_fat", "sodium_mg")} + out["kcal"] = out["kcal"] or 0 + return out + + +def _arc(a, b, r=50): + """SVG path of a circle arc from fraction a to b (0 = top, clockwise).""" + if b - a >= 0.9999: + b = a + 0.9999 + p = lambda f: (round(r * math.sin(2 * math.pi * f), 2), round(-r * math.cos(2 * math.pi * f), 2)) + (x1, y1), (x2, y2) = p(a), p(b) + return f"M{x1} {y1}A{r} {r} 0 {1 if b - a > 0.5 else 0} 1 {x2} {y2}" + + +def ring(t, target): + """The energy ring: arcs per macro (their share of the energy eaten), all together as far + round as eaten ÷ target (a full ring = the target; over it the ring turns red).""" + kcal = t["kcal"] or 0 + frac = min(1.0, kcal / target) if target else 0 + from_macros = {m: (t[m] or 0) * KCAL_PER_G[m] for m in MACROS} + known = sum(from_macros.values()) + arcs, at = [], 0.0 + if known and frac: + gap = 0.006 if frac > 0.05 else 0 + for m in MACROS: + f = frac * from_macros[m] / known + if f > gap * 2: + arcs.append({"m": m, "d": _arc(at + gap, at + f - gap)}) + at += f + elif frac: + arcs.append({"m": "kcal", "d": _arc(0, frac)}) + return {"arcs": arcs, "over": kcal > target * 1.05, "left": round(target - kcal), "kcal": round(kcal), + "target": target} + + +def bars(t, tg): + """Nutrient bars under the ring: value vs target (goal / min / max).""" + rows = [("protein", "Protein", "g"), ("carbs", "Carbs", "g"), ("fat", "Fat", "g"), ("fiber", "Fibre", "g"), + ("sugar", "Sugar", "g"), ("added_sugar", "Added sugar ≈", "g"), ("sat_fat", "Saturated fat", "g"), + ("sodium_mg", "Sodium", "mg")] + out = [] + for k, label, unit in rows: + target, kind = tg[k] + v = t.get(k) + if k == "added_sugar" and v is None: + continue # not worked out (no added_of): leave the bar out + frac = (v or 0) / target if target else 0 + state = "" + if v is not None: + if kind == "max" and v > target: + state = "over" + elif kind == "min" and v >= target: + state = "ok" + elif kind == "goal" and v > target * 1.15: + state = "high" + out.append({"k": k, "label": label, "unit": unit, "v": v, "target": target, "kind": kind, + "w": round(min(frac, 1) * 100, 1), "state": state}) + return out + + +AHEAD = 60 # days into the future the diary goes (planning meals) + + +def day(entries_of, totals_of, s, d, today, energy=None, activity=None, added_of=None): + """entries_of(a, z) / totals_of(a, z): db reads (ISO days); energy: Health's (plan()); + activity: Health's day ({steps, workouts, energy}) or None; added_of(entry) → its added sugar, g (sugar.py).""" + tg = targets(s, energy) + rows = entries_of(d.isoformat(), d.isoformat()) + meals = [] + for k in MEAL_KEYS: + items = [r for r in rows if r["meal"] == k] + meals.append({"key": k, "label": MEAL_LABELS[k], "rows": items, "t": totals(items)}) + other = [r for r in rows if r["meal"] not in MEAL_KEYS] # imports without a meal + if other: + meals.append({"key": "", "label": "Other", "rows": other, "t": totals(other)}) + t = totals(rows) + t["added_sugar"] = round(sum(added_of(r) for r in rows), 1) if added_of and rows else (0 if added_of else None) + yday = (d - timedelta(days=1)).isoformat() + yesterday = [r for r in entries_of(yday, yday) if r["meal"] in MEAL_KEYS] # the add box offers them again + mon = d - timedelta(days=d.weekday()) + wk = totals_of((mon).isoformat(), (mon + timedelta(days=6)).isoformat()) + strip = [] + for i in range(7): + x = mon + timedelta(days=i) + k = (wk.get(x.isoformat()) or {}).get("kcal") + strip.append({"d": x, "kcal": round(k) if k else None, "h": round(min(1.15, (k or 0) / tg["kcal"][0]) * 100), + "today": x == today, "sel": x == d, "future": x > today + timedelta(days=AHEAD), + "ahead": x > today, + "over": bool(k and k > tg["kcal"][0] * 1.05)}) + burned = ((activity or {}).get("energy") or {}).get("total") + return {"day": d, "today": today, "prev": d - timedelta(days=1), + "next": d + timedelta(days=1) if d < today + timedelta(days=AHEAD) else None, "future": d > today, + "plan": plan(s, energy), "activity": activity, "balance": round(t["kcal"] - burned) if burned and rows else None, # nothing logged: no balance + "meals": meals, "yesterday": yesterday, "t": t, "n": len(rows), "ring": ring(t, tg["kcal"][0]), "bars": bars(t, tg), "strip": strip, + "week_kcal": round(sum((v.get("kcal") or 0) for v in wk.values())), + "week_days": sum(1 for v in wk.values() if v.get("kcal"))} + + +def _range(r, first, today): + r = r if r in RANGES else "1m" + n = RANGES[r][1] + if n is None: + a = date.fromisoformat(first) if first else today + else: + a = today - timedelta(days=n - 1) + return r, a + + +def history(totals_of, top_of, first, s, r, today, energy=None): + tg = targets(s, energy) + r, a = _range(r, first, today) + days = totals_of(a.isoformat(), today.isoformat()) + logged = [v for v in days.values() if v.get("kcal")] + n_days = (today - a).days + 1 + avg = lambda k: (sum(v[k] or 0 for v in logged) / len(logged)) if logged else None + av = {k: avg(k) for k in ("kcal", "protein", "carbs", "fat", "fiber", "sugar", "sodium_mg", "sat_fat")} + split = None + if logged: + e = {m: (av[m] or 0) * KCAL_PER_G[m] for m in MACROS} + tot = sum(e.values()) + split = {m: round(100 * e[m] / tot) for m in MACROS} if tot else None + on_target = sum(1 for v in logged if abs(v["kcal"] - tg["kcal"][0]) <= tg["kcal"][0] * 0.1) + return {"range": r, "ranges": RANGES, "from": a, "to": today, "n_days": n_days, "logged": len(logged), + "avg": av, "split": split, "on_target": on_target, "chart": chart(days, a, today, tg["kcal"][0]), + "top": top_of(a.isoformat(), today.isoformat()), "targets": tg} + + +def chart(days, a, z, target): + """Energy per day (or per week from WEEKLY_FROM days: the average logged day) as bars + stacked protein / carbs / fat (by their energy; the rest — alcohol, rounding — grey), + a dashed target line. Coordinates in a CHART_W × CHART_H box.""" + n = (z - a).days + 1 + weekly = n >= WEEKLY_FROM + buckets = [] + if weekly: + start = a - timedelta(days=a.weekday()) + while start <= z: + vs = [days[(start + timedelta(days=i)).isoformat()] for i in range(7) + if (start + timedelta(days=i)).isoformat() in days] + vs = [v for v in vs if v.get("kcal")] + buckets.append((start, vs, f"Week of {start.day} {start.strftime('%b %Y')}")) + start += timedelta(days=7) + else: + for i in range(n): + x = a + timedelta(days=i) + v = days.get(x.isoformat()) + buckets.append((x, [v] if v and v.get("kcal") else [], x.strftime("%a %-d %b %Y"))) + peak = max([target * 1.25] + [sum(v["kcal"] for v in vs) / len(vs) for _, vs, _ in buckets if vs]) + y = lambda k: round(CHART_H - CHART_H * k / peak, 1) + bw = CHART_W / max(1, len(buckets)) + out = [] + for i, (x, vs, label) in enumerate(buckets): + if not vs: + out.append({"x": round(i * bw, 2), "w": round(bw, 2), "segs": [], "tip": f"{label} · nothing logged", "d": x}) + continue + k = sum(v["kcal"] for v in vs) / len(vs) + e = {m: sum((v[m] or 0) for v in vs) / len(vs) * KCAL_PER_G[m] for m in MACROS} + scale = k / sum(e.values()) if sum(e.values()) > k else 1 # labels' macros can add up past the kcal + segs, base = [], 0.0 + for m in MACROS: + h = e[m] * scale + if h > 0: + segs.append({"m": m, "y": y(base + h), "h": round(y(base) - y(base + h), 1)}) + base += h + if k - base > 1: + segs.append({"m": "rest", "y": y(k), "h": round(y(base) - y(k), 1)}) + g = {m: round(sum((v[m] or 0) for v in vs) / len(vs)) for m in MACROS} + tip = f"{label} · {round(k)} kcal" + (f" (average of {len(vs)} days)" if weekly else "") + \ + f" · protein {g['protein']} g, carbs {g['carbs']} g, fat {g['fat']} g" + out.append({"x": round(i * bw, 2), "w": round(bw, 2), "segs": segs, "tip": tip, "d": x, "kcal": round(k)}) + # x labels: months (long ranges) or Mondays + every = 1 if len(buckets) <= 60 else 3 if len(buckets) <= 160 else 6 # months between labels + ticks = [] + for i, (x, _, _) in enumerate(buckets): + if weekly: + if x.day <= 7 and (x.month - 1) % every == 0: + ticks.append({"x": round(i * bw + bw / 2, 1), "t": x.strftime("%b %Y" if x.month == 1 else "%b")}) + elif n > 35 and x.day == 1: + ticks.append({"x": round(i * bw + bw / 2, 1), "t": x.strftime("%b")}) + elif n <= 35 and x.weekday() == 0: + ticks.append({"x": round(i * bw + bw / 2, 1), "t": x.strftime("%-d %b")}) + return {"bars": out, "target_y": y(target), "target": target, "w": CHART_W, "h": CHART_H, "ticks": ticks, + "weekly": weekly, "pad": round(bw * 0.18, 2) if bw > 4 else 0} + + +def summary(entries_of, s, today, energy=None): + """Health ▸ Overview: today's numbers (the card and the tile).""" + tg = targets(s, energy) + rows = entries_of(today.isoformat(), today.isoformat()) + t = totals(rows) + return {"n": len(rows), "t": t, "ring": ring(t, tg["kcal"][0]), "bars": bars(t, tg)[:4], "target": tg["kcal"][0]} + + +def report(totals_of, s, days, today): + """Health's report: the average logged day over the report's range, with references.""" + a = today - timedelta(days=days - 1) + logged = [v for v in totals_of(a.isoformat(), today.isoformat()).values() if v.get("kcal")] + if not logged: + return {"since": a, "today": today, "logged": 0} + avg = lambda k: sum(v[k] or 0 for v in logged) / len(logged) + kcal = avg("kcal") + pct = lambda k: round(100 * avg(k) * KCAL_PER_G.get(k, 9) / kcal) if kcal else None + return {"since": a, "today": today, "logged": len(logged), "days": days, "kcal": round(kcal), + "protein": round(avg("protein")), "protein_pct": pct("protein"), + "carbs": round(avg("carbs")), "carbs_pct": pct("carbs"), + "fat": round(avg("fat")), "fat_pct": pct("fat"), + "sat_pct": round(100 * avg("sat_fat") * 9 / kcal) if kcal else None, + "sugar": round(avg("sugar")), "fiber": round(avg("fiber")), "sodium": round(avg("sodium_mg"))} diff --git a/dashboard/plugins/health/__init__.py b/dashboard/plugins/health/__init__.py new file mode 100644 index 0000000..a415d16 --- /dev/null +++ b/dashboard/plugins/health/__init__.py @@ -0,0 +1,489 @@ +"""Health: body measurements, and the watch data (sleep, heart rate, steps, workouts) from a band. + + /health overview: workouts, steps, BMI, sleep score, last night, last workout + /health/body body values + charts (?r=3m|1y|all), body fat by every formula, ratios, + the measurements (10 a page, ?mp=N) + /health/sleep a night's stages (?d=) + analysis of the range; /heart lowest / highest + heart rate + blood pressure and blood oxygen readings, two kinds kept + apart (typed in or imported; 10 a page each, ?bp=N / ?op=N); /activity steps, energy, workouts; + /workout/ heart rate + zones + calories — watch data from hc.py / + mi.py (Health Connect / Mi Fitness imports) + /health/report a summary for a doctor (?r=3m|6m|1y): values with their reference ranges, + points to discuss, the cycle tracker's summary when it's on; printable + /health/export.csv every measured day + /health/api/… JSON writes (same-origin only, like the core's) + +Data: dash_data/health/health.db (SQLite, see db.py). Never shown on the wall screens. +""" +import csv +import io +import os +import threading +import time +from contextlib import closing +from datetime import date, timedelta + +from flask import Response, abort, jsonify, render_template, request + +from . import blocks, calc, db, gb, mi, summary, views, watch + +MEASURE_PAGE = 10 # Body ▸ Measurements, rows a page + +META = { + "title": "Health", + "glyph": "⚕", + "glyph_color": "#7fd6a3", + "glyph_svg": {"viewBox": "-12 -12 24 24", "d": "M-2.0 -10.5 H2.0 A1.6 1.6 0 0 1 3.6 -8.9 V-3.6 H8.9 A1.6 1.6 0 0 1 10.5 -2.0 V2.0 A1.6 1.6 0 0 1 8.9 3.6 H3.6 V8.9 A1.6 1.6 0 0 1 2.0 10.5 H-2.0 A1.6 1.6 0 0 1 -3.6 8.9 V3.6 H-8.9 A1.6 1.6 0 0 1 -10.5 2.0 V-2.0 A1.6 1.6 0 0 1 -8.9 -3.6 H-3.6 V-8.9 A1.6 1.6 0 0 1 -2.0 -10.5Z"}, # a rounded medical cross + "description": "Body measurements (BMI, waist ratios, body fat by several formulas) and a band's sleep, " + "heart rate, steps and workouts (Gadgetbridge or Mi Fitness), with charts.", + "links": [{"label": "Open", "href": "/health"}, {"label": "Body fat", "href": "/health/body"}], + "settings": [ + {"key": "sex", "label": "Sex (the formulas differ)", "type": "select", "default": "female", + "options": [["female", "Female"], ["male", "Male"]]}, + {"key": "birth_date", "label": "Birth date (YYYY-MM-DD)", "type": "text", "default": "", "max": 10, + "pattern": r"\d{4}-\d{2}-\d{2}", "pattern_help": "Like 1994-03-21.", + "help": "For the age in the formulas."}, + {"key": "height", "label": "Height (cm)", "type": "number", "default": 0, "min": 0, "max": 250, + "help": "Adults: set once. 0 = not set."}, + {"key": "max_hr", "label": "Maximum heart rate (bpm)", "type": "number", "default": 0, "min": 0, "max": 230, + "integer": True, "help": "For the workout zones. 0 = estimate from age (208 − 0.7 × age)."}, + {"key": "resting_hr", "label": "Resting heart rate (bpm)", "type": "number", "default": 0, "min": 0, "max": 120, + "integer": True, "help": "0 = from the watch data (median of the daily lows, last 90 days)."}, + {"key": "zones", "label": "Heart-rate zones", "type": "select", "default": "hrr", + "options": [["hrr", "% of heart-rate reserve (Karvonen) — uses resting heart rate"], + ["max", "% of max heart rate — like Mi Fitness"]]}, + {"key": "activity_level", "label": "How much you exercise", "type": "select", "default": "auto", + "options": calc.ACTIVITY_LEVELS, + "help": "Only used when there are fewer than 2 brisk GPS walks to work out your fitness (VO₂max) from. " + "Automatic counts your workouts of the last 12 weeks."}, + {"key": "vo2max", "label": "VO₂max (ml/kg/min)", "type": "number", "default": 0, "min": 0, "max": 90, + "help": "From a fitness test, if you have one. 0 = from your brisk GPS walks (speed vs heart rate), " + "else estimated from age, sex, BMI and how much you exercise. Workout calories scale with it."}, + {"key": "sleep_goal", "label": "Sleep goal (hours)", "type": "number", "default": 8, "min": 5, "max": 11}, + {"key": "timezone", "label": "Time zone of the band's data", "type": "text", "default": "", "max": 60, + "pattern": "[A-Za-z]+(/[A-Za-z0-9_+-]+){0,2}|UTC", "pattern_help": "A zone name like Europe/Berlin.", + "help": "Empty = the phone's (the app sends it with the band's data), else this computer's (timedatectl). " + "Otherwise a name like Europe/Berlin or America/New_York."}, + {"key": "gb_export", "label": "Gadgetbridge export (folder or file on the Pi)", "type": "text", "default": "", + "max": 300, "help": "Where Syncthing puts Gadgetbridge's database export, e.g. /home/pi/Sync/gadgetbridge. " + "A newer export is imported by itself within ~5 minutes. Empty = off."}, + ], + # what syncs between devices (sync.py / syncdb.py): what you enter — measurements (one a day), + # blood pressure / oxygen readings (an import's reading by its minute), the tab layouts. The + # watch data stays here (a summary for the app comes later). + "sync": {"health.db": { + "measure": {"key": "'measure:' || NEW.day"}, + "vital": {"key": "CASE WHEN NEW.source IS NOT NULL THEN 'vital:' || NEW.t END"}, + "layout": {"key": "'layout:' || NEW.owner || ':' || NEW.tab"}, + "summary": {"key": "NEW.k"}, # the app's Health pages (summary.py) — written here only + }, "gbrelay.db": gb.RELAY_SYNC}, # the band's rows from the phone app (gb.import_relay) — written there only +} + + +def validate_settings(sec): + v = sec.get("birth_date") + if v: + try: + d = date.fromisoformat(v) + except ValueError: + return "birth_date", "Not a real date." + if not date(1900, 1, 1) <= d <= date.today(): + return "birth_date", "Must be in the past." + if sec.get("height") and sec["height"] < 50: + return "height", "In centimetres — at least 50 (or 0 = not set)." + return None + + +def register(ctx): + bp = ctx.blueprint("/health") + ctx.section_tabs([("/health", "Overview"), ("/health/body", "Body"), ("/health/sleep", "Sleep"), + ("/health/heart", "Heart"), ("/health/activity", "Activity")], # + Cycle when it's on (pluginhost) + more=[("Edit layout", "#edit", True), ("See report page", "/health/report")]) + ctx.warm("/health", "/health/body", "/health/sleep", "/health/heart", "/health/activity", # kept built in + *(f"/health/{p}?r={r}" for p in ("sleep", "heart", "activity") for r in ("3m", "1y"))) # the background + ctx.nav("Health", "/health") + here = os.path.dirname(os.path.abspath(__file__)) + + @bp.context_processor + def asset_version(): # cache-buster for health.css / .js + st = os.path.join(here, "static") + return {"asset_v": "%x" % int(max(os.path.getmtime(os.path.join(st, f)) for f in os.listdir(st)))} + + def con(): + return closing(db.connect(ctx.data_path("health.db"))) + + # Reads kept in memory per database version (any write — a measurement, an import — + # changes the file, so the next request reads afresh). The same list objects come back + # each time, which lets watch.enriched() remember its workout calculations too. + reads = {"version": None, "vals": {}} + + def read(c, name, *args, **kw): + v = ctx.data_version("health.db") + if reads["version"] != v: + reads.update(version=v, vals={}) + key = (name, args, tuple(sorted(kw.items()))) + if key not in reads["vals"]: + if len(reads["vals"]) > 80: # range reads (samples, hourly steps) pile up + reads["vals"] = {k: x for k, x in reads["vals"].items() if not k[1]} + reads["vals"][key] = getattr(db, name)(c, *args, **kw) + return reads["vals"][key] + + def body(): + if not ctx.same_origin(): + abort(403) + return request.get_json(silent=True) or {} + + @bp.context_processor + def add_form(): # the + dialog on every page (_parts.adder) + with con() as c: + return {"add_form": views.form_data(read(c, "all_rows")), "fields": db.FIELDS} + + # ---- the range + grouping every tab shares: ?r= / ?g= pick them (a cookie keeps them for + # the other tabs and later visits); cached pages are keyed by them too + def shared_range(): + return (request.args.get("r") or request.cookies.get("hl_r") or views.DEFAULT_RANGE, + request.args.get("g") or request.cookies.get("hl_g") or "") + + @bp.after_request + def keep_range(resp): + for k in ("r", "g"): + val = request.args.get(k) + if val and len(val) <= 4: + resp.set_cookie("hl_" + k, val, max_age=365 * 86400, path="/health", samesite="Lax") + return resp + + def source(c, src, r, g): + """One page's view, for the blocks that need it (blocks.py `src`).""" + if src == "overview": + hr = read(c, "hr_rows", hist=True, since=date.today() - timedelta(days=7)) + wks = read(c, "exercises") + return watch.overview(read(c, "nights"), lambda d: read(c, "stages", d), wks, + lambda a, z: read(c, "hr_samples", a, z), read(c, "steps_days"), + watch.with_resting(ctx.settings, hr, wks), read(c, "weights"), hr) + if src == "body": + v = views.page(read(c, "all_rows"), ctx.settings, r) + try: # the measurements table: MEASURE_PAGE a page (?mp=N) + mp = max(1, int(request.args.get("mp", 1))) + except ValueError: + mp = 1 + v["mpages"] = max(1, -(-len(v["rows"]) // MEASURE_PAGE)) + v["mp"] = min(mp, v["mpages"]) + v["mrows"] = v["rows"][(v["mp"] - 1) * MEASURE_PAGE:v["mp"] * MEASURE_PAGE] + return v + if src == "sleep": + try: + day = date.fromisoformat(request.args.get("d", "")) + except ValueError: + day = None + return watch.sleep_page(read(c, "nights"), read(c, "naps"), lambda d: read(c, "stages", d), + read(c, "exercises"), ctx.settings, r, g, day) + if src == "heart": + pg = {} + for k in ("bp", "op"): # the two readings tables' pages + try: + pg[k] = int(request.args.get(k, 1)) + except ValueError: + pg[k] = 1 + return watch.heart_page(read(c, "hr_rows"), r, g, lambda a, z: read(c, "hr_samples", a, z), + vitals=read(c, "vitals"), bp_page=pg["bp"], ox_page=pg["op"]) + if src == "activity": + days = views.RANGES.get(r, views.RANGES[views.DEFAULT_RANGE])[1] or 3650 + hr = read(c, "hr_rows", hist=True, since=date.today() - timedelta(days=max(days, 7) + 7)) + wks = read(c, "exercises") + return watch.activity_page(read(c, "steps_days"), wks, watch.with_resting(ctx.settings, hr, wks), + read(c, "weights"), r, g, lambda a, z: read(c, "steps_hourly", a, z), hr) + raise KeyError(src) + + def energy(): # for the food diary's calorie target (ctx.ask) + with con() as c: + hr = read(c, "hr_rows", hist=True, since=date.today() - timedelta(days=100)) + wks = read(c, "exercises") + return watch.energy_summary(read(c, "steps_days"), wks, watch.with_resting(ctx.settings, hr, wks), + read(c, "weights")) + ctx.provide("energy", energy) + + def day(d): # one day's steps, workouts, energy — the food diary's day view + with con() as c: + hr = read(c, "hr_rows", hist=True, since=date.today() - timedelta(days=100)) + wks = read(c, "exercises") + return watch.day_activity(d, read(c, "steps_days"), wks, watch.with_resting(ctx.settings, hr, wks), + read(c, "weights")) + ctx.provide("day", day) + + # ---- Gadgetbridge: a newer database export in the synced folder is imported by itself (gb.py) + gb_lock = threading.Lock() + + def zone(): + """The band's time zone: Settings ▸ Health, else the phone's (the app's relay), else this computer's.""" + return ctx.settings.get("timezone") or gb.relay_tz(ctx.data_path("gbrelay.db")) + + def gb_once(force=False): + with gb_lock: + mi.set_tz(zone()) + return gb.import_if_new(ctx.settings.get("gb_export"), ctx.data_path("health.db"), + os.path.dirname(ctx.data_path("health.db")), force) + + def gb_watch(_ctx): + while True: + if ctx.settings.get("gb_export") and ctx.enabled: + try: + res = gb_once() + if res: + print(f"health: Gadgetbridge import {res}", flush=True) + except Exception as e: + print(f"health: Gadgetbridge import failed: {e}", flush=True) + time.sleep(gb.CHECK_EVERY) + ctx.worker(gb_watch) + + # ---- the phone app's relay of the band (gbrelay.db, filled by the sync): imported once it has + # stayed unchanged for gb.RELAY_SETTLE seconds after a change + relay = ctx.data_path("gbrelay.db") + gb.relay_create(relay) + + relay_state = {"done": ctx.data_version("gbrelay.db")} + + def relay_once(): + """Import the relay if it changed since the last import → the result (None = nothing new).""" + with gb_lock: + v = ctx.data_version("gbrelay.db") + if v == relay_state["done"]: + return None + mi.set_tz(zone()) + res = gb.import_relay(relay, ctx.data_path("health.db")) + relay_state["done"] = v + print(f"health: Gadgetbridge (app relay) import {res}", flush=True) + return res + + def relay_watch(_ctx): + seen = ctx.data_version("gbrelay.db") + while True: + time.sleep(gb.RELAY_SETTLE) + try: + v = ctx.data_version("gbrelay.db") + if ctx.enabled and v == seen: + relay_once() + seen = v + except Exception as e: + print(f"health: Gadgetbridge (app relay) import failed: {e}", flush=True) + ctx.worker(relay_watch) + + # ---- the phone app's Health summaries (summary.py): rewritten when health.db, the settings or the + # day changed (checked every 10 minutes) + sums = {"key": None, "last": None} + + sum_lock = threading.Lock() + + def summaries_once(): + """Rewrite the summaries if their inputs changed → True when something was written.""" + if not ctx.primary(): # the other dashboard makes them; they come synced + return False + with sum_lock: + diet = ctx.ask("food", "diet") # Settings ▸ Food, for the app (None: food is off) + key = (ctx.data_version("health.db"), repr(sorted(ctx.settings.items())) + repr(diet), date.today()) + if key == sums["key"]: + return False + with con() as c: + t0 = time.time() + res = summary.refresh(c, ctx.settings, diet=diet) + # remember the version *with* our own writes, so they don't trigger another round + sums.update(key=(ctx.data_version("health.db"), key[1], key[2]), last=dict(res, secs=round(time.time() - t0, 1))) + if res["written"] or res["deleted"]: + print(f"health: summaries {sums['last']}", flush=True) + return bool(res["written"] or res["deleted"]) + + def summary_watch(_ctx): + time.sleep(60) # let the rest start first + while True: + try: + if ctx.enabled: + summaries_once() + except Exception as e: + print(f"health: summaries failed: {e}", flush=True) + time.sleep(600) + ctx.worker(summary_watch) + + # the phone app's "sync now" (sync.kick, after a pull): the relay and the summaries at once, not on their timers + def after_kick(): + if not ctx.enabled: + return False + relay_once() + return summaries_once() + ctx.on_sync(after_kick) + ctx.settings_panel("health/_settings.html", + lambda: {"gb": gb.status(ctx.data_path("health.db"), ctx.settings.get("gb_export"))}) + + @bp.route("/api/gb/import", methods=["POST"]) + def api_gb_import(): # Settings ▸ Health ▸ "Import now" (also when nothing changed) + body() + if not ctx.settings.get("gb_export"): + return jsonify(error="Set the Gadgetbridge export folder first."), 400 + try: + res = gb_once(force=True) + except Exception as e: + return jsonify(error=str(e)), 500 + return jsonify(ok=True, result=res) if res else (jsonify(error="No export found in that folder."), 404) + ctx.provide("version", lambda: (ctx.data_version("health.db"), repr(sorted(ctx.settings.items())))) + + HOME = {"overview": {"body"}, "body": {"body"}, "sleep": {"sleep"}, "heart": {"heart"}, "activity": {"activity"}} + TAB_LABELS = {"overview": "Overview", "body": "Body", "sleep": "Sleep", "heart": "Heart", "activity": "Activity"} + + def guests(): + """Blocks of the plugins living inside Health now (pluginhost inside(…, blocks=)): {id: block}.""" + return {b["id"]: dict(b, src=None, pin=False) for b in ctx.section()["blocks"]} + + def cache_key(): # pages are cached per range + the guests' data + return shared_range(), tuple(str(b["version"]()) for b in guests().values() if b.get("version")) + + def page_v(V, r, g): + """What the shared macros read as `v`: today, the shared range, the body view's parts.""" + rng, grain, a, grains = watch.period(r, g, date.today()) + body = V.get("body") or {} + return {"today": date.today(), "range": rng, "ranges": views.RANGES, "grain": grain, "grains": grains, + "body": body.get("body", {}), "prof": body.get("prof")} + + def tab_page(tab): + """A tab drawn from its layout: only the views its blocks need are computed.""" + r, g = shared_range() + extra = guests() + B = {**blocks.BLOCKS, **extra} + with con() as c: + items = blocks.clean(tab, read(c, "layout", blocks.OWNER, tab) or blocks.default(tab, extra), extra) + srcs = HOME[tab] | {B[i["id"]]["src"] for i in items if B[i["id"]]["src"]} + V = {src: source(c, src, r, g) for src in sorted(srcs)} + labels = dict(TAB_LABELS, **{b["tab"]: b["tab_label"] for b in extra.values()}) + return render_template("health/tab.html", tab=tab, V=V, v=page_v(V, r, g), items=items, blocks=blocks, B=B, + catalog=blocks.catalog(tab, extra), tab_labels=labels, vsources=db.VITAL_SOURCES, + page="health") + + @bp.route("/", strict_slashes=False) + @ctx.cached_page("health.db", extra=cache_key) + def index(): + return tab_page("overview") + + @bp.route("/body") + @ctx.cached_page("health.db", extra=cache_key) + def body_fat(): + return tab_page("body") + + @bp.route("/sleep") + @ctx.cached_page("health.db", extra=cache_key) + def sleep(): + return tab_page("sleep") + + @bp.route("/heart") + @ctx.cached_page("health.db", extra=cache_key) + def heart(): + return tab_page("heart") + + @bp.route("/activity") + @ctx.cached_page("health.db", extra=cache_key) + def activity(): + return tab_page("activity") + + @bp.route("/api/block") + @ctx.cached_page("health.db", extra=cache_key) + def api_block(): # ?id=&w= — one block drawn alone (edit mode: an added block fills in) + extra = guests() + B = {**blocks.BLOCKS, **extra} + bid = request.args.get("id", "") + if bid not in B: + abort(404) + it = blocks.clean("overview", [{"id": bid, "w": request.args.get("w")}], extra)[0] + r, g = shared_range() + with con() as c: + V = {src: source(c, src, r, g) for src in sorted({"body", B[bid]["src"]} - {None})} + return render_template("health/block.html", it=it, V=V, v=page_v(V, r, g), blocks=blocks, B=B, + tab="overview", vsources=db.VITAL_SOURCES, page="health") + + @bp.route("/api/layout", methods=["POST"]) + def api_layout(): # {tab, items: [{id, w}]} — a tab's blocks in order (blocks.clean drops the rest) + d = body() + tab = d.get("tab") + if tab not in blocks.TABS: + return jsonify(error="Unknown tab."), 400 + with con() as c: + db.save_layout(c, blocks.OWNER, tab, blocks.clean(tab, d.get("items"), guests())) + return jsonify(ok=True) + + @bp.route("/api/layout/reset", methods=["POST"]) + def api_layout_reset(): # {tab} — back to blocks.DEFAULTS + tab = body().get("tab") + if tab in blocks.TABS: + with con() as c: + db.reset_layout(c, blocks.OWNER, tab) + return jsonify(ok=True) + + @bp.route("/report") # not page-cached: the cycle part has its own data + def report_page(): + with con() as c: + hr = read(c, "hr_rows") + wks = read(c, "exercises") + s = watch.with_resting(ctx.settings, hr, wks) + v = watch.report(read(c, "all_rows"), s, read(c, "nights"), read(c, "naps"), wks, read(c, "steps_days"), + hr, read(c, "vitals"), read(c, "weights"), request.args.get("r")) + days = watch.REPORT_RANGES[v["range"]][1] + return render_template("health/report.html", v=v, page="health", tab="report", + guests=[fn(days) for fn in ctx.section()["reports"]]) + + @bp.route("/workout/") + @ctx.cached_page("health.db") + def workout(eid): + with con() as c: + w = db.exercise(c, eid) + if not w: + abort(404) + ids = [r[0] for r in c.execute("SELECT id FROM exercise ORDER BY start")] + i = ids.index(eid) + wks = read(c, "exercises") + v = watch.workout_page(w, read(c, "hr_samples", w["start"], w["end"]), + watch.with_resting(ctx.settings, read(c, "hr_rows"), wks), read(c, "weights"), + (ids[i - 1] if i else None, ids[i + 1] if i + 1 < len(ids) else None), wks) + return render_template("health/workout.html", v=v, page="health", tab="activity") + + @bp.route("/export.csv") + def export_csv(): + with con() as c: + rows = db.all_rows(c) + buf = io.StringIO() + w = csv.writer(buf) + w.writerow(["date", *(f"{l} ({u})" for l, u, *_ in db.FIELDS.values()), "note"]) + for r in rows: + w.writerow([r["day"].isoformat(), *("" if r[k] is None else f"{r[k]:g}" for k in db.FIELDS), r["note"]]) + return Response("" + buf.getvalue(), mimetype="text/csv", # BOM: Excel / LibreOffice read UTF-8 + headers={"Content-Disposition": f'attachment; filename="health-{date.today()}.csv"'}) + + @bp.route("/api/measure", methods=["POST"]) + def api_measure(): # {day, was?, …, note} — replaces that day's row + d = body() + with con() as c: + try: + db.save(c, d) + except db.Invalid as e: + return jsonify(error=str(e), field=e.field), 400 + return jsonify(ok=True) + + @bp.route("/api/measure/delete", methods=["POST"]) + def api_delete(): + d = body() + with con() as c: + try: + db.delete(c, d.get("day")) + except db.Invalid as e: + return jsonify(error=str(e), field=e.field), 400 + return jsonify(ok=True) + + @bp.route("/api/vital", methods=["POST"]) + def api_vital(): # {id?, kind: bp | ox, day, time, sys + dia | spo2, note} — one reading + d = body() + with con() as c: + try: + return jsonify(id=db.save_vital(c, d)) + except db.Invalid as e: + return jsonify(error=str(e), field=e.field), 400 + + @bp.route("/api/vital/delete", methods=["POST"]) + def api_vital_delete(): + d = body() + with con() as c: + db.delete_vital(c, d.get("id")) + return jsonify(ok=True) diff --git a/dashboard/plugins/health/blocks.py b/dashboard/plugins/health/blocks.py new file mode 100644 index 0000000..2924580 --- /dev/null +++ b/dashboard/plugins/health/blocks.py @@ -0,0 +1,123 @@ +"""The building blocks of the health pages and their layouts. + +Every tile (a small cell) and card (a chart, a table) is a block: an id, the tab it lives on, +its kind, a label (the Overview's add picker), the data it needs (`src`: which page's view — +computed only when a block on the page asks for it) and its default width. Each block is a +macro of the same name in templates/health/_blocks.html (dots → underscores). + +A tab's layout = an ordered list of {"id", "w"}: kept per person and tab in the `layout` +table (db.py), else DEFAULTS. Tiles and cards are laid out apart (tiles first, in their own +row); widths are % of the row: tiles TILE_W, cards CARD_W (a 12-column grid). Overview may +hold any block of any tab; the other tabs only their own (reordered, resized). +""" + +TABS = ("overview", "body", "sleep", "heart", "activity") +TILE_W = (10, 15, 20, 25, 33) +CARD_W = (33, 50, 66, 100) +OWNER = "me" # whose layout: one person for now — a household member's login later + +# id: (tab, kind, label, src, default width) +_B = [ + ("body.weight", "body", "tile", "Weight", "body", 25), + ("body.bmi", "body", "tile", "BMI", "body", 25), + ("body.waist", "body", "tile", "Waist", "body", 25), + ("body.fat", "body", "tile", "Body fat", "body", 25), + ("body.charts", "body", "card", "Weight / waist / BMI / body fat chart", "body", 100), + ("body.fat_table", "body", "card", "Body fat by formula", "body", 50), + ("body.ratios", "body", "card", "Ratios & energy", "body", 50), + ("body.measurements", "body", "card", "Measurements", "body", 50), + + ("sleep.last_score", "sleep", "tile", "Sleep score, last night", "overview", 20), + ("sleep.last_night", "sleep", "card", "Last night", "overview", 50), + ("sleep.asleep", "sleep", "tile", "Asleep, average", "sleep", 25), + ("sleep.deep", "sleep", "tile", "Deep sleep", "sleep", 25), + ("sleep.score", "sleep", "tile", "Sleep score, average", "sleep", 25), + ("sleep.times", "sleep", "tile", "Usual sleep times", "sleep", 25), + ("sleep.stages", "sleep", "card", "Sleep stages", "sleep", 33), + ("sleep.window", "sleep", "card", "Bedtime → wake-up", "sleep", 33), + ("sleep.score_chart", "sleep", "card", "Sleep score chart", "sleep", 33), + ("sleep.findings", "sleep", "card", "What stands out (sleep)", "sleep", 50), + ("sleep.weekday", "sleep", "card", "Sleep by weekday", "sleep", 50), + + ("heart.resting", "heart", "tile", "Resting heart rate", "heart", 20), + ("heart.lowest", "heart", "tile", "Lowest heart rate, 30 days", "heart", 20), + ("heart.highest", "heart", "tile", "Highest heart rate, 30 days", "heart", 20), + ("heart.bp", "heart", "tile", "Blood pressure, latest", "heart", 20), + ("heart.ox", "heart", "tile", "Blood oxygen, latest", "heart", 20), + ("heart.chart", "heart", "card", "Heart rate chart", "heart", 100), + ("heart.bp_card", "heart", "card", "Blood pressure", "heart", 50), + ("heart.ox_card", "heart", "card", "Blood oxygen", "heart", 50), + + ("act.last_workout", "activity", "card", "Last workout", "overview", 50), + ("act.steps", "activity", "tile", "Steps", "activity", 20), + ("act.energy", "activity", "tile", "Energy (estimate)", "activity", 20), + ("act.workouts", "activity", "tile", "Workouts", "activity", 20), + ("act.fitness", "activity", "tile", "Fitness · form", "activity", 20), + ("act.vitality", "activity", "tile", "Vitality", "activity", 20), + ("act.steps_chart", "activity", "card", "Steps chart", "activity", 33), + ("act.energy_chart", "activity", "card", "Energy chart", "activity", 33), + ("act.workout_time", "activity", "card", "Workout time", "activity", 33), + ("act.training", "activity", "card", "Training (fitness / fatigue / form)", "activity", 50), + ("act.vitality_chart", "activity", "card", "Vitality chart", "activity", 50), + ("act.workouts_list", "activity", "card", "Workouts list", "activity", 100), +] +# tiles with a hover explanation (.hl-pin); shown on another tab than their own, a tile links +# to its tab (tab.html) +HREF = {} +PIN = {"act.energy", "act.fitness", "act.vitality"} +BLOCKS = {i: {"id": i, "tab": t, "kind": k, "label": l, "src": s, "w": w, "macro": i.replace(".", "_"), + "href": HREF.get(i), "pin": i in PIN} + for i, t, k, l, s, w in _B} +# Overview has no blocks of its own: it's put together from the other tabs' (so adding +# "everything" never doubles one); the rest show their own, except the "last night / last +# workout" ones (Sleep has its night card on top; they're for Overview) +FOR_OVERVIEW = {"sleep.last_score", "sleep.last_night", "act.last_workout"} +DEFAULTS = {t: [{"id": b["id"], "w": b["w"]} for b in BLOCKS.values() if b["tab"] == t and b["id"] not in FOR_OVERVIEW] + for t in TABS if t != "overview"} +DEFAULTS["overview"] = [{"id": i, "w": w} for i, w in ( + ("act.workouts", 20), ("act.steps", 20), ("body.bmi", 20), ("act.fitness", 20), ("sleep.last_score", 20), + ("sleep.last_night", 50), ("act.last_workout", 50))] +GUEST_DEFAULT = ("cycle.card", "food.card") # a guest's block on the default Overview (when it's on) +# blocks that were Overview's own once (saved layouts still name them) +ALIASES = {"ov.workouts": "act.workouts", "ov.steps": "act.steps", "ov.bmi": "body.bmi", "ov.fitness": "act.fitness", + "ov.vitality": "act.vitality", "ov.sleep_score": "sleep.last_score", "ov.last_night": "sleep.last_night", + "ov.last_workout": "act.last_workout"} + + +def allowed(tab, bid, extra=None): + """extra = the guests' blocks ({id: block}, Overview only).""" + b = BLOCKS.get(bid) or (extra or {}).get(bid) + return bool(b) and (tab == "overview" or b["tab"] == tab) + + +def clean(tab, items, extra=None): + """A layout as sent / stored → only known blocks this tab may hold, once each, valid widths + (old ids → their new ones, ALIASES).""" + out, seen = [], set() + for it in items if isinstance(items, list) else []: + bid = it.get("id") if isinstance(it, dict) else None + bid = ALIASES.get(bid, bid) + if not allowed(tab, bid, extra) or bid in seen: + continue + b = BLOCKS.get(bid) or extra[bid] + ws = TILE_W if b["kind"] == "tile" else CARD_W + try: + w = int(it.get("w")) + except (TypeError, ValueError): + w = b["w"] + out.append({"id": bid, "w": w if w in ws else b["w"]}) + seen.add(bid) + return out + + +def catalog(tab, extra=None): + """What the add picker offers on `tab` (Overview: every block of every tab + the guests').""" + return [{k: b[k] for k in ("id", "tab", "kind", "label", "w")} + for b in list(BLOCKS.values()) + list((extra or {}).values()) if allowed(tab, b["id"], extra)] + + +def default(tab, extra=None): + out = list(DEFAULTS[tab]) + if tab == "overview": + out += [{"id": i, "w": extra[i]["w"]} for i in GUEST_DEFAULT if i in (extra or {})] + return out diff --git a/dashboard/plugins/health/calc.py b/dashboard/plugins/health/calc.py new file mode 100644 index 0000000..4601586 --- /dev/null +++ b/dashboard/plugins/health/calc.py @@ -0,0 +1,426 @@ +"""Body formulas: BMI, ratios, body fat by several published formulas, BMR. +Body fat uses tape-measure formulas (+ a scale's reading), not BMI-based ones. + +All take metric values (kg, cm, mm), `sex` "female" / "male", `age` in years. Each fat +formula is an estimate from a population study — they disagree by several points; the +spread between them is part of the answer. A formula that lacks an input returns None. +""" +from datetime import timedelta +from math import exp, log10 + +FEMALE = "female" + + +def bmi(weight, height): + if not (weight and height): + return None + return weight / (height / 100) ** 2 + + +BMI_CLASSES = [(18.5, "underweight"), (25, "normal"), (30, "overweight"), + (35, "obese (class I)"), (40, "obese (class II)"), (999, "obese (class III)")] + + +def bmi_class(b): + return next(name for top, name in BMI_CLASSES if b < top) if b else None + + +def healthy_weight(height): + """Weight range for BMI 18.5–24.9 at this height.""" + if not height: + return None + m2 = (height / 100) ** 2 + return 18.5 * m2, 24.9 * m2 + + +def whtr(waist, height): # waist-to-height ratio + return waist / height if waist and height else None + + +def whtr_class(r): + if r is None: + return None + return "low" if r < 0.4 else "healthy" if r < 0.5 else "raised" if r < 0.6 else "high" + + +def whr(waist, hip): # waist-to-hip ratio + return waist / hip if waist and hip else None + + +def whr_class(r, sex): + if r is None: + return None + return "raised (WHO)" if r >= (0.85 if sex == FEMALE else 0.90) else "healthy" + + +def waist_class(waist, sex): # WHO waist cut-offs (European) + if not waist: + return None + a, b = (80, 88) if sex == FEMALE else (94, 102) + return "healthy" if waist < a else "raised" if waist < b else "high" + + +# ---- body fat % ---------------------------------------------------------------------- + +def navy(m, height, sex, age): + """U.S. Navy circumference method (Hodgdon & Beckett 1984). Women need the hips.""" + w, n, h = m.get("waist"), m.get("neck"), m.get("hip") + if not (w and n and height): + return None + if sex == FEMALE: + if not h or w + h - n <= 0: + return None + return 495 / (1.29579 - 0.35004 * log10(w + h - n) + 0.22100 * log10(height)) - 450 + if w - n <= 0: + return None + return 495 / (1.0324 - 0.19077 * log10(w - n) + 0.15456 * log10(height)) - 450 + + +def rfm(m, height, sex, age): + """Relative fat mass (Woolcott & Bergman 2018): height and waist only.""" + w = m.get("waist") + if not (w and height): + return None + return (76 if sex == FEMALE else 64) - 20 * height / w + + +def ymca(m, height, sex, age): + """YMCA: waist and weight (in inches / pounds inside).""" + w, kg = m.get("waist"), m.get("weight") + if not (w and kg): + return None + lb, inch = kg * 2.20462, w / 2.54 + return (4.15 * inch - 0.082 * lb - (76.76 if sex == FEMALE else 98.42)) / lb * 100 + + +def scale(m, height, sex, age): + return m.get("fat_scale") + + +# key, name, needs (field keys; "height" = settings), function, one-line note. Left out on +# purpose: BMI-based formulas (CUN-BAE, Deurenberg — muscle reads as fat) and skinfolds. +FAT = [ + ("navy", "U.S. Navy", ("waist", "neck", "hip?", "height"), navy, + "tape: waist, neck, hips · about ±3–4 % in studies"), + ("rfm", "Relative fat mass", ("waist", "height"), rfm, "waist and height · checked against DEXA scans"), + ("ymca", "YMCA", ("waist", "weight"), ymca, "waist and weight · simple, less tested in women"), + ("scale", "Your scale", ("fat_scale",), scale, "bioimpedance · shifts with water, time of day"), +] + + +def fat_all(m, height, sex, age): + """[{key, name, value, needs, note}] — value None when inputs are missing (needs = + what's missing).""" + out = [] + for key, name, needs, fn, note in FAT: + v = fn(m, height, sex, age) + if v is not None and not 2 <= v <= 75: # outside anything plausible: bad inputs + v = None + missing = [] + if v is None: + for n in needs: + if n == "hip?": + if sex == FEMALE and not m.get("hip"): + missing.append("hip") + elif n == "height": + height or missing.append("height") + elif not m.get(n): + missing.append(n) + out.append({"key": key, "name": name, "value": v, "missing": missing, "note": note}) + return out + + +# Healthy body-fat ranges by sex and age (Gallagher et al. 2000, Am J Clin Nutr — derived +# from BMI 18.5 / 25 / 30 against measured fat): (age from, to, healthy from, high from, +# very high from). Under 20 there are no adult ranges; 80+ uses the last row. +FAT_RANGES = { + FEMALE: [(20, 39, 21, 33, 39), (40, 59, 23, 34, 40), (60, 79, 24, 36, 42)], + "male": [(20, 39, 8, 20, 25), (40, 59, 11, 22, 28), (60, 79, 13, 25, 30)], +} +FAT_NAMES = ("low", "healthy", "high", "very high") + + +def _sexkey(sex): + return FEMALE if sex == FEMALE else "male" + + +def fat_band(sex, age): + """This person's row of FAT_RANGES, or None (no age / under 20).""" + if not age or age < 20: + return None + rows = FAT_RANGES[_sexkey(sex)] + return next((r for r in rows if r[0] <= age <= r[1]), rows[-1]) + + +def fat_class(v, sex, age): + band = fat_band(sex, age) + if v is None or not band: + return None + return FAT_NAMES[sum(v >= x for x in band[2:])] + + +# Desirable BMI by age (US National Research Council 1989; the same for women and men — +# WHO's 18.5–25 applies to all adults regardless of sex or age): (age from, to, lo, hi). +BMI_AGE = [(19, 24, 19, 24), (25, 34, 20, 25), (35, 44, 21, 26), (45, 54, 22, 27), + (55, 64, 23, 28), (65, 200, 24, 29)] + + +def bmi_age_band(age): + if not age or age < 19: + return None + return next(r for r in BMI_AGE if r[0] <= age <= r[1]) + + +# ---- energy -------------------------------------------------------------------------- + +def bmr_mifflin(weight, height, sex, age): + """Mifflin–St Jeor resting energy, kcal / day.""" + if not (weight and height and age): + return None + return 10 * weight + 6.25 * height - 5 * age + (-161 if sex == FEMALE else 5) + + +def bmr_katch(weight, fat): + """Katch–McArdle: from lean mass, so it needs a body-fat value.""" + if not (weight and fat): + return None + return 370 + 21.6 * weight * (1 - fat / 100) + + +# ---- workouts: heart-rate zones + calories -------------------------------------------- + +# Health Connect exercise types as Mi Fitness writes them (worked out by matching the +# export against the Mi Fitness screens: 7 = boxing, 27 = pilates, 53 = walk, 57 = yoga; +# 4 had a 876 m GPS route in 3 min → cycling). Unknown ones show as "Workout (type N)". +EXERCISE_TYPES = {7: "Boxing", 27: "Pilates", 53: "Walking", 57: "Yoga", 4: "Cycling", 59: "Climbing machine"} +# Mi Fitness sport categories → names +MI_SPORTS = {"boxing": "Boxing", "free_training": "Free training", "yoga": "Yoga", "walking": "Walking", + "indoor_fitness": "Indoor fitness", "pilates": "Pilates", "climbing_machine": "Climbing machine", + "outdoor_riding": "Cycling", "parkour": "Parkour", "outdoor_running": "Running", "indoor_running": "Treadmill"} + + +def exercise_name(t, name=None): + return name or EXERCISE_TYPES.get(t, f"Workout (type {t})") + + +def max_hr(age, setting=None): + """Maximum heart rate: the setting if given, else Tanaka (208 − 0.7 × age) — + closer for adults than 220 − age.""" + if setting: + return int(setting) + return round(208 - 0.7 * age) if age else 190 + + +# (name, from %, colour class) — the usual 5 zones. The % is of max heart rate ("max", how +# Mi Fitness does it) or of heart-rate reserve ("hrr", Karvonen: resting + % × (max − resting), +# the ACSM way — it accounts for your own resting heart rate). +ZONES = [("Warm-up", 50, "z1"), ("Fat burn", 60, "z2"), ("Aerobic", 70, "z3"), + ("Anaerobic", 80, "z4"), ("Maximum", 90, "z5")] +ZONE_METHODS = {"hrr": "% of heart-rate reserve (Karvonen)", "max": "% of max heart rate (like Mi Fitness)"} + + +def zone_bounds(hrmax, rest=None, method="hrr"): + """Lower bound (bpm) of each zone in ZONES.""" + if method == "hrr" and rest: + return [rest + p / 100 * (hrmax - rest) for _, p, _ in ZONES] + return [hrmax * p / 100 for _, p, _ in ZONES] + + +def zone_of(bpm, bounds): + """Index into ZONES, or -1 below the first (resting).""" + z = -1 + for i, lo in enumerate(bounds): + if bpm >= lo: + z = i + return z + + +def zones(hist, bounds): + """Seconds per zone from a {bpm: seconds} histogram: [below, z1 … z5].""" + out = [0] * (len(ZONES) + 1) + for bpm, sec in hist.items(): + out[zone_of(bpm, bounds) + 1] += sec + return out + + +# Activity level for the VO2max estimate (Jackson et al. 1990, "PA-R" 0–7) +ACTIVITY_LEVELS = [["auto", "Automatic — from your workouts (last 12 weeks)"], [1, "Little or no exercise"], [3, "Regular moderate activity (walks, gardening)"], + [4, "Hard exercise, under 30 min a week"], [5, "Hard exercise, 30–60 min a week"], + [6, "Hard exercise, 1–3 h a week"], [7, "Hard exercise, over 3 h a week"]] + + +def activity_level(minutes_a_week): + """Workout minutes a week → the PA-R level of ACTIVITY_LEVELS.""" + m = minutes_a_week or 0 + return 1 if m < 10 else 4 if m < 30 else 5 if m < 60 else 6 if m < 180 else 7 + + +WALK_MIN_SPEED, WALK_MIN_MINUTES = 66.7, 20 # m/min (4 km/h), minutes: a brisk, steady walk + + +def vo2max_from_walks(walks, rest, hrmax): + """VO2max from GPS walks as a submaximal test: the walk's oxygen cost is known from its + speed (ACSM: 3.5 + 0.1 × m/min, level ground), its effort from heart rate (% of heart-rate + reserve ≈ % of VO2 reserve, Swain 1997) → VO2max = 3.5 + (VO2 − 3.5) ÷ effort. Only brisk + walks (≥ 4 km/h, ≥ 20 min — stops make slow ones underestimate); median; None under 2. + walks = [(metres, minutes, average bpm)].""" + if not (rest and hrmax and hrmax > rest): + return None, 0 + est = [] + for dist, minutes, hr in walks: + if not (dist and minutes and hr) or minutes < WALK_MIN_MINUTES: + continue + speed = dist / minutes + x = (hr - rest) / (hrmax - rest) + if speed >= WALK_MIN_SPEED and 0.15 < x < 0.9: + est.append(3.5 + 0.1 * speed / x) + if len(est) < 2: + return None, len(est) + est.sort() + mid = len(est) // 2 + return (est[mid] if len(est) % 2 else (est[mid - 1] + est[mid]) / 2), len(est) + + +def vo2max_estimate(age, sex, weight, height, level): + """VO2max (ml/kg/min) without a fitness test: Jackson et al. 1990 (age, sex, BMI, + activity level). ±~5 ml/kg/min; a measured value in Settings replaces it.""" + b = bmi(weight, height) + if not (b and age): + return None + v = 56.363 + 1.921 * (level or 5) - 0.381 * age - 0.754 * b + 10.987 * (sex != FEMALE) + return max(12.0, v) + + +def workout_kcal(hist, weight, height, sex, age, hrmax, rest, vo2max): + """(active, total) kcal from a {bpm: seconds} histogram — the ACSM way: % of heart-rate + reserve ≈ % of VO2 reserve (Swain 1997), so each second costs + VO2 = 3.5 + %HRR × (VO2max − 3.5) ml/kg/min; active = the part above resting + (VO2 − 3.5), × weight × 5 kcal per litre of O2. Total = active + resting (Mifflin–St Jeor).""" + if not (weight and rest and hrmax and vo2max and hrmax > rest): + return None, None + secs = sum(hist.values()) + active = 0.0 + for bpm, sec in hist.items(): + hrr = max(0.0, min(1.0, (bpm - rest) / (hrmax - rest))) + active += hrr * (vo2max - 3.5) * weight / 1000 * 5 * sec / 60 + rest_kcal = (bmr_mifflin(weight, height, sex, age) or 1400) / 1440 * secs / 60 + return active, active + rest_kcal + + +# ---- steps ----------------------------------------------------------------------------- + +def stride(height, sex): + """Walking step length in m (≈ 41.3 % of height for women, 41.5 % for men).""" + return height / 100 * (0.413 if sex == FEMALE else 0.415) if height else 0.7 + + +def walk_vo2(speed): + """ACSM walking equation, level ground: VO2 (ml/kg/min) at speed m/min (50–100).""" + return 3.5 + 0.1 * speed + + +def steps_kcal(steps, weight, height, sex): + """Net walking energy: ≈ 0.5 kcal per kg per km (ACSM walking equation, level ground).""" + if not (steps and weight): + return 0.0 + return 0.5 * weight * steps * stride(height, sex) / 1000 + + +# ---- training load, fitness / fatigue / form, vitality, effect ---------------------------- + +def _hrr(bpm, rest, hrmax): + return max(0.0, min(1.0, (bpm - rest) / (hrmax - rest))) if hrmax and rest and hrmax > rest else 0.0 + + +def trimp(hist, rest, hrmax, sex): + """Training load of a workout: Banister's TRIMP (1991) — minutes × effort × a weight that + grows exponentially with effort (women 0.86·e^(1.67x), men 0.64·e^(1.92x), x = % of + heart-rate reserve). An easy hour ≈ 40–60, a hard one 120+.""" + k, b = (0.86, 1.67) if sex == FEMALE else (0.64, 1.92) + out = 0.0 + for bpm, sec in hist.items(): + x = _hrr(bpm, rest, hrmax) + if x > 0: + out += sec / 60 * x * k * exp(b * x) + return out + + +FITNESS_DAYS, FATIGUE_DAYS = 42, 7 # Banister impulse–response (as in TrainingPeaks CTL / ATL) + + +def fitness_fatigue(loads, a, z): + """{day: load} → [(day, fitness, fatigue, form)] for a..z: exponentially weighted + averages of daily load over 42 and 7 days; form = yesterday's fitness − fatigue.""" + kf, ka = 1 - exp(-1 / FITNESS_DAYS), 1 - exp(-1 / FATIGUE_DAYS) + f = t = 0.0 + out, d = [], a + while d <= z: + form = f - t + x = loads.get(d, 0.0) + f += (x - f) * kf + t += (x - t) * ka + out.append((d, f, t, form)) + d += timedelta(days=1) + return out + + +EFFECTS = [(0.6, "Easy"), (0.9, "Maintaining"), (1.3, "Improving"), (99, "Very hard")] + + +def effect(load, usual): + """Workout load vs your usual one (average of the previous 6 weeks' workouts).""" + if not (load and usual): + return None + r = load / usual + return next(name for top, name in EFFECTS if r < top) + + +def intensity_minutes(hist, rest, hrmax): + """(moderate, vigorous) minutes from a {bpm: seconds} histogram — moderate = 40–59 %, + vigorous = 60 %+ of heart-rate reserve (ACSM). Vitality counts vigorous twice (WHO).""" + mod = vig = 0.0 + for bpm, sec in hist.items(): + x = _hrr(bpm, rest, hrmax) + if x >= 0.6: + vig += sec / 60 + elif x >= 0.4: + mod += sec / 60 + return mod, vig + + +VITALITY_GOAL = 150 # minutes a week (moderate + 2 × vigorous), WHO + + +# ---- vitals --------------------------------------------------------------------------------- +# Blood pressure: ESC 2024 guideline categories (office readings, mmHg); a reading takes the +# higher category of its two numbers. One reading says little — the average of several, +# on different days, is what counts. +BP_CLASSES = [ # (name, systolic from, diastolic from, colour class) + ("non-elevated", 0, 0, "ok"), + ("elevated", 120, 70, "mid"), + ("hypertension", 140, 90, "high"), + ("severe hypertension", 180, 110, "vhigh"), +] + + +def bp_class(sys, dia): + """→ (name, colour class) of a blood-pressure reading, or None.""" + if not sys or not dia: + return None + pick = BP_CLASSES[0] + for c in BP_CLASSES: + if sys >= c[1] or dia >= c[2]: + pick = c + return pick[0], pick[3] + + +def spo2_class(p): + """Blood oxygen at rest: 95–100 % normal; 91–94 % low; 90 % or less very low (see a doctor). + Wrist sensors read a couple of % low now and then — a single low spot check isn't a verdict.""" + if p is None: + return None + if p >= 95: + return "normal", "ok" + if p > 90: + return "low", "mid" + return "very low", "vhigh" diff --git a/dashboard/plugins/health/db.py b/dashboard/plugins/health/db.py new file mode 100644 index 0000000..d86eb21 --- /dev/null +++ b/dashboard/plugins/health/db.py @@ -0,0 +1,412 @@ +"""Health storage: one SQLite file (dash_data/health/health.db). + +Body measurements: one `measure` row per day with whatever was measured that day (any +field may be empty). Everything derived — BMI, body fat, ratios, trends — is computed on +read (calc.py, views.py). + +Watch data (written by hc.py, the Health Connect import; every row has a `source`): +`night` (one per night, keyed by the day you woke up, with minutes per sleep stage) + +`sleep_stage` (its hypnogram) + `nap`; `hr_sample` (every heart-rate reading) + +`hr_day` (daily lowest / highest); `exercise` (workouts, with a heart-rate histogram so +zones and calories are computed on read); `steps_day` (one source per day, no doubles). + +Vitals: `vital` — one row per reading, of one kind: blood pressure (sys + dia) or blood +oxygen (spo2), typed in on the Heart page or imported (Mi Fitness / Health Connect spot checks; an import keeps one +row per minute, so the same check from both apps counts once). +""" +import os +import sqlite3 +import threading +import json +from datetime import date, datetime, timedelta, timezone + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS measure ( + day TEXT PRIMARY KEY, -- YYYY-MM-DD + note TEXT NOT NULL DEFAULT '', + updated TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS night ( + day TEXT PRIMARY KEY, -- the day you woke up + start TEXT NOT NULL, -- local 'YYYY-MM-DD HH:MM' (fell asleep) + end TEXT NOT NULL, -- woke up + asleep INTEGER NOT NULL, -- minutes (light + deep + rem; or the whole span without stages) + light INTEGER, deep INTEGER, rem INTEGER, awake INTEGER, -- minutes per stage + wakeups INTEGER, -- awake stretches inside the night + source TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS nap ( + start TEXT PRIMARY KEY, + end TEXT NOT NULL, + minutes INTEGER NOT NULL, + source TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS sleep_stage ( + day TEXT NOT NULL, -- the night's day + start TEXT NOT NULL, + end TEXT NOT NULL, + stage TEXT NOT NULL -- light / deep / rem / awake +); +CREATE INDEX IF NOT EXISTS sleep_stage_day ON sleep_stage (day); +CREATE TABLE IF NOT EXISTS hr_day ( + day TEXT PRIMARY KEY, + low INTEGER, -- bpm: lowest reading outside workouts + high INTEGER, -- highest sample + source TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS hr_sample ( + t INTEGER PRIMARY KEY, -- local time as seconds since 1970 (wall clock, no zone) + bpm INTEGER NOT NULL +); +CREATE TABLE IF NOT EXISTS exercise ( + id INTEGER PRIMARY KEY, + start TEXT NOT NULL UNIQUE, -- local 'YYYY-MM-DD HH:MM:SS' + end TEXT NOT NULL, + day TEXT NOT NULL, + type INTEGER, -- Health Connect exercise type (calc.EXERCISE_TYPES) + minutes REAL NOT NULL, + distance REAL, -- metres + kcal_device REAL, -- what the watch app said (active kcal) — for comparison + avg_hr REAL, max_hr INTEGER, + hr_hist TEXT, -- JSON {bpm: seconds} — zones + calories are computed from it + steps INTEGER, -- steps counted during it (left out of step calories) + source TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS steps_rec ( + start TEXT NOT NULL, -- local 'YYYY-MM-DD HH:MM:SS' — the day's chosen source only + end TEXT NOT NULL, + steps INTEGER NOT NULL +); +CREATE INDEX IF NOT EXISTS steps_rec_start ON steps_rec (start); +CREATE TABLE IF NOT EXISTS vital ( + id INTEGER PRIMARY KEY, + t TEXT NOT NULL, -- local 'YYYY-MM-DD HH:MM' + sys INTEGER, dia INTEGER, -- blood pressure, mmHg (both or neither) + pulse INTEGER, -- unused (not typed in: heart rate comes from the band) + spo2 REAL, -- blood oxygen, % + note TEXT NOT NULL DEFAULT '', + source TEXT -- NULL = typed here; mi_fitness / health_connect +); +CREATE INDEX IF NOT EXISTS vital_t ON vital (t); +CREATE UNIQUE INDEX IF NOT EXISTS vital_import ON vital (t) WHERE source IS NOT NULL; +CREATE TABLE IF NOT EXISTS layout ( + owner TEXT NOT NULL, -- whose (blocks.OWNER: one person for now) + tab TEXT NOT NULL, -- overview / body / sleep / heart / activity + blocks TEXT NOT NULL, -- JSON [{"id", "w"}] in order (blocks.py) + updated TEXT NOT NULL, + PRIMARY KEY (owner, tab) +); +CREATE TABLE IF NOT EXISTS steps_day ( + day TEXT PRIMARY KEY, + steps INTEGER NOT NULL, -- from ONE source per day: the band if it counted, else the best other + workout_steps INTEGER NOT NULL DEFAULT 0, -- of those, during workouts + source TEXT NOT NULL +); +CREATE TABLE IF NOT EXISTS summary ( -- for the phone app (summary.py): written here only, synced one way + k TEXT PRIMARY KEY, -- day: / night: / wk: / meta: + kind TEXT NOT NULL, + day TEXT, + data TEXT NOT NULL -- JSON +); +""" +# key: (label, unit, min, max, group). Columns are added by ALTER on first connect, so a +# new field is just a new line here. (v1 had skinfold columns sf_*; they stay in the file, unused.) +FIELDS = { + "weight": ("Weight", "kg", 20, 400, "body"), + "waist": ("Waist", "cm", 30, 250, "body"), + "hip": ("Hips", "cm", 30, 250, "body"), + "neck": ("Neck", "cm", 15, 80, "body"), + "chest": ("Chest", "cm", 40, 250, "body"), + "arm": ("Upper arm", "cm", 10, 80, "body"), + "thigh": ("Thigh", "cm", 20, 120, "body"), + "fat_scale": ("Body fat from a scale", "%", 2, 75, "body"), +} +# vital values: key -> (label, unit, min, max); a reading is one kind (VITAL_KINDS) +VITALS = { + "sys": ("Systolic", "mmHg", 60, 260), + "dia": ("Diastolic", "mmHg", 30, 160), + "spo2": ("Blood oxygen (SpO₂)", "%", 50, 100), +} +VITAL_KINDS = {"bp": ("sys", "dia"), "ox": ("spo2",)} +VITAL_SOURCES = {"mi_fitness": "Mi Fitness", "health_connect": "Health Connect"} + +# later columns of the watch tables (added by ALTER on first connect, like FIELDS) +EXTRA = {"exercise": {"name": "TEXT"}, # from Mi Fitness ("Boxing"); else from the type + "hr_day": {"rest": "INTEGER", # resting heart rate (Mi's daily value) + "hist": "TEXT"}} # JSON {bpm: seconds} of the whole day +_init_lock = threading.Lock() +_ready = set() + + +class Invalid(ValueError): + def __init__(self, field, msg): + super().__init__(msg) + self.field = field + + +def connect(path): + """A connection for one request (sqlite3 connections don't cross threads).""" + con = sqlite3.connect(path, timeout=10) + con.row_factory = sqlite3.Row + if path not in _ready: + with _init_lock: + con.executescript(SCHEMA) + have = {r[1] for r in con.execute("PRAGMA table_info(measure)")} + for col in FIELDS: + if col not in have: + con.execute(f"ALTER TABLE measure ADD COLUMN {col} REAL") + for table, cols in EXTRA.items(): + have = {r[1] for r in con.execute(f"PRAGMA table_info({table})")} + for col, typ in cols.items(): + if col not in have: + con.execute(f"ALTER TABLE {table} ADD COLUMN {col} {typ}") + con.commit() + _ready.add(path) + os.chmod(path, 0o600) + return con + + +def now(): + return datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + +def _day(v): + try: + d = date.fromisoformat(str(v or "").strip()) + except ValueError: + raise Invalid("day", "Not a valid day.") + if d > date.today(): + raise Invalid("day", "That day hasn't happened yet.") + return d + + +def _num(v, key): + if v is None or str(v).strip() == "": + return None + label, unit, lo, hi, _ = FIELDS[key] + try: + n = float(str(v).replace(",", ".")) + except ValueError: + raise Invalid(key, f"{label}: not a number.") + if not lo <= n <= hi: + raise Invalid(key, f"{label}: between {lo} and {hi} {unit}.") + return round(n, 2) + + +# ---- reads --------------------------------------------------------------------------- + +def all_rows(con): + """Every measured day, oldest first: [{day: date, note, : float|None}].""" + out = [] + for r in con.execute("SELECT * FROM measure ORDER BY day"): + row = {k: r[k] for k in FIELDS} + row.update(day=date.fromisoformat(r["day"]), note=r["note"]) + out.append(row) + return out + + +def _dt(t): + return datetime.fromisoformat(t) + + +def vitals(con): + """Every reading, oldest first: [{id, t: datetime, sys, dia, spo2, note, source}] (sys + dia or spo2).""" + return [dict(r, t=_dt(r["t"])) for r in con.execute("SELECT * FROM vital ORDER BY t, id")] + + +def nights(con): + """Every night, oldest first: [{day, start, end, asleep, light, deep, rem, awake, wakeups}].""" + out = [] + for r in con.execute("SELECT * FROM night ORDER BY day"): + d = dict(r) + d.update(day=date.fromisoformat(r["day"]), start=_dt(r["start"]), end=_dt(r["end"])) + out.append(d) + return out + + +def naps(con): + return [{"start": _dt(r["start"]), "end": _dt(r["end"]), "minutes": r["minutes"]} + for r in con.execute("SELECT * FROM nap ORDER BY start")] + + +def stages(con, day): + """The night's hypnogram: [(start, end, stage)].""" + return [(_dt(r["start"]), _dt(r["end"]), r["stage"]) + for r in con.execute("SELECT * FROM sleep_stage WHERE day=? ORDER BY start", (day.isoformat(),))] + + +def hr_rows(con, hist=False, since=None): + """[{day, low, high, rest[, hist {bpm: seconds}]}] oldest first; hist only from `since` + (a date) on, if given — parsing every day's histogram is the slow part.""" + out = [] + for r in con.execute("SELECT * FROM hr_day ORDER BY day"): + d = {"day": date.fromisoformat(r["day"]), "low": r["low"], "high": r["high"], "rest": r["rest"]} + if hist and (since is None or d["day"] >= since): + d["hist"] = {int(k): v for k, v in json.loads(r["hist"] or "{}").items()} + out.append(d) + return out + + +def hr_samples(con, a, z): + """[(datetime, bpm)] between two local datetimes.""" + t0, t1 = (int(x.replace(tzinfo=timezone.utc).timestamp()) for x in (a, z)) + return [(datetime.fromtimestamp(t, timezone.utc).replace(tzinfo=None), b) + for t, b in con.execute("SELECT t, bpm FROM hr_sample WHERE t BETWEEN ? AND ? ORDER BY t", (t0, t1))] + + +def _exercise(r): + d = dict(r) + d.update(start=_dt(r["start"]), end=_dt(r["end"]), day=date.fromisoformat(r["day"]), + hr_hist={int(k): v for k, v in json.loads(r["hr_hist"] or "{}").items()}) + return d + + +def exercises(con): + return [_exercise(r) for r in con.execute("SELECT * FROM exercise ORDER BY start")] + + +def exercise(con, eid): + r = con.execute("SELECT * FROM exercise WHERE id=?", (eid,)).fetchone() + return _exercise(r) if r else None + + +def steps_days(con): + return [{"day": date.fromisoformat(r["day"]), "steps": r["steps"], "workout_steps": r["workout_steps"], + "source": r["source"]} for r in con.execute("SELECT * FROM steps_day ORDER BY day")] + + +def steps_hourly(con, a, z): + """{hour (datetime): steps} between two local datetimes, records split pro rata.""" + out = {} + for s_, e_, n in con.execute("SELECT start, end, steps FROM steps_rec WHERE start < ? AND end > ?", + (z.isoformat(" "), a.isoformat(" "))): + s0, e0 = _dt(s_), _dt(e_) + dur = max(1.0, (e0 - s0).total_seconds()) + h = s0.replace(minute=0, second=0, microsecond=0) + while h < e0: + o = (min(e0, h + timedelta(hours=1)) - max(s0, h)).total_seconds() + if o > 0: + out[h] = out.get(h, 0) + n * o / dur + h += timedelta(hours=1) + return out + + +def weights(con): + """[(date, kg)] of every weighed day — for calorie maths at the time of a workout.""" + return [(date.fromisoformat(r[0]), r[1]) for r in con.execute( + "SELECT day, weight FROM measure WHERE weight IS NOT NULL ORDER BY day")] + + +# ---- writes -------------------------------------------------------------------------- + +def save(con, d): + """Replace the day's row with d ({day, …, note}); a row with nothing in it is + deleted. `was` (another day) moves the row: editing its date.""" + day = _day(d.get("day")).isoformat() + vals = {k: _num(d.get(k), k) for k in FIELDS} + note = str(d.get("note") or "").strip()[:2000] + was = d.get("was") + if was and was != day: + _day(was) + if con.execute("SELECT 1 FROM measure WHERE day=?", (day,)).fetchone(): + raise Invalid("day", "That day already has measurements — edit it instead.") + con.execute("DELETE FROM measure WHERE day=?", (was,)) + if all(v is None for v in vals.values()) and not note: + con.execute("DELETE FROM measure WHERE day=?", (day,)) + else: + cols = ["note", "updated", *vals] + con.execute(f"INSERT OR REPLACE INTO measure (day, {', '.join(cols)}) " + f"VALUES (?, {', '.join('?' * len(cols))})", (day, note, now(), *vals.values())) + con.commit() + + +def delete(con, day): + con.execute("DELETE FROM measure WHERE day=?", (_day(day).isoformat(),)) + con.commit() + + +def save_vital(con, d): + """New or edited ({id}) reading of one kind: {kind: bp | ox, day, time, sys + dia | spo2, + note}; the other kind's values are cleared. Returns its id.""" + kind = d.get("kind") + if kind not in VITAL_KINDS: + raise Invalid("kind", "Blood pressure or oxygen?") + day = _day(d.get("day")) + try: + hh, mm = (int(x) for x in str(d.get("time") or "").split(":")[:2]) + t = datetime.combine(day, datetime.min.time()).replace(hour=hh, minute=mm) + except ValueError: + raise Invalid("time", "Not a valid time.") + if t > datetime.now() + timedelta(minutes=5): + raise Invalid("time", "That time hasn't come yet.") + vals = {} + for k, (label, unit, lo, hi) in VITALS.items(): + v = d.get(k) if k in VITAL_KINDS[kind] else None + if v is None or str(v).strip() == "": + vals[k] = None + continue + try: + n = float(str(v).replace(",", ".")) + except ValueError: + raise Invalid(k, f"{label}: not a number.") + if not lo <= n <= hi: + raise Invalid(k, f"{label}: between {lo} and {hi} {unit}.") + vals[k] = round(n, 1) if k == "spo2" else int(round(n)) + if kind == "bp": + if vals["sys"] is None or vals["dia"] is None: + raise Invalid("dia" if vals["sys"] is not None else "sys", "Blood pressure needs both numbers (e.g. 120 / 80).") + if vals["sys"] <= vals["dia"]: + raise Invalid("sys", "The upper number (systolic) is the bigger one.") + elif vals["spo2"] is None: + raise Invalid("spo2", "Enter the oxygen %.") + note = str(d.get("note") or "").strip()[:500] + row = (t.strftime("%Y-%m-%d %H:%M"), *vals.values(), note) + vid = int(d.get("id") or 0) + if vid and con.execute("SELECT 1 FROM vital WHERE id=?", (vid,)).fetchone(): + con.execute("UPDATE vital SET t=?, sys=?, dia=?, spo2=?, note=?, pulse=NULL WHERE id=?", (*row, vid)) + else: + vid = con.execute("INSERT INTO vital (t, sys, dia, spo2, note) VALUES (?, ?, ?, ?, ?)", row).lastrowid + con.commit() + return vid + + +def layout(con, owner, tab): + """The saved layout of a tab ([{"id", "w"}]) or None (= the default, blocks.DEFAULTS).""" + r = con.execute("SELECT blocks FROM layout WHERE owner=? AND tab=?", (owner, tab)).fetchone() + try: + return json.loads(r[0]) if r else None + except ValueError: + return None + + +def save_layout(con, owner, tab, items): + con.execute("INSERT OR REPLACE INTO layout (owner, tab, blocks, updated) VALUES (?, ?, ?, ?)", + (owner, tab, json.dumps(items), now())) + con.commit() + + +def reset_layout(con, owner, tab): + con.execute("DELETE FROM layout WHERE owner=? AND tab=?", (owner, tab)) + con.commit() + + +def delete_vital(con, vid): + con.execute("DELETE FROM vital WHERE id=?", (int(vid or 0),)) + con.commit() + + +def import_vitals(con, readings, source): + """[(local datetime, {sys, dia, spo2})] from a watch export → vital rows (one per minute; + reruns add nothing). Out-of-range values are dropped.""" + rows = [] + for t, v in readings: + sp = v.get("spo2") + sp = float(sp) if sp and 50 <= float(sp) <= 100 else None + sy, di = v.get("sys"), v.get("dia") + if not (sy and di and 60 <= sy <= 260 and 30 <= di <= 160 and sy > di): + sy = di = None + if sp is not None or sy is not None: + rows.append((t.strftime("%Y-%m-%d %H:%M"), sy and int(round(sy)), di and int(round(di)), sp, source)) + before = con.total_changes + con.executemany("INSERT OR IGNORE INTO vital (t, sys, dia, spo2, source) VALUES (?, ?, ?, ?, ?)", rows) + return con.total_changes - before diff --git a/dashboard/plugins/health/gb.py b/dashboard/plugins/health/gb.py new file mode 100644 index 0000000..a8df4ab --- /dev/null +++ b/dashboard/plugins/health/gb.py @@ -0,0 +1,320 @@ +"""Import a Gadgetbridge database export (Gadgetbridge ▸ Settings ▸ Automations ▸ Auto export +▸ Database export, a SQLite file) into health.db — the band paired with Gadgetbridge instead +of Mi Fitness (Xiaomi Smart Band 9: its XIAOMI_* tables). + + python3 -m plugins.health.gb [--all] + +Incremental: the export is the whole database every time, so only what's newer than the last +import (minus OVERLAP — the band hands over sleep and late minutes after the fact) is taken; +`--all` takes everything. The plugin's worker (gb_watch) runs this by itself when a newer +export lands in the folder Syncthing fills (Settings ▸ Health ▸ Gadgetbridge export). + +* Per-minute samples (XIAOMI_ACTIVITY_SAMPLE, UTC seconds): heart rate (0 = not measured) + → hr_sample; steps → steps_rec for the minutes Gadgetbridge covers (anything else on those + days, e.g. Mi Fitness's before the switch, stays), steps_day summed from steps_rec ("band"). +* Daily summary (XIAOMI_DAILY_SUMMARY_SAMPLE, local midnight): the resting heart rate. +* Sleep (XIAOMI_SLEEP_TIME_SAMPLE + stage changes in XIAOMI_SLEEP_STAGE_SAMPLE; stages like + Mi Fitness: 2 deep, 3 light, 4 REM, 5 awake) → hc.group_sleep / store_sleep (nights, naps). +* Workouts (BASE_ACTIVITY_SUMMARY: start / end ms, ACTIVITY_KIND = Gadgetbridge's ActivityKind + code → KINDS) → exercise (matched by start ± 5 min, else added); distance from the samples. +* Spot checks (XIAOMI_MANUAL_SAMPLE, type 18 = SpO2) → vital. +Then the workouts' histograms and the heart-rate days from the first day touched on. + +Or through the phone app (no Syncthing): the app copies those tables' new rows into gbrelay.db +over the sync (RELAY_SCHEMA); the worker imports them the same way (import_relay). +""" +import json +import os +import shutil +import sqlite3 +import sys +import time +from collections import defaultdict +from contextlib import closing +from datetime import datetime, timedelta + +from . import db, hc, mi + +SOURCE = "gadgetbridge" +OVERLAP = timedelta(days=2) +STAGES = mi.STATES # 2 deep, 3 light, 4 REM, 5 awake +SPO2_TYPE = 18 +# Gadgetbridge ActivityKind codes (model/ActivityKind.java) → our workout names +KINDS = {0x0400003a: "Boxing", 0x00004000: "Yoga", 0x04000009: "Pilates", 0x00000020: "Walking", + 0x040000b2: "Walking", 0x04000012: "Walking", 0x00000010: "Running", 0x040000b1: "Running", + 0x040000b0: "Treadmill", 0x00000100: "Treadmill", 0x00000080: "Cycling", 0x040000b3: "Cycling", + 0x00000800: "Indoor cycling", 0x0400005e: "Free training", 0x040000cb: "Indoor fitness", + 0x00200000: "Strength training", 0x04000045: "HIIT", 0x040000dd: "Stretching", 0x00400000: "Hiking", + 0x040000db: "Climbing machine", 0x00000040: "Swimming", 0x04000060: "Kickboxing", 0x0400005c: "Dance"} +STATE = """CREATE TABLE IF NOT EXISTS import_state ( + source TEXT PRIMARY KEY, + last INTEGER, -- newest sample taken (UTC seconds) + stamp TEXT, -- the export file's mtime + size when last imported + updated TEXT NOT NULL, + result TEXT -- what the last import did (JSON) or its error +)""" +# ---- the phone app's relay: the same tables (only the columns read here), filled by the app from +# Gadgetbridge's export on the phone and synced to gbrelay.db (META "sync"); import_all reads it as +# if it were the export. Keys = the band's timestamps, so a re-sent row is the same row. +RELAY_SCHEMA = """ +CREATE TABLE IF NOT EXISTS XIAOMI_ACTIVITY_SAMPLE (TIMESTAMP INTEGER PRIMARY KEY, HEART_RATE INTEGER, STEPS INTEGER, + DISTANCE_CM INTEGER); +CREATE TABLE IF NOT EXISTS XIAOMI_DAILY_SUMMARY_SAMPLE (TIMESTAMP INTEGER PRIMARY KEY, HR_RESTING INTEGER); +CREATE TABLE IF NOT EXISTS XIAOMI_SLEEP_STAGE_SAMPLE (TIMESTAMP INTEGER PRIMARY KEY, STAGE INTEGER); +CREATE TABLE IF NOT EXISTS XIAOMI_SLEEP_TIME_SAMPLE (TIMESTAMP INTEGER PRIMARY KEY, WAKEUP_TIME INTEGER); +CREATE TABLE IF NOT EXISTS BASE_ACTIVITY_SUMMARY (START_TIME INTEGER PRIMARY KEY, END_TIME INTEGER, ACTIVITY_KIND INTEGER, + OVERRIDE_ACTIVITY_KIND INTEGER); +CREATE TABLE IF NOT EXISTS XIAOMI_MANUAL_SAMPLE (TIMESTAMP INTEGER, TYPE INTEGER, VALUE INTEGER, PRIMARY KEY (TIMESTAMP, TYPE)); +CREATE TABLE IF NOT EXISTS RELAY_INFO (k TEXT PRIMARY KEY, v TEXT); -- about the phone: tz = its time zone +""" +RELAY_SYNC = { # META["sync"]["gbrelay.db"] — the app computes the same ids + "XIAOMI_ACTIVITY_SAMPLE": {"key": "'a:' || NEW.TIMESTAMP"}, + "XIAOMI_DAILY_SUMMARY_SAMPLE": {"key": "'d:' || NEW.TIMESTAMP"}, + "XIAOMI_SLEEP_STAGE_SAMPLE": {"key": "'s:' || NEW.TIMESTAMP"}, + "XIAOMI_SLEEP_TIME_SAMPLE": {"key": "'t:' || NEW.TIMESTAMP"}, + "BASE_ACTIVITY_SUMMARY": {"key": "'w:' || NEW.START_TIME"}, + "XIAOMI_MANUAL_SAMPLE": {"key": "'m:' || NEW.TIMESTAMP || ':' || NEW.TYPE"}, + "RELAY_INFO": {"key": "'i:' || NEW.k"}, +} +RELAY_SETTLE = 60 # s the relay must stay unchanged (a pull may bring several batches) + + +def relay_create(path): + """Make gbrelay.db's tables (the plugin, at start — before the sync stamps them).""" + with closing(sqlite3.connect(path)) as c: + c.executescript(RELAY_SCHEMA) + os.chmod(path, 0o600) + + +def relay_tz(relay_path): + """The phone's time zone, as the app sends it with the band's rows (e.g. "Europe/Bucharest") — None if none came.""" + try: + with closing(sqlite3.connect(f"file:{relay_path}?mode=ro", uri=True)) as c: + r = c.execute("SELECT v FROM RELAY_INFO WHERE k = 'tz'").fetchone() + return r[0] if r and r[0] else None + except sqlite3.Error: + return None + + +def import_relay(relay_path, health_path): + """What the app relayed → health.db, like an export (incremental the same way).""" + with closing(sqlite3.connect(f"file:{relay_path}?mode=ro", uri=True)) as gb, closing(db.connect(health_path)) as con: + return import_all(con, gb) + + +CHECK_EVERY = 300 # s between looks at the export folder +SETTLE = 60 # s a file must stay unchanged (Syncthing may still be writing it) + + +def _utc(t): + """UTC epoch (seconds, or ms when it's that big) → local naive datetime (mi.TZ: the machine's zone).""" + return mi._loc(t / 1000 if t > 1e11 else t) + + +def state(con): + con.execute(STATE) + r = con.execute("SELECT last, stamp FROM import_state WHERE source=?", (SOURCE,)).fetchone() + return (r[0], r[1]) if r else (None, None) + + +def _kind_name(k): + return KINDS.get(k) or f"Workout (Gadgetbridge {k:#x})" + + +def store_steps(con, steps): + """{local minute: steps} → steps_rec for exactly those minutes (the rest of the day stays), + steps_day = the day's steps_rec summed (source "band").""" + days = defaultdict(list) + for t, n in steps.items(): + days[t.date()].append((t, n)) + for d, rows in days.items(): + a, z = min(t for t, _ in rows), max(t for t, _ in rows) + timedelta(minutes=1) + con.execute("DELETE FROM steps_rec WHERE start >= ? AND start < ?", (hc._fmt(a, True), hc._fmt(z, True))) + con.executemany("INSERT INTO steps_rec (start, end, steps) VALUES (?, ?, ?)", + [(hc._fmt(t, True), hc._fmt(t + timedelta(minutes=1), True), n) for t, n in rows if n]) + total = con.execute("SELECT COALESCE(SUM(steps), 0) FROM steps_rec WHERE start >= ? AND start < ?", + (d.isoformat(), (d + timedelta(days=1)).isoformat())).fetchone()[0] + con.execute("INSERT OR REPLACE INTO steps_day (day, steps, workout_steps, source) VALUES (?, ?, 0, 'band')", + (d.isoformat(), total)) + return len(days) + + +def store_workouts(con, wks): + """Match by start (± 5 min) → name + distance; else add.""" + have = [(db._dt(s), i) for i, s in con.execute("SELECT id, start FROM exercise")] + named = added = 0 + for w in wks: + m = min(have, key=lambda h: abs((h[0] - w["start"]).total_seconds()), default=None) + if m and abs((m[0] - w["start"]).total_seconds()) <= 300: + con.execute("UPDATE exercise SET name=?, distance=COALESCE(?, distance) WHERE id=?", (w["name"], w["distance"], m[1])) + named += 1 + else: + con.execute("INSERT OR IGNORE INTO exercise (start, end, day, type, name, minutes, distance, source) " + "VALUES (?, ?, ?, NULL, ?, ?, ?, ?)", + (hc._fmt(w["start"], True), hc._fmt(w["end"], True), w["start"].date().isoformat(), w["name"], + (w["end"] - w["start"]).total_seconds() / 60, w["distance"], SOURCE)) + added += 1 + return named, added + + +def import_all(con, gb, everything=False): + """gb = a connection to the export (read-only). Returns what it did.""" + gb.row_factory = sqlite3.Row + last, _ = state(con) + since_ts = 0 if everything or not last else last - int(OVERLAP.total_seconds()) + out = {} + # per-minute samples + hr, steps, dist, newest = {}, {}, {}, last or 0 + for r in gb.execute("SELECT TIMESTAMP, HEART_RATE, STEPS, DISTANCE_CM FROM XIAOMI_ACTIVITY_SAMPLE " + "WHERE TIMESTAMP >= ? ORDER BY TIMESTAMP", (since_ts,)): + t = _utc(r["TIMESTAMP"]) + newest = max(newest, r["TIMESTAMP"]) + if r["HEART_RATE"] and 25 <= r["HEART_RATE"] <= 230: + hr[hc._epoch(t)] = r["HEART_RATE"] + steps[t.replace(second=0)] = max(0, r["STEPS"] or 0) + if r["DISTANCE_CM"] and r["DISTANCE_CM"] > 0: + dist[t] = r["DISTANCE_CM"] / 100 + first = min(steps).date() if steps else None + con.executemany("INSERT OR REPLACE INTO hr_sample (t, bpm) VALUES (?, ?)", hr.items()) + out["hr readings"] = len(hr) + out["step days"] = store_steps(con, steps) + # resting heart rate per day (the summary's timestamp is local midnight) + rest = {} + for r in gb.execute("SELECT TIMESTAMP, HR_RESTING FROM XIAOMI_DAILY_SUMMARY_SAMPLE WHERE TIMESTAMP >= ?", + (since_ts * 1000,)): + if r["HR_RESTING"]: + rest[_utc(r["TIMESTAMP"]).date()] = r["HR_RESTING"] + # sleep: each record + the stage changes inside it + stages = [(r[0], r[1]) for r in gb.execute("SELECT TIMESTAMP, STAGE FROM XIAOMI_SLEEP_STAGE_SAMPLE " + "WHERE TIMESTAMP >= ? ORDER BY TIMESTAMP", (since_ts * 1000,))] + sess = [] + for r in gb.execute("SELECT TIMESTAMP, WAKEUP_TIME FROM XIAOMI_SLEEP_TIME_SAMPLE WHERE TIMESTAMP >= ? ORDER BY TIMESTAMP", + (since_ts * 1000,)): + a_ms, b_ms = r["TIMESTAMP"], r["WAKEUP_TIME"] + if not b_ms or b_ms <= a_ms: + continue + seg = [(t, s) for t, s in stages if a_ms <= t < b_ms] + items = [(_utc(t), _utc(nxt), STAGES.get(s, "asleep")) for (t, s), (nxt, _) in zip(seg, seg[1:] + [(b_ms, None)])] + sess.append((_utc(a_ms), _utc(b_ms), items, a_ms)) + groups = hc.group_sleep(sess) + if groups: # these days' sleep comes from here now + # only sleeps starting inside this read: a night is keyed by its wake-up day, so clearing + # whole days from the first start's date dropped the night before (ending that day, read earlier) + a = hc._fmt(groups[0][0]) + con.execute("DELETE FROM night WHERE start >= ?", (a,)) + con.execute("DELETE FROM nap WHERE start >= ?", (a,)) + con.execute("DELETE FROM sleep_stage WHERE day NOT IN (SELECT day FROM night)") + first = min(first or groups[0][0].date(), groups[0][0].date()) + out["nights, naps"] = hc.store_sleep(con, groups, SOURCE) + # workouts + wks = [] + for r in gb.execute("SELECT START_TIME, END_TIME, ACTIVITY_KIND, OVERRIDE_ACTIVITY_KIND FROM BASE_ACTIVITY_SUMMARY " + "WHERE START_TIME >= ? ORDER BY START_TIME", (since_ts * 1000,)): + a, b = _utc(r["START_TIME"]), _utc(r["END_TIME"]) + if b > a: + k = r["OVERRIDE_ACTIVITY_KIND"] or r["ACTIVITY_KIND"] + d = sum(m for t, m in dist.items() if a <= t < b) + wks.append({"start": a, "end": b, "name": _kind_name(k), "distance": round(d) if d else None}) + first = min(first or a.date(), a.date()) + out["workouts named, added"] = store_workouts(con, wks) + # spot checks + spo2 = [(_utc(r["TIMESTAMP"]), {"spo2": r["VALUE"]}) for r in gb.execute( + "SELECT TIMESTAMP, VALUE FROM XIAOMI_MANUAL_SAMPLE WHERE TYPE=? AND TIMESTAMP >= ?", (SPO2_TYPE, since_ts * 1000))] + out["oxygen readings"] = db.import_vitals(con, spo2, SOURCE) + # derived: from the first day touched on + if first: + mi.refresh_workouts(con, since=first) + out["hr days"] = hc.rebuild_hr_days(con, rest, SOURCE, since=first) + out["from"] = first.isoformat() if first else None + con.execute("INSERT OR REPLACE INTO import_state (source, last, stamp, updated) VALUES (?, ?, " + "(SELECT stamp FROM import_state WHERE source=?), ?)", + (SOURCE, newest or None, SOURCE, datetime.now().isoformat(timespec="seconds"))) + con.commit() + return out + + +def run(export_path, health_path, everything=False): + with closing(sqlite3.connect(f"file:{export_path}?mode=ro", uri=True)) as gb, closing(db.connect(health_path)) as con: + return import_all(con, gb, everything) + + +# ---- automatic: the plugin's worker ---------------------------------------------------------- + +def find_export(path): + """The export: `path` itself, or the newest SQLite file in that folder (Gadgetbridge's auto + export overwrites one file; Syncthing may keep it under any name). None if nothing yet.""" + if not path or not os.path.exists(path): + return None + files = [path] if os.path.isfile(path) else [os.path.join(path, f) for f in os.listdir(path) + if not f.startswith(".") and os.path.isfile(os.path.join(path, f))] + def sqlite(f): + try: + with open(f, "rb") as h: + return h.read(16) == b"SQLite format 3\x00" + except OSError: + return False + files = [f for f in files if sqlite(f)] + return max(files, key=os.path.getmtime) if files else None + + +def stamp_of(f): + st = os.stat(f) + return f"{int(st.st_mtime)}:{st.st_size}" + + +def import_if_new(path, health_path, work_dir, force=False): + """One look: a newer, settled export → copied aside (Syncthing may replace it while we read) + and imported. Returns the result dict, or None when there was nothing to do.""" + f = find_export(path) + if not f: + return None + if not force and time.time() - os.path.getmtime(f) < SETTLE: + return None + s = stamp_of(f) + with closing(db.connect(health_path)) as con: + state(con) + row = con.execute("SELECT stamp FROM import_state WHERE source=?", (SOURCE,)).fetchone() + if not force and row and row[0] == s: # this very file was imported already (rows aren't tuples: compare the value) + return None + tmp = os.path.join(work_dir, "gadgetbridge-import.db") + shutil.copyfile(f, tmp) + try: + res = run(tmp, health_path) + err = None + except Exception as e: # a half-synced / odd file: remember, try the next one + res, err = None, f"{type(e).__name__}: {e}" + finally: + os.remove(tmp) + with closing(db.connect(health_path)) as con: + state(con) + con.execute("INSERT INTO import_state (source, stamp, updated, result) VALUES (?, ?, ?, ?) " + "ON CONFLICT(source) DO UPDATE SET stamp=excluded.stamp, updated=excluded.updated, result=excluded.result", + (SOURCE, s, datetime.now().isoformat(timespec="seconds"), json.dumps(res) if res else err)) + con.commit() + if err: + raise RuntimeError(err) + return res + + +def status(health_path, path): + """Settings ▸ Health: the folder, the export found, the last import.""" + f = find_export(path) if path else None + out = {"path": path, "file": f, "file_time": datetime.fromtimestamp(os.path.getmtime(f)) if f else None, + "updated": None, "result": None, "error": None, "newest": None} + with closing(db.connect(health_path)) as con: + state(con) + r = con.execute("SELECT last, updated, result FROM import_state WHERE source=?", (SOURCE,)).fetchone() + if r: + out["newest"] = _utc(r[0]) if r[0] else None + out["updated"] = datetime.fromisoformat(r[1]) if r[1] else None + try: + out["result"] = json.loads(r[2]) if r[2] else None + except ValueError: + out["error"] = r[2] + return out + + +if __name__ == "__main__": + if len(sys.argv) < 3: + sys.exit(__doc__) + print(run(sys.argv[1], sys.argv[2], "--all" in sys.argv[3:])) diff --git a/dashboard/plugins/health/hc.py b/dashboard/plugins/health/hc.py new file mode 100644 index 0000000..7d0b3e3 --- /dev/null +++ b/dashboard/plugins/health/hc.py @@ -0,0 +1,331 @@ +"""Import a Health Connect export (the phone's Health Connect ▸ Export → a zip with +health_connect_export.db) into health.db — and its nutrition into the food plugin's db. + + python3 -m plugins.health.hc [] + +Rerunning replaces everything this source brought (source = "health_connect"); the hand- +made screenshot import from before is dropped. What it does with the raw records: + +* Sleep: Mi Fitness writes the same night several times, overlapping. Sessions that + overlap or are < 60 min apart are one sleep; its stages are laid out per minute (so + doubles count once). A sleep of 3 h+ or starting 18:00–06:00 is a **night** (keyed by + the day you woke up; two on one day merge), else a **nap**. +* Heart rate: every sample (local time). Mi Fitness exports continuous heart rate only + during workouts; outside them a few spot readings — the day's "low" is the lowest of + those (approximate resting), "high" the highest sample. +* Workouts: per session the heart-rate histogram (bpm → seconds) for zones + calories + (computed on read, from your current settings), distance, the app's own kcal (shown for + comparison), steps during it. +* Daily heart rate: the screenshot import's days are kept where this export has no + reading outside workouts for that day. +* Steps: per day ONE source — the band (Mi Fitness) if it counted any that day, else the + other source with the most (the phone and Health Connect's own counter count the same + steps, so they're never added together). +""" +import json +import sqlite3 +from bisect import bisect_right +import sys +from collections import Counter, defaultdict +from contextlib import closing +from datetime import datetime, timedelta, timezone + +from . import db + +SOURCE = "health_connect" +BAND = "com.xiaomi.wearable" +# Health Connect sleep stage → ours (2 "sleeping" and 0 "unknown" = asleep, stage not known) +STAGE = {0: "asleep", 1: "awake", 2: "asleep", 3: "awake", 4: "light", 5: "deep", 6: "rem", 7: "awake"} +GAP = timedelta(minutes=60) # sessions closer than this are one sleep +NIGHT_MIN = 180 # minutes: a sleep this long is a night wherever it falls + + +def _local(ms, off): + return datetime.fromtimestamp(ms / 1000, timezone.utc).replace(tzinfo=None) + timedelta(seconds=off or 0) + + +def _fmt(t, sec=False): + return t.strftime("%Y-%m-%d %H:%M:%S" if sec else "%Y-%m-%d %H:%M") + + +def _epoch(t): # naive local datetime → "local seconds" + return int(t.replace(tzinfo=timezone.utc).timestamp()) + + +# ---- sleep ----------------------------------------------------------------------------- + +def group_sleep(sess): + """Sleep records → sleeps: sess = [(start, end, [(s, e, stage)], modified)] in local time. + Records that overlap or are < GAP apart are one sleep; stages are laid out per minute so + doubles count once (newer records win where they disagree). → [(start, end, minute map)].""" + groups = [] + for x in sorted(sess, key=lambda r: r[0]): + if groups and x[0] <= groups[-1][1] + GAP: + groups[-1][1] = max(groups[-1][1], x[1]) + groups[-1][2].append(x) + else: + groups.append([x[0], x[1], [x]]) + out = [] + for a, b, ss in groups: + minute = {} + for sa, sb, stages, _ in sorted(ss, key=lambda r: r[3] or 0): + m = sa.replace(second=0) + while m < sb: + minute.setdefault(m, "asleep") + m += timedelta(minutes=1) + for x, y, st in stages: + m = x.replace(second=0) + while m < y: + minute[m] = st + m += timedelta(minutes=1) + out.append((a, b, minute)) + return out + + +def _sleeps(hc): + sess = hc.execute("SELECT row_id, start_time, end_time, start_zone_offset, end_zone_offset, last_modified_time " + "FROM sleep_session_record_table ORDER BY start_time").fetchall() + st = defaultdict(list) + for pk, a, b, t in hc.execute("SELECT parent_key, stage_start_time, stage_end_time, stage_type FROM sleep_stages_table"): + st[pk].append((a, b, t)) + return group_sleep([(_local(s[1], s[3]), _local(s[2], s[4]), + [(_local(x, s[3]), _local(y, s[3]), STAGE.get(t, "asleep")) for x, y, t in st[s[0]]], s[5]) + for s in sess]) + + +def _night_stats(minute): + ms = sorted(minute) + while ms and minute[ms[0]] == "awake": # awake at the edges isn't part of the night + ms.pop(0) + while ms and minute[ms[-1]] == "awake": + ms.pop() + if not ms: + return None + c = Counter(minute[m] for m in ms) + runs, wakeups = [], 0 + for m in ms: + s = minute[m] + if runs and runs[-1][2] == s and runs[-1][1] == m: + runs[-1][1] = m + timedelta(minutes=1) + else: + if s == "awake": + wakeups += 1 + runs.append([m, m + timedelta(minutes=1), s]) + asleep = c["light"] + c["deep"] + c["rem"] + c["asleep"] + return {"start": ms[0], "end": ms[-1] + timedelta(minutes=1), "asleep": asleep, "light": c["light"], + "deep": c["deep"], "rem": c["rem"], "awake": c["awake"], "wakeups": wakeups, "runs": runs} + + +def import_sleep(con, hc): + return store_sleep(con, _sleeps(hc), SOURCE) + + +def store_sleep(con, groups, source): + """Sleeps (group_sleep) → nights (keyed by wake-up day) + naps, replacing those days.""" + nights, naps = {}, [] + for a, b, minute in groups: + n = _night_stats(minute) + if not n: + continue + h = n["start"].hour + if n["asleep"] >= NIGHT_MIN or h >= 18 or h < 6: + day = n["end"].date() + if day in nights: # two sleeps ending the same day: one night + o = nights[day] + for k in ("asleep", "light", "deep", "rem", "awake", "wakeups"): + n[k] += o[k] + n["runs"] = sorted(o["runs"] + n["runs"]) + n["start"], n["end"] = min(o["start"], n["start"]), max(o["end"], n["end"]) + nights[day] = n + else: + naps.append(n) + for day, n in nights.items(): + con.execute("DELETE FROM sleep_stage WHERE day=?", (day.isoformat(),)) + con.execute("INSERT OR REPLACE INTO night (day, start, end, asleep, light, deep, rem, awake, wakeups, source) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + (day.isoformat(), _fmt(n["start"]), _fmt(n["end"]), n["asleep"], n["light"], n["deep"], n["rem"], + n["awake"], n["wakeups"], source)) + con.executemany("INSERT INTO sleep_stage (day, start, end, stage) VALUES (?, ?, ?, ?)", + [(day.isoformat(), _fmt(x), _fmt(y), s) for x, y, s in n["runs"]]) + for n in naps: + con.execute("INSERT OR REPLACE INTO nap (start, end, minutes, source) VALUES (?, ?, ?, ?)", + (_fmt(n["start"]), _fmt(n["end"]), n["asleep"], source)) + return len(nights), len(naps) + + +# ---- heart rate -------------------------------------------------------------------------- + +def import_hr(con, hc): + rows = hc.execute("SELECT s.epoch_millis, s.beats_per_minute, r.start_zone_offset FROM heart_rate_record_series_table s " + "JOIN heart_rate_record_table r ON r.row_id = s.parent_key").fetchall() + samples = {ms // 1000 + (off or 0): bpm for ms, bpm, off in rows} + con.executemany("INSERT OR REPLACE INTO hr_sample (t, bpm) VALUES (?, ?)", samples.items()) + return samples + + +def rebuild_hr_days(con, rest=None, source=SOURCE, since=None): + """hr_day for every day with readings: low (outside workouts), high, resting (Mi's, else + kept), histogram (each reading counts until the next, at most 10 min). since (a date): + only the days from it on (an import of the newest data); the older days stay.""" + spans = sorted((_epoch(db._dt(a)) - 60, _epoch(db._dt(b)) + 60) + for a, b in con.execute("SELECT start, end FROM exercise")) + starts = [a for a, _ in spans] + in_workout = lambda t: (i := bisect_right(starts, t) - 1) >= 0 and t <= spans[i][1] + old = {r[0]: r[1] for r in con.execute("SELECT day, rest FROM hr_day WHERE rest IS NOT NULL")} + low, high, hist = {}, {}, defaultdict(Counter) + prev = None + t0 = _epoch(datetime.combine(since, datetime.min.time())) - 600 if since else 0 # the reading before counts too + for t, bpm in con.execute("SELECT t, bpm FROM hr_sample WHERE t >= ? ORDER BY t", (t0,)): + if prev: + pt, pb = prev + d = datetime.fromtimestamp(pt, timezone.utc).date() + hist[d][pb] += min(600, max(1, t - pt)) + d = datetime.fromtimestamp(t, timezone.utc).date() + high[d] = max(high.get(d, 0), bpm) + if not in_workout(t): + low[d] = min(low.get(d, 999), bpm) + prev = (t, bpm) + keep = (lambda d: d >= since) if since else (lambda d: True) + con.execute("DELETE FROM hr_day WHERE day >= ?", (since.isoformat() if since else "",)) + for d in sorted(x for x in set(high) | set(rest or {}) if keep(x)): + con.execute("INSERT INTO hr_day (day, low, high, rest, hist, source) VALUES (?, ?, ?, ?, ?, ?)", + (d.isoformat(), low.get(d), high.get(d), (rest or {}).get(d) or old.get(d.isoformat()), + json.dumps(hist.get(d, {})), source)) + return len(high) + + +def _hist(con, a, b): + """{bpm: seconds} and the samples between two local datetimes (each sample counts until + the next one, at most 90 s — Health Connect has one a second, Mi Fitness one a minute).""" + ts = con.execute("SELECT t, bpm FROM hr_sample WHERE t BETWEEN ? AND ? ORDER BY t", (_epoch(a), _epoch(b))).fetchall() + hist = Counter() + for (t, bpm), nxt in zip(ts, ts[1:] + [(ts[-1][0] + 1, 0)] if ts else []): + hist[bpm] += min(90, max(1, nxt[0] - t)) + return hist, [b for _, b in ts] + + +# ---- steps ------------------------------------------------------------------------------- + +def _apps(hc): + return {r[0]: r[1] for r in hc.execute("SELECT row_id, package_name FROM application_info_table")} + + +def _step_records(hc): + """{app: [(start, end, steps)]} (local), doubles within an app dropped.""" + out = defaultdict(set) + for app, a, b, off, n in hc.execute("SELECT app_info_id, start_time, end_time, start_zone_offset, count FROM steps_record_table"): + out[app].add((_local(a, off), _local(b, off), n)) + return out + + +def _overlap(recs, a, b): + """Steps of records [(start, end, n)] falling inside a..b (pro rata).""" + tot = 0.0 + for x, y, n in recs: + o = (min(y, b) - max(x, a)).total_seconds() + if o > 0: + tot += n * o / max(1.0, (y - x).total_seconds()) + return tot + + +def import_steps(con, hc, workouts): + apps = _apps(hc) + recs = _step_records(hc) + per = defaultdict(lambda: defaultdict(int)) # day → app → steps + for app, rs in recs.items(): + for a, b, n in rs: + per[a.date()][app] += n + band = next((k for k, v in apps.items() if v == BAND), None) + n = 0 + for day, by in per.items(): + app = band if by.get(band) else max(by, key=by.get) + day_recs = [r for r in recs[app] if r[0].date() == day] + ws = sum(_overlap(day_recs, a, b) for a, b in workouts if a.date() == day) + con.executemany("INSERT INTO steps_rec (start, end, steps) VALUES (?, ?, ?)", + [(_fmt(x, True), _fmt(y, True), k) for x, y, k in day_recs]) + con.execute("INSERT OR REPLACE INTO steps_day (day, steps, workout_steps, source) VALUES (?, ?, ?, ?)", + (day.isoformat(), by[app], round(ws), "band" if app == band else "phone")) + n += 1 + return n, recs, band + + +# ---- workouts ---------------------------------------------------------------------------- + +def import_exercise(con, hc): + rows = hc.execute("SELECT start_time, end_time, start_zone_offset, exercise_type, app_info_id FROM exercise_session_record_table " + "ORDER BY start_time").fetchall() + dist = hc.execute("SELECT start_time, end_time, distance, app_info_id FROM distance_record_table").fetchall() + kcal = hc.execute("SELECT start_time, end_time, energy, app_info_id FROM active_calories_burned_record_table").fetchall() + spans = [] + for s, e, off, t, app in rows: + a, b = _local(s, off), _local(e, off) + inside = lambda recs: sum(v for x, y, v, ap in recs if ap == app and x >= s - 60000 and y <= e + 60000) + hist, bpms = _hist(con, a, b) + con.execute("INSERT OR REPLACE INTO exercise (start, end, day, type, minutes, distance, kcal_device, avg_hr, max_hr, " + "hr_hist, source) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", + (_fmt(a, True), _fmt(b, True), a.date().isoformat(), t, (e - s) / 60000, inside(dist) or None, + (inside(kcal) / 1000) or None, sum(bpms) / len(bpms) if bpms else None, max(bpms) if bpms else None, + json.dumps(hist), SOURCE)) + spans.append((a, b)) + return len(rows), spans + + +def set_workout_steps(con, recs, band): + """Steps the band counted during each workout (they're in the workout's calories).""" + rs = recs.get(band, set()) + for eid, a, b in con.execute("SELECT id, start, end FROM exercise").fetchall(): + con.execute("UPDATE exercise SET steps=? WHERE id=?", (round(_overlap(rs, db._dt(a), db._dt(b))), eid)) + + +# ---- all --------------------------------------------------------------------------------- + +def drop_old(con): + """Forget the screenshot import (v1 tables) and this source's previous run.""" + con.execute("DROP TABLE IF EXISTS sleep") + con.execute("DROP TABLE IF EXISTS workout") + con.execute("DELETE FROM hr_day WHERE source=?", (SOURCE,)) # screenshot days stay where they're better + for t in ("night", "nap", "exercise", "steps_day"): + con.execute(f"DELETE FROM {t} WHERE source=?", (SOURCE,)) + con.execute("DELETE FROM steps_rec") + con.execute("DELETE FROM sleep_stage WHERE day NOT IN (SELECT day FROM night)") + + +def import_vitals(con, hc): + """Blood oxygen + blood pressure records (spot checks) → vital rows (db.import_vitals). + Mi Fitness writes these with zone offset 0: then the Pi's own time zone is used.""" + def _local(ms, off): + return datetime.fromtimestamp(ms / 1000, timezone.utc).replace(tzinfo=None) + timedelta(seconds=off) \ + if off else datetime.fromtimestamp(ms / 1000) + out = [] + tables = {r[0] for r in hc.execute("SELECT name FROM sqlite_master WHERE type='table'")} + if "oxygen_saturation_record_table" in tables: + out += [(_local(t, off), {"spo2": p}) for t, off, p in + hc.execute("SELECT time, zone_offset, percentage FROM oxygen_saturation_record_table")] + if "blood_pressure_record_table" in tables: + out += [(_local(t, off), {"sys": a, "dia": b}) for t, off, a, b in + hc.execute("SELECT time, zone_offset, systolic, diastolic FROM blood_pressure_record_table")] + return db.import_vitals(con, out, SOURCE) + + +def import_all(con, hc): + drop_old(con) + out = {"nights, naps": import_sleep(con, hc)} + samples = import_hr(con, hc) + n, spans = import_exercise(con, hc) + out.update({"hr samples": len(samples), "workouts": n}) + out["step days"], recs, band = import_steps(con, hc, spans) + set_workout_steps(con, recs, band) + out["hr days"] = rebuild_hr_days(con) + out["vitals"] = import_vitals(con, hc) + con.commit() + return out + + +if __name__ == "__main__": + src, health = sys.argv[1], sys.argv[2] + with closing(sqlite3.connect(f"file:{src}?mode=ro", uri=True)) as hc, closing(db.connect(health)) as con: + print(import_all(con, hc)) + if len(sys.argv) > 3: + from plugins.food import db as food + with closing(food.connect(sys.argv[3])) as fc: + print("food:", food.import_health_connect(fc, hc)) diff --git a/dashboard/plugins/health/mi.py b/dashboard/plugins/health/mi.py new file mode 100644 index 0000000..d30b142 --- /dev/null +++ b/dashboard/plugins/health/mi.py @@ -0,0 +1,202 @@ +"""Import a Mi Fitness data export (Xiaomi privacy portal → "copy of my data": a folder of +CSVs named __MiFitness_*.csv) into health.db — the main source; the Health +Connect import (hc.py) fills what this lacks (e.g. phone steps on days without the band). + + python3 -m plugins.health.mi + +Rerunnable (source = "mi_fitness"). Taken from Mi (what the band measured): sleep with its +stages, every heart-rate reading, the daily resting heart rate, steps per minute, workouts +with their names. Not taken: Mi's scores (training effect / load, PAI, vitality, calories +… we compute our own), stress, SpO2. + +* Sleep: `watch_night_sleep` / `watch_daytime_sleep` (older band link, to May 2025) and + `sleep` (since), each with stage items (state 2 deep, 3 light, 4 REM, 5 awake) and its + time zone in quarter hours; grouped into nights / naps like hc.py (`group_sleep`); the + days Mi covers replace Health Connect's. +* Heart rate: every 10 minutes all day, every minute when active. Added to hr_sample + (Health Connect's per-second workout samples stay); then `hr_day` is rebuilt for every + day: low (outside workouts), high, Mi's resting heart rate, a {bpm: seconds} histogram. +* Workouts (`sport_record`): matched to Health Connect's by start (± 5 min) → named; + older ones added. Every workout's heart-rate histogram + steps are recomputed. +* Steps: Mi's per-minute counts replace the band's days (steps_day + steps_rec). +""" +import csv +import glob +import json +import os +import sys +from collections import Counter, defaultdict +from contextlib import closing +from datetime import datetime, timedelta, timezone + +from . import calc, db, hc + +SOURCE = "mi_fitness" +STATES = {2: "deep", 3: "light", 4: "rem", 5: "awake"} +TZ = None # None = the machine's own time zone (timedatectl set-timezone …) + + +def set_tz(name): + """Settings ▸ Health ▸ time zone (or DASH_TZ on the command line); empty / unknown = the machine's.""" + global TZ + name = (name or os.environ.get("DASH_TZ") or "").strip() + if not name: + TZ = None + return + try: + from zoneinfo import ZoneInfo + TZ = ZoneInfo(name) + except Exception: + print(f"health: unknown time zone {name!r}, using the machine's", flush=True) + TZ = None + + +set_tz(None) + + +def _loc(t, q=None): + """Epoch seconds → local naive datetime (q = Mi's time zone in quarter hours, if given).""" + if q is not None: + return datetime.fromtimestamp(t, timezone.utc).replace(tzinfo=None) + timedelta(minutes=15 * q) + if TZ: + return datetime.fromtimestamp(t, TZ).replace(tzinfo=None) + return datetime.fromtimestamp(t) + + +def _file(folder, name): + hits = glob.glob(os.path.join(folder, f"*_MiFitness_{name}.csv")) + return hits[0] if hits else None + + +def _rows(path): + csv.field_size_limit(1 << 30) + with open(path, newline="", encoding="utf-8-sig") as f: + yield from csv.DictReader(f) + + +WANT = {"sleep", "watch_night_sleep", "watch_daytime_sleep", "heart_rate", "resting_heart_rate", "steps", + "spo2", "single_spo2"} + + +def read_fitness(folder): + """One pass over the big file → sleep records, heart-rate samples, resting HR, steps, + blood-oxygen spot checks.""" + sess, hr, rest, steps, spo2 = [], {}, {}, {}, [] + for r in _rows(_file(folder, "hlth_center_fitness_data")): + k = r["Key"] + if k not in WANT: + continue + v = json.loads(r["Value"]) + if k == "heart_rate": + if v.get("bpm"): + hr[hc._epoch(_loc(int(v.get("time") or r["Time"])))] = v["bpm"] + elif k == "steps": + if v.get("steps"): + steps[_loc(int(v.get("time") or r["Time"]))] = v["steps"] + elif k in ("spo2", "single_spo2"): # spot checks (both keys: the same check) + if v.get("spo2"): + spo2.append((_loc(int(v.get("time") or r["Time"])), {"spo2": v["spo2"]})) + elif k == "resting_heart_rate": + if v.get("bpm"): + rest[datetime.fromtimestamp(int(v.get("date_time") or r["Time"]), timezone.utc).date()] = v["bpm"] + else: # a sleep record + q = v.get("timezone") + items = [(_loc(i["start_time"], q), _loc(i["end_time"], q), STATES.get(i.get("state"), "asleep")) + for i in v.get("items") or [] if i.get("end_time", 0) > i.get("start_time", 0)] + a = _loc(v["bedtime"], q) if v.get("bedtime") else (items[0][0] if items else None) + b = _loc(v["wake_up_time"], q) if v.get("wake_up_time") else (items[-1][1] if items else None) + if a and b and b > a: + sess.append((a, b, items, v.get("protoTime") or int(r["Time"]))) + return sess, hr, rest, steps, spo2 + + +def read_workouts(folder): + out = [] + for r in _rows(_file(folder, "hlth_center_sport_record")): + v = json.loads(r["Value"]) + q = v.get("timezone") + a, b = _loc(v["start_time"], q), _loc(v["end_time"], q) + if b > a: + out.append({"start": a, "end": b, "name": calc.MI_SPORTS.get(r["Category"], r["Category"].replace("_", " ").capitalize()), + "kcal": v.get("calories")}) + return out + + +# ---- writing ------------------------------------------------------------------------------- + +def store_workouts(con, wks): + """Name the matching workouts (start ± 5 min), add the others.""" + have = [(db._dt(s), i) for i, s in con.execute("SELECT id, start FROM exercise")] + named = added = 0 + for w in wks: + m = min(have, key=lambda h: abs((h[0] - w["start"]).total_seconds()), default=None) + if m and abs((m[0] - w["start"]).total_seconds()) <= 300: + con.execute("UPDATE exercise SET name=? WHERE id=?", (w["name"], m[1])) + named += 1 + else: + con.execute("INSERT OR IGNORE INTO exercise (start, end, day, type, name, minutes, kcal_device, source) " + "VALUES (?, ?, ?, NULL, ?, ?, ?, ?)", + (hc._fmt(w["start"], True), hc._fmt(w["end"], True), w["start"].date().isoformat(), w["name"], + (w["end"] - w["start"]).total_seconds() / 60, w["kcal"], SOURCE)) + added += 1 + return named, added + + +def store_steps(con, steps): + """Mi's per-minute counts → steps_rec + steps_day for every day they cover (band).""" + days = defaultdict(list) + for t, n in steps.items(): + days[t.date()].append((t, n)) + for d, rows in days.items(): + con.execute("DELETE FROM steps_rec WHERE start >= ? AND start < ?", + (d.isoformat(), (d + timedelta(days=1)).isoformat())) + con.executemany("INSERT INTO steps_rec (start, end, steps) VALUES (?, ?, ?)", + [(hc._fmt(t, True), hc._fmt(t + timedelta(minutes=1), True), n) for t, n in rows]) + con.execute("INSERT OR REPLACE INTO steps_day (day, steps, workout_steps, source) VALUES (?, ?, 0, 'band')", + (d.isoformat(), sum(n for _, n in rows))) + return len(days) + + +def refresh_workouts(con, since=None): + """Every workout (since: from that day on): heart-rate histogram, avg / max, steps during + it; steps_day's share.""" + per_day = defaultdict(float) + for eid, a, b in con.execute("SELECT id, start, end FROM exercise WHERE day >= ?", + (since.isoformat() if since else "",)).fetchall(): + a, b = db._dt(a), db._dt(b) + hist, bpms = hc._hist(con, a, b) + st = con.execute("SELECT start, end, steps FROM steps_rec WHERE start < ? AND end > ?", + (hc._fmt(b, True), hc._fmt(a, True))).fetchall() + n = hc._overlap([(db._dt(x), db._dt(y), k) for x, y, k in st], a, b) + per_day[a.date()] += n + con.execute("UPDATE exercise SET hr_hist=?, avg_hr=?, max_hr=?, steps=? WHERE id=?", + (json.dumps(hist), sum(bpms) / len(bpms) if bpms else None, max(bpms) if bpms else None, round(n), eid)) + con.execute("UPDATE steps_day SET workout_steps = 0 WHERE day >= ?", (since.isoformat() if since else "",)) + con.executemany("UPDATE steps_day SET workout_steps=? WHERE day=?", [(round(n), d.isoformat()) for d, n in per_day.items()]) + + +def import_all(con, folder): + sess, hr, rest, steps, spo2 = read_fitness(folder) + out = {} + groups = hc.group_sleep(sess) + if groups: # Mi's days replace Health Connect's + a, z = groups[0][0].date(), groups[-1][1].date() + con.execute("DELETE FROM night WHERE day BETWEEN ? AND ?", (a.isoformat(), z.isoformat())) + con.execute("DELETE FROM nap WHERE start >= ? AND start < ?", (a.isoformat(), (z + timedelta(days=1)).isoformat())) + con.execute("DELETE FROM sleep_stage WHERE day NOT IN (SELECT day FROM night)") + out["nights, naps"] = hc.store_sleep(con, groups, SOURCE) + con.executemany("INSERT OR IGNORE INTO hr_sample (t, bpm) VALUES (?, ?)", hr.items()) + out["hr readings"] = len(hr) + out["workouts named, added"] = store_workouts(con, read_workouts(folder)) + out["step days"] = store_steps(con, steps) + refresh_workouts(con) + out["hr days"] = hc.rebuild_hr_days(con, rest, SOURCE) + out["resting hr days"] = len(rest) + out["oxygen readings"] = db.import_vitals(con, spo2, SOURCE) + con.commit() + return out + + +if __name__ == "__main__": + with closing(db.connect(sys.argv[2])) as c: + print(import_all(c, sys.argv[1])) diff --git a/dashboard/plugins/health/static/health.css b/dashboard/plugins/health/static/health.css new file mode 100644 index 0000000..4be174b --- /dev/null +++ b/dashboard/plugins/health/static/health.css @@ -0,0 +1,396 @@ +/* Health — on top of dash.css (its tokens, header, .ec-box dialogs). Real px. */ +.page-health { display: flex; flex-direction: column; gap: 12px; font-size: 14px; } +.hl { display: flex; flex-direction: column; gap: 12px; } +/* two cards side by side on wide screens */ +.hl-two { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; align-items: start; } +@media (max-width: 1099px) { .hl-two { grid-template-columns: minmax(0, 1fr); } } +/* the +: a round button floating bottom right (every tab); hovering it (or focusing in it) + lists the kinds above it — a click on the + itself opens the tab's default (the lit one) */ +.hl-fab { position: fixed; right: 22px; bottom: 22px; z-index: 8; display: flex; flex-direction: column; align-items: flex-end; } +/* opens only from the + itself (the closed menu ignores the mouse), right away; stays while + you're on it; closes a beat after you leave (so the gap is crossable). + It unrolls from the bottom: the panel is revealed upwards, the choices follow lowest first. */ +.hl-fabmenu { display: flex; flex-direction: column; gap: 6px; padding: 8px; margin-bottom: 10px; border-radius: 12px; + background: var(--card); box-shadow: 0 8px 24px rgba(0, 0, 0, .5); + visibility: hidden; pointer-events: none; clip-path: inset(100% 0 0 0 round 12px); + transition: clip-path .22s ease-in, visibility 0s linear .42s; transition-delay: .2s, .42s; } +.hl-fab:has(.fab:hover) .hl-fabmenu, .hl-fab:has(.fab:focus-visible) .hl-fabmenu, +.hl-fabmenu:hover, .hl-fabmenu:focus-within { + visibility: visible; pointer-events: auto; clip-path: inset(0 0 0 0 round 12px); + transition: clip-path .28s cubic-bezier(.2, .8, .2, 1), visibility 0s; transition-delay: 0s, 0s; } +.hl-fabmenu > * { border: 0; border-radius: 8px; padding: 10px 16px; background: #262d3b; color: var(--fg); cursor: pointer; + font: 700 15px "DejaVu Web", sans-serif; text-align: left; white-space: nowrap; text-decoration: none; display: block; + opacity: 0; transform: translateY(8px); transition: opacity .15s, transform .15s; transition-delay: .2s; } +.hl-fab:has(.fab:hover) .hl-fabmenu > *, .hl-fab:has(.fab:focus-visible) .hl-fabmenu > *, +.hl-fabmenu:hover > *, .hl-fabmenu:focus-within > * { opacity: 1; transform: none; } +.hl-fab:has(.fab:hover) .hl-fabmenu > :nth-last-child(1) { transition-delay: .06s; } +.hl-fab:has(.fab:hover) .hl-fabmenu > :nth-last-child(2) { transition-delay: .13s; } +.hl-fab:has(.fab:hover) .hl-fabmenu > :nth-last-child(3) { transition-delay: .2s; } +.hl-fab:has(.fab:hover) .hl-fabmenu > :nth-last-child(4) { transition-delay: .27s; } +.hl-fabmenu:hover > * { transition-delay: 0s !important; } /* already open: no replay while on it */ +.hl-fabmenu > :hover { background: #1d222d; color: var(--accent); } +.hl-fabmenu > .def { box-shadow: inset 3px 0 0 var(--accent); } +.hl-add.fab { width: 60px; height: 60px; border: 0; border-radius: 50%; + background: var(--accent); color: var(--bg); font: 400 38px/1 "DejaVu Web", sans-serif; cursor: pointer; + display: flex; align-items: center; justify-content: center; padding-bottom: 4px; + box-shadow: 0 6px 18px rgba(0, 0, 0, .45); } +.hl-add.fab:hover { filter: brightness(.88); } +.hl-add.fab:active { filter: brightness(.75); } +body:has(.hl-fab) .sound-off { right: 100px; } /* beside the +, clear of its menu */ +#page.page-health { padding-bottom: 80px; } /* the last card scrolls clear of the + */ +.hl-note, .hl-empty { padding: 14px 18px; border-radius: 14px; background: var(--card); color: var(--muted); line-height: 1.5; } +.hl-note { background: #2a2416; border-left: 4px solid var(--accent); color: var(--fg); } +.hl-note a { color: var(--accent); } +.hl-link { border: 0; background: none; padding: 0; color: var(--cool); font: inherit; cursor: pointer; text-decoration: underline; } + +/* ---- tiles ------------------------------------------------------------------------- */ +.hl-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 10px; } +.hl-tiles > a { color: inherit; text-decoration: none; } +.hl-tiles > a:hover { background: #1d222d; } .hl-tiles > a:hover span { color: var(--accent); } +.hl-tiles > * { background: var(--card); border-radius: 12px; padding: 10px 14px; display: flex; flex-direction: column; gap: 3px; } +.hl-tiles > * > span:first-child { color: var(--dim); font-size: 11.5px; text-transform: uppercase; letter-spacing: .03em; } +.hl-tiles b { font-size: 21px; } .hl-tiles b em { font-style: normal; font-weight: 400; font-size: 13px; color: var(--muted); } +.hl-tiles small { color: var(--muted); font-size: 12.5px; } +.hl-when { color: var(--dim) !important; font-size: 12.5px; } +.hl-when.stale { color: #ff9f5a !important; } + +/* ---- cards ------------------------------------------------------------------------- */ +.hl-grid.hl-bgrid { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } +.hl-col { display: flex; flex-direction: column; gap: 14px; min-width: 0; } +/* Body ▸ Measurements: 10 a page (?mp=N#measurements), pager in the head and under the table */ +.hl-pager { display: flex; flex-wrap: wrap; gap: 4px; margin-left: auto; } +.hl-pager .hl-mini { min-width: 30px; text-align: center; text-decoration: none; } +.hl-pager .hl-mini.on { background: var(--accent); color: var(--bg); } +.hl-pager .hl-mini.off { opacity: .35; pointer-events: none; } +.hl-pfoot { display: flex; justify-content: flex-end; margin-top: 8px; } +.hl-grid { display: grid; grid-template-columns: minmax(300px, 420px) minmax(0, 1fr); gap: 14px; align-items: start; } +.hl-card { background: var(--card); border-radius: 12px; padding: 12px 16px; min-width: 0; } +.hl-card h2 { margin: 0 0 8px; font: 700 15.5px "DejaVu Web", sans-serif; } +.hl-card h2 small { color: var(--dim); font-weight: 400; font-size: 13.5px; margin-left: 8px; } +.hl-card h2.h2b { margin-top: 18px; } +.hl-fat table { width: 100%; border-collapse: collapse; } +.hl-fat td { padding: 6px 4px; border-bottom: 1px solid #1f2430; vertical-align: top; } +.hl-fat td small { display: block; color: var(--dim); font-size: 12.5px; } +.hl-fat td.num { text-align: right; white-space: nowrap; font-weight: 700; padding-left: 12px; } +.hl-fat td.cls { color: var(--muted); font-size: 13.5px; padding-left: 12px; } +.hl-fat tr.off td { color: var(--dim); font-weight: 400; } +.hl-dl { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 8px 18px; margin: 0; } +.hl-dl dt { color: var(--muted); } .hl-dl dd { margin: 0; } .hl-dl small { color: var(--dim); } +.hl-fine { margin: 14px 0 0; color: var(--dim); font-size: 13px; line-height: 1.45; } +.hl-mini { border-radius: 8px; padding: 6px 12px; background: #262d3b; color: var(--fg); font-size: 14px; text-decoration: none; } +.hl-mini:hover { color: var(--accent); } + +/* ---- charts ------------------------------------------------------------------------ */ +.hl-chead { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; } +.hl-chead h2 { margin: 0; } +.hl-seg { display: flex; border-radius: 10px; background: #1b1f29; overflow: hidden; } +.hl-seg a, .hl-seg button { border: 0; background: none; padding: 7px 13px; color: var(--muted); font: 14px "DejaVu Web", sans-serif; + cursor: pointer; text-decoration: none; } +.hl-seg .on { background: #262d3b; color: var(--accent); } +.hl-svg { width: 100%; height: auto; max-height: 300px; display: block; margin: 0 auto; font: 9px "DejaVu Web", sans-serif; } /* health.js keeps the text 11.5 px */ +.hl-svg line, .hl-svg path { vector-effect: non-scaling-stroke; } +.hl-svg .grid { stroke: #232937; stroke-width: 1; } +.hl-svg .yl { fill: var(--dim); text-anchor: end; } +.hl-svg .xl { fill: var(--dim); text-anchor: middle; } +.hl-svg .band.ok { fill: rgba(127, 214, 163, .07); } +.hl-svg .ln { fill: none; stroke-width: 2.2; stroke-linejoin: round; stroke-linecap: round; } +.hl-svg .dt { stroke: var(--card); stroke-width: 1.5; } +.hl-none { color: var(--dim); } +.hl-keys { display: flex; flex-wrap: wrap; gap: 6px 16px; margin-top: 8px; color: var(--muted); font-size: 13px; } +.hl-keys span { display: inline-flex; align-items: center; gap: 6px; } +.hl-keys i { width: 14px; height: 3px; border-radius: 2px; background: var(--c); } +/* series colours */ +.c-w { --c: var(--accent); } .c-x { --c: var(--cool); } .c-b { --c: #7fd6a3; } +.c-navy { --c: var(--cool); } .c-rfm { --c: #7fd6a3; } .c-ymca { --c: #c792ea; } .c-scale { --c: #9aa4b8; } +.hl-k { display: inline-block; width: 10px; height: 10px; border-radius: 3px; background: var(--c); margin-right: 8px; } +.hl-svg .ln { stroke: var(--c); } .hl-svg .dt { fill: var(--c); } +.hl-svg .ln.c-scale { stroke-dasharray: 4 3; } +.c-s { --c: #9c8cff; } .c-hl { --c: var(--cool); } .c-hh { --c: #ff6b7a; } .c-a { --c: var(--accent); } +.hl-svg .br { fill: var(--c); opacity: .85; } +.hl-svg .br.short { fill: #ff6b7a; } +.hl-svg .br:hover { opacity: 1; } + +/* ---- measurement list -------------------------------------------------------------- */ +.hl-scroll { overflow-x: auto; } +.hl-scroll.tall { max-height: 420px; overflow-y: auto; } +.hl-scroll.tall thead th { position: sticky; top: 0; background: var(--card); z-index: 1; } +.hl-list table { width: 100%; border-collapse: collapse; font-size: 13.5px; } +.hl-list th { text-align: left; font-weight: 400; font-size: 13px; color: var(--dim); padding: 6px 10px; border-bottom: 1px solid #262c39; white-space: nowrap; } +.hl-list th small { color: #4a5266; } +.hl-list td { padding: 5px 10px; border-bottom: 1px solid #1f2430; white-space: nowrap; } +.hl-list td.num { text-align: right; } .hl-list th:not(:first-child):not(:last-child) { text-align: right; } +.hl-list td.nt { color: var(--muted); white-space: normal; min-width: 160px; } +.hl-list tbody tr[data-day] { cursor: pointer; } +.hl-list tbody tr:hover { background: #1d222d; } +.hl-list tbody tr:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } + +/* ---- dialog (looks like the new-event form) ---------------------------------------- */ +.hl-modal[hidden] { display: none !important; } +.hl-modal { position: fixed; inset: 0; z-index: 10; display: flex; align-items: center; justify-content: center; } +.hl-box { display: flex; flex-direction: column; gap: 14px; } +.hl-ftitle { font: 700 22px "DejaVu Web", sans-serif; margin-right: 34px; } +.hl-box label > span:first-child { display: block; color: var(--dim); font-size: 12.5px; margin-bottom: 4px; } +.hl-box input, .hl-box textarea { font: 16px "DejaVu Web", sans-serif; color: var(--fg); background: #1d222d; + border: 1px solid #2c3343; border-radius: 8px; padding: 7px 10px; box-sizing: border-box; min-width: 0; color-scheme: dark; } +.hl-box input::placeholder, .hl-box textarea::placeholder { color: #4a5266; } +.hl-box :focus { outline: 2px solid var(--accent); outline-offset: -1px; } +.hl-box .bad { border-color: #ff7a7a; } +.hl-day input { width: 180px; } +.hl-fields { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px 12px; } +.hl-in { display: flex; align-items: center; gap: 6px; } +.hl-in input { width: 100%; text-align: right; } +.hl-in i { font-style: normal; color: var(--dim); font-size: 13px; width: 22px; } +.hl-box textarea { width: 100%; resize: vertical; line-height: 1.4; } +.hl-tip { margin: 0; color: var(--dim); font-size: 13px; line-height: 1.45; } +.hl-actions { display: flex; align-items: center; justify-content: flex-end; gap: 14px; flex-wrap: wrap; } +.hl-ferr { flex: 1; color: #ff7a7a; font-size: 15px; min-width: 120px; } +.hl-save { padding: 9px 18px; border: 0; border-radius: 10px; cursor: pointer; font: 700 16px "DejaVu Web", sans-serif; + background: var(--accent); color: var(--bg); } +.hl-save:disabled { opacity: .5; cursor: wait; } +.hl-del { padding: 9px 14px; border: 0; border-radius: 10px; cursor: pointer; font: 14px "DejaVu Web", sans-serif; + background: #262d3b; color: var(--muted); } +.hl-del.armed { background: #4a1f24; color: #ff9a9a; } + +/* ---- narrow ------------------------------------------------------------------------ */ +@media (max-width: 899px) { .hl-grid, .hl-grid.hl-bgrid { grid-template-columns: minmax(0, 1fr); } } +@media (max-width: 499px) { + .hl-card { padding: 14px 12px; } + .hl-tiles { grid-template-columns: 1fr 1fr; gap: 8px; } + .hl-tiles > * { padding: 12px; } .hl-tiles b { font-size: 22px; } + .hl-fab { right: 14px; bottom: 14px; } .hl-add.fab { width: 54px; height: 54px; } + .hl-dl { grid-template-columns: minmax(0, 1fr); gap: 2px; } .hl-dl dd { margin-bottom: 8px; } + .hl-fields { grid-template-columns: 1fr 1fr; } + .hl-seg a, .hl-seg button { padding: 7px 9px; font-size: 13px; } +} + + +/* ---- ranges popup (hover / focus over a category) ---------------------------------- */ +.hl-pin { position: relative; cursor: help; border-bottom: 1px dotted currentColor; outline: none; } +.hl-pop { display: none; position: absolute; z-index: 30; top: calc(100% + 8px); left: 50%; transform: translateX(-50%); + width: 300px; padding: 12px 14px; border-radius: 10px; background: #232a38; box-shadow: 0 8px 24px rgba(0, 0, 0, .5); + color: var(--fg); font: 13px/1.45 "DejaVu Web", sans-serif; text-align: left; text-transform: none; cursor: default; } +.hl-pin:hover .hl-pop, .hl-pin:focus .hl-pop, .hl-pin:focus-within .hl-pop { display: flex; flex-direction: column; gap: 8px; } +.hl-tiles > :last-child .hl-pop { left: auto; right: -12px; transform: none; } +/* with health.js the pin's own popup stays hidden; a copy floats on (see health.js) */ +.hl-js .hl-pin .hl-pop { display: none; } +.hl-pop.hl-float { position: fixed; display: flex; flex-direction: column; gap: 8px; transform: none; pointer-events: none; } +.hl-pop.hl-float[hidden] { display: none; } +.hl-pop strong { font-size: 14px; } +.hl-pop small { color: var(--dim); font-size: 12px; } +.hl-pl { color: var(--muted); } +.hl-bar { position: relative; display: block; height: 10px; margin: 4px 0 2px; } +.hl-bar i { position: absolute; top: 0; bottom: 0; } +.hl-bar i:first-child { border-radius: 5px 0 0 5px; } .hl-bar i:last-of-type { border-radius: 0 5px 5px 0; } +.hl-bar .s1 { background: #5cc8ff88; } .hl-bar .s2 { background: #7fd6a3; } .hl-bar .s3 { background: #ffb33acc; } .hl-bar .s4 { background: #ff6b7acc; } +.hl-bar b { position: absolute; top: -4px; bottom: -4px; width: 4px; margin-left: -2px; border-radius: 2px; background: var(--fg); box-shadow: 0 0 0 2px #232a38; } +.hl-pt { display: table; width: 100%; border-collapse: collapse; } +.hl-pt > span { display: table-row; } +.hl-pt em { display: table-cell; font-style: normal; padding: 2px 4px; white-space: nowrap; } +.hl-pt > span:first-child em { color: var(--dim); font-size: 12px; } +.hl-pt > span.me em { color: var(--accent); font-weight: 700; } +.hl-pt2 em:last-child { text-align: right; } + +/* ---- watch data: sleep stages, zones -------------------------------------------------- */ +.st-deep { --c: #4f6bed; } .st-light { --c: #5cc8ff; } .st-rem { --c: #c792ea; } .st-asleep { --c: #7a8399; } .st-awake { --c: #ffb33a; } +.z0 { --c: #4a5266; } .z1 { --c: #8fa3bf; } .z2 { --c: #5cc8ff; } .z3 { --c: #7fd6a3; } .z4 { --c: #ffb33a; } .z5 { --c: #ff6b7a; } +.c-st { --c: #7fd6a3; } .c-en { --c: var(--accent); } +.hl-svg rect[class^="st-"], .hl-svg a rect { fill: var(--c); } +.hl-svg a:hover rect { opacity: .75; } +.hl-svg .goal { stroke: var(--fg); stroke-width: 1.2; stroke-dasharray: 5 4; opacity: .6; } +.hl-svg .band.z1, .hl-svg .band.z2, .hl-svg .band.z3, .hl-svg .band.z4, .hl-svg .band.z5 { fill: var(--c); opacity: .13; } +.hl-svg .ln.hr { stroke: #ff8a96; stroke-width: 1.8; } +.hl-keys i[class^="st-"], .hl-keys i[class^="z"] { background: var(--c); height: 10px; width: 10px; border-radius: 3px; } +.hl-k[class*=" z"] { background: var(--c); } +.hl-rangebar { margin: 4px 0 -4px; } +.hl-rangebar h2 { margin: 0; font: 700 18px "DejaVu Web", sans-serif; } +.hl-rangebar h2 small { color: var(--dim); font-weight: 400; font-size: 14px; margin-left: 8px; } +/* one night: numbers left, stages right */ +.hl-nightwrap { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 18px; align-items: center; } +.hl-nightwrap .hl-nightgrid { flex-direction: column; align-items: flex-start; margin: 0; } +.hl-hyp { max-height: 190px; } +@media (max-width: 899px) { .hl-nightwrap { grid-template-columns: minmax(0, 1fr); } } +/* one night */ +.hl-nightgrid { display: flex; flex-wrap: wrap; align-items: center; gap: 14px 28px; margin-bottom: 8px; } +.hl-score { display: flex; flex-direction: column; align-items: center; justify-content: center; width: 72px; height: 72px; flex: none; + border-radius: 50%; border: 4px solid #4f6bed; box-sizing: border-box; } +.hl-score b { font: 700 24px/1 "DejaVu Web", sans-serif; } .hl-score > span:not(.hl-pop) { color: var(--dim); font-size: 12px; } +.hl-score.hl-pin, .hl-tiles > .hl-pin { border-bottom: 0; } +.hl-score.hl-pin { border: 4px solid #4f6bed; } +.hl-nstats { display: grid; grid-template-columns: repeat(3, max-content); gap: 8px 22px; margin: 0; } +.hl-nstats div { display: flex; flex-direction: column; gap: 2px; } +.hl-nstats dt { color: var(--dim); font-size: 11px; text-transform: uppercase; } .hl-nstats dd { margin: 0; font-size: 14.5px; } +/* findings */ +.hl-find dl { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 7px 16px; margin: 0; line-height: 1.45; font-size: 13.5px; } +.hl-find dt { color: var(--accent); } .hl-find dd { margin: 0; } +/* small bars */ +.hl-mbar { display: inline-block; width: 80px; height: 8px; border-radius: 4px; background: #232937; margin-right: 8px; vertical-align: 1px; overflow: hidden; } +.hl-mbar i { display: block; height: 100%; background: var(--c, #9c8cff); border-radius: 4px; } +.hl-zones { width: 100%; border-collapse: collapse; table-layout: fixed; } +.hl-zones td:nth-child(1) { width: 36%; } .hl-zones td:nth-child(3) { width: 26%; } .hl-zones td { overflow: hidden; text-overflow: ellipsis; } +.hl-zones td { padding: 6px 6px; border-bottom: 1px solid #1f2430; white-space: nowrap; } +.hl-zones .hl-mbar { width: 100%; margin: 0; display: block; } +.hl-zs { display: inline-flex; width: 120px; height: 8px; border-radius: 4px; overflow: hidden; background: #232937; vertical-align: middle; } +.hl-zs i { display: block; height: 100%; background: var(--c); } +.dim { color: var(--dim); } +.hl-list tbody tr[data-href] { cursor: pointer; } +.hl-list tbody tr.sel td { background: #222837; } +.hl-wd td { padding: 6px 8px; } +@media (max-width: 499px) { .hl-find dl { grid-template-columns: minmax(0, 1fr); gap: 2px; } .hl-find dd { margin-bottom: 10px; } .hl-mbar { width: 50px; } } +.hl-hr { max-height: 380px; } + +/* ---- filters, hover tips, three-up ------------------------------------------------- */ +.hl-filters { display: flex; flex-wrap: wrap; gap: 8px; } +.hl-three { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 12px; align-items: start; } +@media (max-width: 1399px) { .hl-three { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +@media (max-width: 899px) { .hl-three { grid-template-columns: minmax(0, 1fr); } } +.hl-svg .hits rect { fill: transparent; cursor: crosshair; } +.hl-svg .hits rect[data-href] { cursor: pointer; } +.hl-svg .hits rect.on { fill: rgba(255, 255, 255, .07); } +.hl-tipbox { position: fixed; z-index: 30; pointer-events: none; display: flex; flex-direction: column; gap: 2px; + padding: 7px 10px; border-radius: 8px; background: #2a3242; box-shadow: 0 6px 18px rgba(0, 0, 0, .45); + font: 12.5px/1.35 "DejaVu Web", sans-serif; color: var(--fg); white-space: nowrap; } +.hl-tipbox[hidden] { display: none; } +.hl-tipbox b { font-weight: 700; } .hl-tipbox span { color: var(--muted); } +.hl-tt { border-bottom: 1px dotted #4a5266; } +.hl-tt .hl-pop { font-weight: 400; width: 320px; left: 0; transform: none; } +.st-nap { --c: #ff8fc8; } +.hl-scroll { scrollbar-color: #3a4254 transparent; color-scheme: dark; } +.hl-svg rect.tip { cursor: crosshair; } .hl-svg rect.tip.on { opacity: .75; stroke: var(--fg); stroke-width: 1; } +.hl-hr-s { max-height: 230px; } .hl-wstats { grid-template-columns: repeat(4, max-content); margin-bottom: 8px; } .hl-chead .hl-mini { font-size: 13px; } +@media (max-width: 699px) { .hl-wstats, .hl-nstats { grid-template-columns: repeat(2, minmax(0, 1fr)); } } +.c-fit { --c: var(--cool); } .c-fat { --c: #ff8fc8; } .c-form { --c: var(--accent); } .c-vit { --c: #7fd6a3; } +.hl-wstats.hl-w5 { grid-template-columns: repeat(5, max-content); } +.eff-easy { color: var(--muted); } .eff-maintaining { color: #5cc8ff; } .eff-improving { color: #7fd6a3; } .eff-very-hard { color: #ff9f5a; } +.c-hr { --c: #7fd6a3; } +.hl-tipbox span { display: flex; align-items: center; gap: 6px; } .hl-tipbox i { width: 8px; height: 8px; border-radius: 50%; background: var(--c); flex: none; } +@media (max-width: 699px) { .hl-wstats.hl-w5 { grid-template-columns: repeat(2, minmax(0, 1fr)); } } + +/* ---- Heart: blood pressure + oxygen ---------------------------------------------------- */ +.c-bs { --c: #ff6b7a; } .c-bd { --c: #ffb3a1; } .c-ox { --c: var(--cool); } +.hl-svg .band.high { fill: rgba(255, 107, 122, .07); } +/* category badge (calc.bp_class / spo2_class) */ +.hl-cls { display: inline-block; padding: 0 6px; border-radius: 6px; font-size: 12px; line-height: 18px; white-space: nowrap; } +.hl-cls.ok { background: rgba(127, 214, 163, .15); color: #7fd6a3; } +.hl-cls.mid { background: rgba(255, 179, 58, .15); color: var(--accent); } +.hl-cls.high { background: rgba(255, 140, 90, .18); color: #ff9a6a; } +.hl-cls.vhigh { background: rgba(255, 107, 122, .2); color: #ff6b7a; } +.hl-modal [data-for][hidden] { display: none; } +/* each vitals card: chart, then its readings */ +.hl-rhead { display: flex; align-items: baseline; gap: 10px; margin-top: 14px; } +.hl-rhead h3 { margin: 0; font: 700 15px "DejaVu Web", sans-serif; } +.hl-rhead h3 small { color: var(--dim); font-weight: 400; margin-left: 6px; } +.hl-readings { width: 100%; margin-top: 6px; } +.hl-readings tr[data-vital] { cursor: pointer; } +.hl-readings tr[data-vital]:hover td { background: #1d222d; } +/* a card's add button: just a yellow + */ +.hl-plus { margin-left: auto; border: 0; background: none; padding: 0 4px; color: var(--accent); cursor: pointer; + font: 400 28px/1 "DejaVu Web", sans-serif; } +/* the add dialog's tabs (one per kind; hidden while editing) */ +.hl-atabs { display: flex; gap: 4px; margin: 0 34px 12px 0; border-bottom: 1px solid #262c39; } +.hl-atabs[hidden], .hl-mform[hidden], .hl-vform[hidden] { display: none; } +.hl-atabs button { border: 0; background: none; color: var(--muted); padding: 8px 12px; margin-bottom: -1px; cursor: pointer; + border-bottom: 3px solid transparent; font: 700 14px "DejaVu Web", sans-serif; } +.hl-atabs button:hover { color: var(--fg); } +.hl-atabs button.on { color: var(--accent); border-bottom-color: var(--accent); } +.hl-ftitle:empty { display: none; } + +/* ---- the report for a doctor (/health/report): a document; printed light, only .rp ---------- */ +.rp-bar { justify-content: space-between; } +.hl-btn { border: 0; border-radius: 10px; padding: 9px 16px; background: var(--accent); color: var(--bg); cursor: pointer; + font: 700 14px "DejaVu Web", sans-serif; } +.rp { max-width: 1000px; width: 100%; margin: 0 auto; background: var(--card); border-radius: 14px; padding: 28px 36px; + box-sizing: border-box; font-size: 14.5px; line-height: 1.45; } +.rp h1 { margin: 0; font: 700 26px "DejaVu Web", sans-serif; } +.rp-head p { margin: 4px 0 0; color: var(--muted); } +.rp-who { display: flex; flex-wrap: wrap; gap: 4px 22px; margin: 12px 0 0; } +.rp-who dt { color: var(--muted); } .rp-who dd { margin: 0 0 0 -16px; font-weight: 700; } +.rp-src, .rp-ref, .rp-fine { color: var(--muted); font-size: 13px; } +.rp-sec { margin-top: 22px; padding-top: 16px; border-top: 1px solid #262c39; break-inside: avoid; } +.rp-sec h2 { margin: 0 0 8px; font: 700 18px "DejaVu Web", sans-serif; } +.rp-sec h2 small, .rp-sec h3 small { color: var(--muted); font-weight: 400; font-size: 13px; margin-left: 6px; } +.rp-sec h3 { margin: 10px 0 4px; font: 700 14px "DejaVu Web", sans-serif; color: var(--muted); } +.rp-t { width: 100%; border-collapse: collapse; } +.rp-t th { text-align: left; font-weight: 400; color: var(--muted); width: 160px; padding: 4px 10px 4px 0; vertical-align: top; } +.rp-t td { padding: 4px 10px 4px 0; vertical-align: top; } +.rp-t td small { color: var(--muted); } +.rp-list { margin-top: 10px; font-size: 13px; } .rp-list th { width: auto; border-bottom: 1px solid #262c39; } +.rp-chart { margin-top: 8px; } .rp-chart .hl-svg { width: 100%; height: auto; max-height: none; } +.rp-none { color: var(--muted); margin: 0; } +@media print { + @page { size: A4; margin: 14mm; } + body, #page { background: #fff !important; color: #000 !important; padding: 0 !important; } + body > *:not(#page), #page > :not(.hl), .hl > :not(.rp), .hl-fab, .sound-off { display: none !important; } + .rp { max-width: none; padding: 0; background: none; border-radius: 0; color: #000; font-size: 11pt; } + .rp-head p, .rp-src, .rp-ref, .rp-fine, .rp-t th, .rp-t td small, .rp-who dt, .rp-sec h2 small, .rp-sec h3 { color: #444 !important; } + .rp-sec { border-top-color: #bbb; } + .rp-list th { border-bottom-color: #bbb; } + .hl-cls { background: none !important; color: #000 !important; padding: 0; } .hl-cls::before { content: "("; } .hl-cls::after { content: ")"; } + .hl-svg text { fill: #333 !important; } .hl-svg .grid { stroke: #ddd !important; } + .hl-svg .band.ok { fill: rgba(0, 150, 80, .08) !important; } .hl-svg .band.high { fill: rgba(220, 0, 40, .07) !important; } +} + +/* ---- block layout (tab.html, blocks.py): rows of tiles and cards, each block --f of its row + (flex-basis exact with the gaps: n blocks whose --f adds up to 1 fill the row) ---------- */ +.hl-blocks { --gap: 12px; display: flex; flex-wrap: wrap; gap: var(--gap); align-items: flex-start; } +.hl-tiles.hl-blocks { --gap: 10px; align-items: stretch; } +.hl-blocks > .hl-blk { flex: 0 0 calc((100% + var(--gap)) * var(--f) - var(--gap)); min-width: 0; box-sizing: border-box; } +.hl-cards > .hl-blk > .hl-card, .hl-cards > .hl-blk > .hl-empty { margin: 0; } +body:not(.hl-editing) .hl-void { display: none; } +@media (max-width: 1099px) { /* narrower: thirds → halves, two thirds → whole */ + .hl-cards > .hl-blk[data-w="33"] { --f: .5; } .hl-cards > .hl-blk[data-w="66"] { --f: 1; } + .hl-tiles > .hl-blk[data-w="10"], .hl-tiles > .hl-blk[data-w="15"] { --f: .2; } +} +@media (max-width: 699px) { /* phones: two tiles a row, cards full width */ + .hl-tiles > .hl-blk { --f: .5 !important; } .hl-cards > .hl-blk { --f: 1 !important; } +} + +/* ---- edit mode (⋮ ▸ Edit layout, layout.js) ---- */ +.hl-editing .hl-blk { position: relative; outline: 2px dashed #3a4256; outline-offset: 2px; } +.hl-editing .hl-blocks { margin-top: 8px; row-gap: calc(var(--gap) + 14px); } /* room for the toolbars on the outlines */ +.hl-editing .hl-blk > :not(.hl-bt) { pointer-events: none; } +.hl-editing .hl-void { opacity: .55; } +.hl-editing .hl-blk.dragging { opacity: .35; } +.hl-editing .hl-fab { display: none; } +.hl-bt { position: absolute; top: -13px; right: 6px; z-index: 3; display: flex; align-items: center; gap: 3px; padding: 2px; + border-radius: 8px; background: #0f131a; box-shadow: 0 2px 8px rgba(0, 0, 0, .5); } +.hl-bt button, .hl-bt .hl-grip { border: 0; border-radius: 6px; padding: 2px 5px; background: #262d3b; color: var(--muted); + font: 700 11.5px "DejaVu Web", sans-serif; cursor: pointer; } +.hl-bt button:hover { color: var(--fg); } .hl-bt button.on { background: var(--accent); color: var(--bg); } +.hl-bt .hl-grip { cursor: grab; touch-action: none; font-size: 15px; padding: 0 6px; line-height: 20px; } +.hl-bt .hl-rm:hover { color: #ff6b7a; } +.hl-ebar { position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%); z-index: 12; display: flex; align-items: center; + gap: 8px; padding: 10px 12px; border-radius: 14px; background: var(--card); box-shadow: 0 10px 30px rgba(0, 0, 0, .6); } +.hl-ebar b { margin: 0 8px 0 4px; font-size: 14px; transition: color .15s; } +.hl-ebar b.hl-warn { color: var(--accent); } +.hl-ebar button { border: 0; border-radius: 9px; padding: 8px 14px; background: #262d3b; color: var(--fg); cursor: pointer; + font: 700 14px "DejaVu Web", sans-serif; } +.hl-ebar button:hover { background: #1d222d; } .hl-ebar .hl-esave { background: var(--accent); color: var(--bg); } +.hl-ebar .hl-ereset { color: var(--muted); } +/* Overview: the add picker (every block of every tab) */ +.hl-pick { position: fixed; left: 50%; bottom: 80px; transform: translateX(-50%); z-index: 12; width: min(760px, 94vw); + max-height: 60vh; overflow: auto; padding: 14px 16px; border-radius: 14px; background: var(--card); + box-shadow: 0 10px 30px rgba(0, 0, 0, .6); } +.hl-pick[hidden] { display: none; } +.hl-pick h3 { margin: 10px 0 6px; font: 700 13px "DejaVu Web", sans-serif; color: var(--muted); text-transform: uppercase; letter-spacing: .03em; } +.hl-pick h3:first-child { margin-top: 0; } +.hl-pick div { display: flex; flex-wrap: wrap; gap: 6px; } +.hl-pick button { border: 0; border-radius: 8px; padding: 7px 12px; background: #262d3b; color: var(--fg); cursor: pointer; + font: 13.5px "DejaVu Web", sans-serif; } +.hl-pick button:hover { color: var(--accent); } +.hl-pick button small { color: var(--dim); margin-left: 6px; } +.hl-pick button:disabled { opacity: .35; cursor: default; } +.hl-blk.hl-loading small, .hl-blk.hl-loading .hl-none { animation: hl-pulse 1.2s ease-in-out infinite; } +@keyframes hl-pulse { 50% { opacity: .4; } } + +/* ---- a card's inside follows the card's own width (container queries), not the window's: + at 33 % / 50 % a card is narrow even on a wide screen ---------------------------------- */ +.hl-cards > .hl-blk { container-type: inline-size; } +@container (max-width: 760px) { + .hl-wstats.hl-w5, .hl-wstats { grid-template-columns: repeat(auto-fill, minmax(118px, max-content)); } + .hl-nightwrap { grid-template-columns: minmax(0, 1fr); } /* stages under the score */ +} +@container (max-width: 420px) { + .hl-nstats, .hl-wstats, .hl-wstats.hl-w5 { grid-template-columns: repeat(2, minmax(0, 1fr)); } +} +/* a tile shown away from its tab links there: "›" after its name */ +.hl-tiles > a.hl-blk > span:first-child::after { content: " ›"; } diff --git a/dashboard/plugins/health/static/health.js b/dashboard/plugins/health/static/health.js new file mode 100644 index 0000000..7dec4d6 --- /dev/null +++ b/dashboard/plugins/health/static/health.js @@ -0,0 +1,243 @@ +// Health pages. The floating + (every tab) opens the add dialog on the tab's default kind +// (Heart: blood pressure, else body measurements); hovering it lists all of them. The dialog +// has a tab per kind; a click on a row edits it (a measured day on Body, a reading on Heart). +// Empty measurement fields show your last value in grey. Chart tabs on Body: Weight / Waist / +// BMI / Body fat (remembered per browser). After a save the page's .hl is swapped for a fresh +// server copy (everything shown is computed there). No browser dialogs. +(function () { + const post = async (url, data) => { + const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw Object.assign(new Error(j.error || `Error ${r.status}`), { field: j.field }); + return j; + }; + const modal = (on) => document.body.classList.toggle("modal", on); // dash.js: keys off + const store = { get(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }, + set(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* private mode */ } } }; + + // charts are SVGs that scale with their box; keep their text 11.5 px at any width + const fitText = () => document.querySelectorAll(".hl-svg").forEach((svg) => { + const r = svg.getBoundingClientRect(), vb = svg.viewBox.baseVal; // drawn scale ("meet") + const k = Math.min(r.width / vb.width, r.height / vb.height); + if (k) svg.style.fontSize = (11.5 / k).toFixed(2) + "px"; + }); + fitText(); + addEventListener("resize", fitText); + document.addEventListener("click", (e) => { if (e.target.closest(".hl-ctabs")) requestAnimationFrame(fitText); }); + + // chart hover: each bucket has an invisible strip with its values (data-tip); a click on + // one with data-href opens it (a night). Touch: tap shows the tip. + const tipBox = document.createElement("div"); + tipBox.className = "hl-tipbox"; tipBox.hidden = true; + document.body.appendChild(tipBox); + let tipOn = null; + const showTip = (r, x, y) => { + if (tipOn !== r) { tipOn?.classList.remove("on"); r.classList.add("on"); tipOn = r; } + const [head, ...rest] = r.dataset.tip.split("\n"); + tipBox.replaceChildren(Object.assign(document.createElement("b"), { textContent: head }), + ...rest.map((t) => { // "c-fit|Fitness: 18" → a coloured dot + text + const span = document.createElement("span"), m = /^([\w-]+)\|(.*)$/.exec(t); + if (m) span.append(Object.assign(document.createElement("i"), { className: m[1] }), m[2]); + else span.textContent = t; + return span; + })); + tipBox.hidden = false; + const w = tipBox.offsetWidth, h = tipBox.offsetHeight; + tipBox.style.left = Math.max(8, Math.min(innerWidth - w - 8, x + 14)) + "px"; + tipBox.style.top = (y - h - 12 < 8 ? y + 18 : y - h - 12) + "px"; + }; + const hideTip = () => { tipBox.hidden = true; tipOn?.classList.remove("on"); tipOn = null; }; + document.addEventListener("pointermove", (e) => { + const r = e.target.closest?.(".hl-svg [data-tip]"); + if (r) showTip(r, e.clientX, e.clientY); else if (tipOn) hideTip(); + }); + document.addEventListener("click", (e) => { + const r = e.target.closest?.(".hl-svg [data-tip]"); + if (!r) return; + if (r.dataset.href && (e.pointerType !== "touch" || tipOn === r)) location.href = r.dataset.href; + else showTip(r, e.clientX, e.clientY); + }); + addEventListener("scroll", hideTip, { passive: true }); + + // .hl-pin popups: shown in one box on (a copy of the pin's .hl-pop), not inside the + // pin — cards are CSS containers (container-type), which trap their popups under the next + // card. Under the pin, centred on it, kept 8 px inside the window; above it if there's no + // room below. Without this script the CSS still shows them in place. + document.documentElement.classList.add("hl-js"); + const popBox = document.createElement("div"); + popBox.className = "hl-pop hl-float"; popBox.setAttribute("role", "tooltip"); popBox.hidden = true; + document.body.appendChild(popBox); + let popPin = null; + const placePop = () => { + const r = popPin.getBoundingClientRect(), w = popBox.offsetWidth, h = popBox.offsetHeight; + popBox.style.left = Math.max(8, Math.min(innerWidth - w - 8, r.left + r.width / 2 - w / 2)) + "px"; + popBox.style.top = (r.bottom + 8 + h <= innerHeight - 8 || r.top - 8 - h < 8 ? r.bottom + 8 : r.top - 8 - h) + "px"; + }; + const showPop = (pin) => { + const pop = pin.querySelector(".hl-pop"); + if (!pop || pin.closest(".hl-editing")) { hidePop(); return; } + if (popPin !== pin) { + popPin = pin; + popBox.innerHTML = pop.innerHTML; + popBox.style.width = getComputedStyle(pop).width; // .hl-tt pops are wider + } + popBox.hidden = false; + placePop(); + }; + const hidePop = () => { popBox.hidden = true; popPin = null; }; + document.addEventListener("pointerover", (e) => { + const pin = e.target.closest?.(".hl-pin"); + if (pin) showPop(pin); else if (popPin && popPin !== document.activeElement) hidePop(); + }); + document.addEventListener("focusin", (e) => { const pin = e.target.closest?.(".hl-pin"); if (pin) showPop(pin); }); + document.addEventListener("focusout", (e) => { if (e.target === popPin && !popPin.matches(":hover")) hidePop(); }); + addEventListener("scroll", () => { if (popPin) placePop(); }, { passive: true }); + addEventListener("resize", () => { if (popPin) placePop(); }); + + // rows that open a page (sleep nights, workouts) + const go = (tr) => { location.href = tr.dataset.href; }; + document.addEventListener("click", (e) => { const tr = e.target.closest("tr[data-href]"); if (tr && !e.target.closest("a")) go(tr); }); + document.addEventListener("keydown", (e) => { const tr = e.target.closest?.("tr[data-href]"); if (tr && e.key === "Enter") go(tr); }); + + // ---- the + (every page) and its dialog: a tab per kind — body measurements ("measure", + // one row per day), blood pressure ("bp"), blood oxygen ("ox"; one reading each). The + + // opens the page's default kind; hovering it lists all three (CSS). A click on a row edits: + // tr[data-day] a measured day, tr[data-vital] a reading — its tab, the tabs hidden. + // After a save the page's .hl (and the dialog's data) is swapped for a fresh server copy. + const box = document.getElementById("hl-add"); + if (!box) return; + const mform = box.querySelector(".hl-mform"), vform = box.querySelector(".hl-vform"); + const FIELDS = [...mform.querySelectorAll(".hl-fields input")].map((i) => i.name); + const VKEYS = { bp: ["sys", "dia"], ox: ["spo2"] }; + const TITLE = { measure: "Body measurements", bp: "Blood pressure", ox: "Blood oxygen" }; + const data = () => JSON.parse(document.getElementById("hl-adddata")?.textContent || "{}"); // {today, last, rows} + let kind = "measure", editing = null; // editing: the day (measure) or the reading id + const pad = (n) => String(n).padStart(2, "0"); + const form = () => (kind === "measure" ? mform : vform); + + const err = (m, field) => { + const f = form(); + f.querySelector(".hl-ferr").textContent = m || ""; + f.querySelectorAll(".bad").forEach((e) => e.classList.remove("bad")); + if (field && f.elements[field]) { f.elements[field].classList.add("bad"); f.elements[field].focus(); } + }; + function show(k, edit) { // switch the dialog to kind k + kind = k; + mform.hidden = k !== "measure"; vform.hidden = k === "measure"; + vform.querySelectorAll("[data-for]").forEach((el) => { el.hidden = el.dataset.for !== k; }); + box.querySelectorAll(".hl-atabs [data-akind]").forEach((t) => t.classList.toggle("on", t.dataset.akind === k)); + box.querySelector(".hl-atabs").hidden = !!edit; + box.querySelector(".hl-ftitle").textContent = edit ? "Edit: " + TITLE[k] : ""; + const del = form().querySelector(".hl-del"); + del.hidden = !edit; del.classList.remove("armed"); del.textContent = "Delete"; + err(""); + } + function fillMeasure(r) { // r = a measured day, or null for an empty one + const last = data().last || {}; + FIELDS.forEach((k) => { + const i = mform.elements[k]; + i.value = r && r[k] != null ? String(r[k]) : ""; + i.placeholder = last[k] != null ? String(last[k]) : ""; + }); + mform.elements.note.value = r ? r.note || "" : ""; + } + function openMeasure(day, edit) { + const r = (data().rows || {})[day] || null; + editing = edit && r ? day : null; + show("measure", !!editing); + mform.elements.day.value = day; + fillMeasure(r); + open((editing ? mform.elements.day : mform.elements.weight)); + } + function openVital(k, r) { // a new reading of kind k, or r to edit + const now = new Date(); + editing = r ? r.id : null; + show(r ? r.kind : k, !!r); + vform.elements.day.value = r ? r.day : data().today; + vform.elements.time.value = r ? r.time : `${pad(now.getHours())}:${pad(now.getMinutes())}`; + ["sys", "dia", "spo2"].forEach((f) => { vform.elements[f].value = r && r[f] != null ? String(r[f]) : ""; }); + vform.elements.note.value = r ? r.note || "" : ""; + open(vform.elements[r ? "day" : VKEYS[kind][0]]); + } + const openKind = (k) => (k === "measure" ? openMeasure(data().today, false) : openVital(k, null)); + function open(focus) { box.hidden = false; modal(true); focus.focus(); } + const close = () => { box.hidden = true; modal(false); }; + + async function refresh() { + const doc = new DOMParser().parseFromString(await (await fetch(location.href, { cache: "no-store" })).text(), "text/html"); + const fresh = doc.querySelector(".hl"); + if (fresh) document.querySelector(".hl").replaceWith(fresh); + const d = doc.getElementById("hl-adddata"); + if (d) document.getElementById("hl-adddata").textContent = d.textContent; + showChart(store.get("health.chart")); + fitText(); + } + async function send(url, body) { + const save = form().querySelector(".hl-save"); + save.disabled = true; + try { await post(url, body); close(); await refresh(); } + catch (x) { err(x.message, x.field); } + finally { save.disabled = false; } + } + + // body measurements: picking another day loads its values (a new day keeps what you typed) + mform.elements.day.addEventListener("change", () => { + const r = (data().rows || {})[mform.elements.day.value]; + if (r && r.day !== editing) fillMeasure(r); + }); + mform.addEventListener("submit", (e) => { + e.preventDefault(); + const d = { day: mform.elements.day.value, note: mform.elements.note.value }; + if (editing) d.was = editing; + FIELDS.forEach((k) => { d[k] = mform.elements[k].value.trim(); }); + send("/health/api/measure", d); + }); + vform.addEventListener("submit", (e) => { + e.preventDefault(); + const d = { id: editing, kind, day: vform.elements.day.value, time: vform.elements.time.value, note: vform.elements.note.value }; + VKEYS[kind].forEach((f) => { d[f] = vform.elements[f].value.trim(); }); + send("/health/api/vital", d); + }); + box.querySelectorAll(".hl-del").forEach((del) => del.addEventListener("click", () => { + if (!del.classList.contains("armed")) { del.classList.add("armed"); del.textContent = "Click again to delete"; return; } + if (kind === "measure") send("/health/api/measure/delete", { day: editing }); + else send("/health/api/vital/delete", { id: editing }); + })); + box.addEventListener("click", (e) => { + if (e.target.closest(".ec-x") || e.target.classList.contains("ec-back")) return close(); + const t = e.target.closest(".hl-atabs [data-akind]"); + if (t && t.dataset.akind !== kind) openKind(t.dataset.akind); + }); + addEventListener("keydown", (e) => { + if (box.hidden) return; + if (e.key === "Escape") close(); + if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) form().requestSubmit(); + }); + + // ---- chart tabs (Body) + function showChart(k) { + const tabs = [...document.querySelectorAll(".hl-ctabs [data-chart]")]; + if (!tabs.some((t) => t.dataset.chart === k)) k = "weight"; + tabs.forEach((t) => t.classList.toggle("on", t.dataset.chart === k)); + document.querySelectorAll(".hl-chart").forEach((c) => { c.hidden = c.dataset.chart !== k; }); + } + showChart(store.get("health.chart")); + + // ---- the page: one listener (.hl is replaced after every change) + const vitalOf = (tr) => JSON.parse(document.getElementById("hl-vitals")?.textContent || "{}")[tr.dataset.vital]; + document.addEventListener("click", (e) => { + if (!box.hidden) return; + const add = e.target.closest("[data-add]"); + if (add) { add.blur(); return openKind(add.dataset.add); } + const t = e.target.closest(".hl-ctabs [data-chart]"); + if (t) { store.set("health.chart", t.dataset.chart); return showChart(t.dataset.chart); } + const tr = e.target.closest("tr[data-day], tr[data-vital]"); + if (tr) return tr.dataset.vital ? openVital(null, vitalOf(tr)) : openMeasure(tr.dataset.day, true); + }); + document.addEventListener("keydown", (e) => { + const tr = e.target.closest?.("tr[data-day], tr[data-vital]"); + if (!tr || !box.hidden || !(e.key === "Enter" || e.key === " ")) return; + e.preventDefault(); + if (tr.dataset.vital) openVital(null, vitalOf(tr)); else openMeasure(tr.dataset.day, true); + }); +})(); diff --git a/dashboard/plugins/health/static/layout.js b/dashboard/plugins/health/static/layout.js new file mode 100644 index 0000000..d322ad6 --- /dev/null +++ b/dashboard/plugins/health/static/layout.js @@ -0,0 +1,185 @@ +// Health tabs: edit the layout (⋮ ▸ Edit layout → #edit). Each block gets a toolbar: a grip +// to drag it (mouse or touch — it moves among the blocks of its row kind as you go), its widths +// (tiles 10–33 %, cards 33–100 %) and, on Overview, ✕ to remove it. A bar at the bottom: +// Overview's "+ Add" (any block of any tab — it appears at once as a placeholder you can already +// move and size; its content is fetched alone, /health/api/block, and fills in when ready), +// Reset to default, Cancel, Save. Saving posts the order + widths (/health/api/layout) and just +// leaves edit mode — the page already shows the new layout. No browser dialogs. +(function () { + const data = document.getElementById("hl-layout"); + if (!data) return; + const L = JSON.parse(data.textContent); + const overview = L.tab === "overview"; + let editing = false, bar = null, pick = null; + + const post = async (url, body) => { + const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); + if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || `Error ${r.status}`); + }; + const reload = () => { location.href = location.pathname + location.search; }; + const blocks = () => [...document.querySelectorAll(".hl-blocks > .hl-blk")]; + const frac = (w) => (w === 33 ? 1 / 3 : w === 66 ? 2 / 3 : w / 100); + const items = () => blocks().map((b) => ({ id: b.dataset.id, w: Number(b.dataset.w) })); + + function toolbar(b) { + const tile = b.parentElement.dataset.kind === "tile"; + const t = document.createElement("div"); + t.className = "hl-bt"; + t.innerHTML = `⠿` + + (tile ? L.tile_w : L.card_w).map((w) => ``).join("") + + (overview ? `` : ""); + b.append(t); + mark(b); + } + const mark = (b) => b.querySelectorAll(".hl-bt [data-w]").forEach((x) => x.classList.toggle("on", x.dataset.w === b.dataset.w)); + + function enter() { + history.replaceState(null, "", location.pathname + location.search); + document.querySelectorAll("details.tabs-more[open]").forEach((d) => { d.open = false; }); + if (editing) return; + editing = true; + document.body.classList.add("hl-editing", "modal"); // modal: dash.js keys off + blocks().forEach(toolbar); + bar = document.createElement("div"); + bar.className = "hl-ebar"; + bar.innerHTML = `Editing the layout` + (overview ? `` : "") + + `` + + ``; + document.body.append(bar); + if (overview) { + pick = document.createElement("div"); + pick.className = "hl-pick"; pick.hidden = true; + const by = {}; + L.catalog.forEach((c) => { (by[c.tab] = by[c.tab] || []).push(c); }); + pick.innerHTML = Object.keys(L.tabs).filter((t) => by[t]).map((t) => + `

    ${L.tabs[t]}

    ${by[t].map((c) => ``).join("")}
    `).join(""); + document.body.append(pick); + } + } + + function leave() { // after Save: the page already is the new layout + editing = false; + document.body.classList.remove("hl-editing", "modal"); + document.querySelectorAll(".hl-bt").forEach((t) => t.remove()); + bar.remove(); pick?.remove(); bar = pick = null; + } + + // an added block: a placeholder now (movable, sizable), its content when the server has drawn it + function addBlock(c) { + const tile = c.kind === "tile"; + const ph = document.createElement("div"); + ph.className = "hl-blk hl-loading"; + ph.dataset.id = c.id; ph.dataset.w = c.w; ph.style.setProperty("--f", frac(c.w)); + ph.innerHTML = tile ? `${c.label}Loading…` + : `

    ${c.label}

    Loading…

    `; + document.querySelector(`.hl-blocks[data-kind="${c.kind}"]`).append(ph); + toolbar(ph); + ph.scrollIntoView({ behavior: "smooth", block: "nearest" }); + fetch(`/health/api/block?id=${encodeURIComponent(c.id)}&w=${c.w}`, { cache: "no-store" }) + .then((r) => (r.ok ? r.text() : Promise.reject(new Error(`Error ${r.status}`)))) + .then((html) => { + if (!ph.isConnected) return; // removed again meanwhile + const el = new DOMParser().parseFromString(html, "text/html").querySelector(".hl-blk"); + if (!el) throw new Error("Nothing came back"); + el.dataset.w = ph.dataset.w; el.style.setProperty("--f", ph.style.getPropertyValue("--f")); + ph.replaceWith(el); + if (editing) toolbar(el); + dispatchEvent(new Event("resize")); // health.js: chart text size + }) + .catch((x) => { + const s = ph.querySelector("small, .hl-none"); + if (s) s.textContent = `Couldn't load it (${x.message}) — it's still added; Save and reload.`; + }); + } + + async function save(list) { + try { await post("/health/api/layout", { tab: L.tab, items: list }); return true; } + catch (x) { bar.querySelector("b").textContent = x.message; return false; } + } + + // ---- toolbar + bar clicks. While editing nothing else on the page reacts — no link, tab, + // nav button, range or menu leads away (the bar says to save or cancel first). + const ours = (t) => t.closest(".hl-bt, .hl-ebar, .hl-pick"); + let flashT = 0; + function flash() { + const m = bar.querySelector("b"); + m.textContent = "Save or cancel first"; m.classList.add("hl-warn"); + clearTimeout(flashT); + flashT = setTimeout(() => { if (bar) { m.textContent = "Editing the layout"; m.classList.remove("hl-warn"); } }, 2200); + } + document.addEventListener("click", async (e) => { + if (!editing) return; + e.preventDefault(); // also for our own buttons: a tile's toolbar sits inside the tile — a link + if (!ours(e.target)) { + e.stopPropagation(); + if (e.target.closest("a[href], button, summary, [data-href], [data-add], [data-chart]")) flash(); + return; + } + const w = e.target.closest(".hl-bt [data-w]"); + if (w) { + const blk = w.closest(".hl-blk"); + blk.dataset.w = w.dataset.w; blk.style.setProperty("--f", frac(Number(w.dataset.w))); + return mark(blk); + } + if (e.target.closest(".hl-rm")) { + const blk = e.target.closest(".hl-blk"); + pick?.querySelector(`[data-add-block="${blk.dataset.id}"]`)?.removeAttribute("disabled"); + return blk.remove(); + } + if (e.target.closest(".hl-esave")) { if (await save(items())) leave(); return; } + if (e.target.closest(".hl-ecancel")) return reload(); + if (e.target.closest(".hl-ereset")) { + try { await post("/health/api/layout/reset", { tab: L.tab }); reload(); } + catch (x) { bar.querySelector("b").textContent = x.message; } + return; + } + if (e.target.closest(".hl-eadd")) { + const have = new Set(items().map((i) => i.id)); + pick.querySelectorAll("[data-add-block]").forEach((x) => { x.disabled = have.has(x.dataset.addBlock); }); + pick.hidden = !pick.hidden; + return; + } + const add = e.target.closest("[data-add-block]"); + if (add && !add.disabled) { // the picker stays open: add several + add.disabled = true; + addBlock(L.catalog.find((x) => x.id === add.dataset.addBlock)); + } + }, true); + + // ---- drag: the grip moves its block among the blocks of the same row kind, live + let drag = null; + document.addEventListener("pointerdown", (e) => { + const g = editing && e.target.closest(".hl-grip"); + if (!g) return; + e.preventDefault(); + const blk = g.closest(".hl-blk"); + drag = { blk, box: blk.parentElement }; + blk.classList.add("dragging"); + g.setPointerCapture(e.pointerId); + }); + document.addEventListener("pointermove", (e) => { + if (!drag) return; + drag.blk.style.pointerEvents = "none"; + const over = document.elementFromPoint(e.clientX, e.clientY)?.closest(".hl-blk"); + drag.blk.style.pointerEvents = ""; + if (!over || over === drag.blk || over.parentElement !== drag.box) return; + const r = over.getBoundingClientRect(); + const before = e.clientY < r.top ? true : e.clientY > r.bottom ? false : e.clientX < r.left + r.width / 2; + if (before) over.before(drag.blk); else over.after(drag.blk); + }); + const end = () => { if (drag) { drag.blk.classList.remove("dragging"); drag = null; } }; + document.addEventListener("pointerup", end); + document.addEventListener("pointercancel", end); + + addEventListener("keydown", (e) => { + if (!editing) return; + if (e.key === "Escape" && pick && !pick.hidden) pick.hidden = true; + const a = e.key === "Enter" && e.target.closest?.("a[href], [data-href]"); // keyboard "click" on a link + if (a && !ours(a)) { e.preventDefault(); flash(); } + }, true); + document.addEventListener("auxclick", (e) => { // middle click = open in a new tab: fine, the page stays + if (editing && e.button === 1 && e.target.closest(".hl-blk") && !ours(e.target)) e.preventDefault(); + }, true); + addEventListener("hashchange", () => { if (location.hash === "#edit") enter(); }); + if (location.hash === "#edit") enter(); +})(); diff --git a/dashboard/plugins/health/summary.py b/dashboard/plugins/health/summary.py new file mode 100644 index 0000000..c401d31 --- /dev/null +++ b/dashboard/plugins/health/summary.py @@ -0,0 +1,159 @@ +"""Health summaries for the phone app: what the Health pages compute from the band's data (sleep, +heart rate, steps, workouts, energy), worked out here — with the pages' own functions (watch.py, +calc.py), so the app shows the same numbers — and kept in the `summary` table of health.db, which +syncs one way (the Pi writes it, the app only reads; the raw samples stay here). + + day: steps, energy {bmr, walk, workouts, total}, hr {low, high, rest}, vitality + (intensity minutes), load, fitness / fatigue / form, naps [{start, end, minutes}] + night: the night (watch._night): start, end, asleep, light, deep, rem, awake, wakeups, + score + parts, eff, deep_pct, inbed, unstaged; stages [[from, to (minutes after + start), stage]] (the hypnogram) + wk: a workout (watch.enriched): name, day, start, end, minutes, distance, avg / max hr, + kcal (+ with resting), load, effect, usual, zones (seconds) + zone_pct, bounds, + steps; hr [[seconds from start, bpm]] (≤ HR_POINTS, averaged) + meta:energy watch.energy_summary (the food diary's target: weight, bmr, tdee, days …) + meta:person max / resting heart rate, zone method + bounds, VO₂max (+ where from), age, weight + meta:food Settings ▸ Food: the weight goal, macro split, own kcal target, fibre / sugar / sodium limits + meta:sleep the sleep goal + "What stands out" (watch.findings) per shared period {1d … all: [[title, text]]} + +refresh(con, settings) rewrites only the rows whose data changed (and deletes ones gone), so the +sync sends the differences. The plugin's worker calls it when health.db, the settings or the day +changed. +""" +import json +from collections import defaultdict +from datetime import date + +from . import calc, db, views, watch + +HR_POINTS = 120 + + +def _iso(v): + return v.isoformat() if hasattr(v, "isoformat") else v + + +def _r(v, n=1): + return round(v, n) if isinstance(v, float) else v + + +def _thin(samples, start, n=HR_POINTS): + """[(datetime, bpm)] → ≤ n points [[seconds from start, bpm]] (averages of equal slices).""" + if not samples: + return [] + k = max(1, -(-len(samples) // n)) + out = [] + for i in range(0, len(samples), k): + part = samples[i:i + k] + t = (part[len(part) // 2][0] - start).total_seconds() + out.append([round(t), round(sum(b for _, b in part) / len(part))]) + return out + + +def build(con, s, today=None, diet=None): + """{key: (kind, day, data)} — everything the app's Health pages need (diet = Settings ▸ Food, see refresh).""" + today = today or date.today() + hr = db.hr_rows(con, hist=True) + wks = db.exercises(con) + weights = db.weights(con) + steps = db.steps_days(con) + s2 = watch.with_resting(s, hr, wks) + ew = watch.enriched(wks, s2, weights) + p = watch._person(s2, today, weights) + out = {} + + # workouts + by_day = defaultdict(list) + for w in ew: + by_day[w["day"]].append(w) + samples = db.hr_samples(con, w["start"], w["end"]) + out[f"wk:{w['id']}"] = ("workout", w["day"].isoformat(), { + "id": w["id"], "day": w["day"].isoformat(), "start": _iso(w["start"]), "end": _iso(w["end"]), "name": w["name"], + "minutes": _r(w["minutes"]), "distance": w.get("distance"), "avg_hr": round(w["avg_hr"]) if w.get("avg_hr") else None, "max_hr": w.get("max_hr"), + "steps": w.get("steps"), "kcal": _r(w["kcal"], 0), "kcal_total": _r(w["kcal_total"], 0), "load": _r(w["load"]), + "effect": w.get("effect"), "usual": _r(w.get("usual")), "zones": [round(z) for z in w["zones"]], + "zone_pct": w["zone_pct"], "bounds": [round(b) for b in w["bounds"]], "hr": _thin(samples, w["start"])}) + + # training load → fitness / fatigue / form per day (from the first workout on) + loads = defaultdict(float) + for w in ew: + loads[w["day"]] += w["load"] or 0 + train = {d: (f, t, fm) for d, f, t, fm in calc.fitness_fatigue(loads, min(loads), today)} if loads else {} + + # days + sd = {x["day"]: x for x in steps} + hd = {r["day"]: r for r in hr} + naps = defaultdict(list) + for n in db.naps(con): + naps[n["start"].date()].append({"start": _iso(n["start"]), "end": _iso(n["end"]), "minutes": n["minutes"]}) + for d in sorted(set(sd) | set(hd) | set(by_day) | set(naps)): + e = watch.day_energy(d, sd.get(d), by_day.get(d, []), s2, weights) + h = hd.get(d) + vit = None + if h and h.get("hist") and p["rest"]: + mod, vig = calc.intensity_minutes(h["hist"], p["rest"], p["hrmax"]) + vit = round(mod + 2 * vig) + f = train.get(d) + out[f"day:{d.isoformat()}"] = ("day", d.isoformat(), { + "steps": sd[d]["steps"] if d in sd else None, "workout_steps": sd[d]["workout_steps"] if d in sd else None, + "energy": {k: round(v) for k, v in e.items()} if e else None, + "hr": {"low": h["low"], "high": h["high"], "rest": h.get("rest")} if h else None, + "vitality": vit, "load": _r(loads.get(d)) if d in loads else None, + "fitness": _r(f[0]) if f else None, "fatigue": _r(f[1]) if f else None, "form": _r(f[2]) if f else None, + "naps": naps.get(d, [])}) + + # nights + goal = s.get("sleep_goal") or 8 + for n in db.nights(con): + x = watch._night(n, goal) + runs = db.stages(con, n["day"]) + out[f"night:{n['day'].isoformat()}"] = ("night", n["day"].isoformat(), { + "start": _iso(x["start"]), "end": _iso(x["end"]), "asleep": x["asleep"], "light": x["light"], "deep": x["deep"], + "rem": x["rem"], "awake": x["awake"], "wakeups": x["wakeups"], "score": x["score"], "parts": x["parts"], + "eff": _r(x["eff"], 3), "deep_pct": _r(x["deep_pct"]), "inbed": _r(x["inbed"]), "unstaged": _r(x["unstaged"]), + "stages": [[round((a - x["start"]).total_seconds() / 60, 1), round((b - x["start"]).total_seconds() / 60, 1), st] + for a, b, st in runs]}) + + # sleep: the goal + "What stands out" (watch.findings) for each of the shared periods + goal_f = float(goal) + all_n = [watch._night(n, goal_f) for n in db.nights(con)] + all_naps = db.naps(con) + found = {} + for rng in views.RANGES: + _, _, a, _ = watch.period(rng, "d", today, ("d", "w"), first=all_n[0]["day"] if all_n else None) + found[rng] = [list(f) for f in watch.findings([n for n in all_n if a <= n["day"] <= today], wks, + [x for x in all_naps if a <= x["start"].date() <= today], goal_f)] + out["meta:sleep"] = ("meta", None, {"goal": goal_f, "findings": found}) + + # the target's basis + the person + es = watch.energy_summary(steps, wks, s2, weights, today=today) + out["meta:energy"] = ("meta", None, {k: (_iso(v) if hasattr(v, "isoformat") else _r(v)) for k, v in es.items()}) + if diet: + out["meta:food"] = ("meta", None, diet) + out["meta:person"] = ("meta", None, {"hrmax": p["hrmax"], "rest": p["rest"], "rest_set": p["rest_set"], "method": p["method"], + "bounds": [round(b) for b in p["bounds"]], "vo2max": _r(p["vo2max"]), + "vo2_src": p["vo2_src"], "age": p["age"], "weight": p["weight"], "today": today.isoformat(), + # the profile (Settings ▸ Health), for the app's own body / energy numbers + "sex": s.get("sex"), "birth": s.get("birth_date") or None, "height": s.get("height") or None}) + return out + + +def refresh(con, s, today=None, diet=None): + """Write what changed → {"written", "deleted", "rows"}. diet = the food plugin's settings + (ctx.ask("food", "diet")) → meta:food, so the app's food targets are the dashboard's.""" + new = build(con, s, today, diet) + old = {r[0]: r[1] for r in con.execute("SELECT k, data FROM summary")} + written = deleted = 0 + with con: + for k, (kind, day, data) in new.items(): + text = json.dumps(data, separators=(",", ":"), sort_keys=True) + if old.get(k) == text: + continue + con.execute("INSERT INTO summary (k, kind, day, data) VALUES (?, ?, ?, ?) " + "ON CONFLICT(k) DO UPDATE SET kind = excluded.kind, day = excluded.day, data = excluded.data", + (k, kind, day, text)) + written += 1 + for k in set(old) - set(new): + con.execute("DELETE FROM summary WHERE k = ?", (k,)) + deleted += 1 + return {"written": written, "deleted": deleted, "rows": len(new)} diff --git a/dashboard/plugins/health/templates/health/_blk.html b/dashboard/plugins/health/templates/health/_blk.html new file mode 100644 index 0000000..db46dab --- /dev/null +++ b/dashboard/plugins/health/templates/health/_blk.html @@ -0,0 +1,14 @@ +{# One block in its wrapper (tab.html; alone: GET /health/api/block, layout.js's instant add). + The wrapper carries data-id / data-w and --f (its share of the row); a tile's wrapper is the + tile itself (a link / hover-tip anchor where the block has one). Import "with context" + (V, v, B = {id: block} incl. the guests' — theirs draw themselves, render() —, tab). A tile + shown on another tab than its own links to its tab. #} +{% import "health/_blocks.html" as bl with context %} +{% macro frac(w) %}{{ {33: 0.33333, 66: 0.66667}.get(w, w / 100) }}{% endmacro %} +{% macro block(it) %}{% set b = B[it.id] %}{% set out = (b.render() if b.render else bl[b.macro](V)) | trim %} +{% set href = b.href or (("/health/" ~ b.tab) if b.tab != tab and b.tab in ("body", "sleep", "heart", "activity") else None) %} +{% if b.kind == "tile" %} +<{{ "a" if href else "div" }} class="hl-blk{% if b.pin %} hl-pin{% endif %}{% if not out %} hl-void{% endif %}" data-id="{{ b.id }}" data-w="{{ it.w }}" style="--f:{{ frac(it.w) }}"{% if href %} href="{{ href }}"{% elif b.pin %} tabindex="0"{% endif %}>{{ (out if out else '' ~ b.label ~ 'nothing to show') | safe }} +{% else %} +
    {{ (out if out else '

    ' ~ b.label ~ '

    Nothing to show.

    ') | safe }}
    +{% endif %}{% endmacro %} diff --git a/dashboard/plugins/health/templates/health/_blocks.html b/dashboard/plugins/health/templates/health/_blocks.html new file mode 100644 index 0000000..8e32349 --- /dev/null +++ b/dashboard/plugins/health/templates/health/_blocks.html @@ -0,0 +1,272 @@ +{# The health pages' building blocks (blocks.py): one macro per block, named after its id + (dots → underscores). Each gets V = the views the page computed ({src: view}: overview, + body, sleep, heart, activity — only those its blocks need). A tile macro gives the tile's + inside (tab.html wraps it: the wrapper is the tile); a card macro gives its section. + Nothing to show → empty output (the page hides the block; edit mode shows a placeholder). + Import "with context" (v: today, range, ranges, grain, grains, body, prof). #} +{% import "health/_parts.html" as hp with context %} +{% from "health/_watch.html" import hm, clock with context %} +{% set n, sgn, dm, chart = hp.n, hp.sgn, hp.dm, hp.chart %} +{% macro tip(text, t) %}{{ text }}{{ t }}{% endmacro %} +{% macro cls(c) %}{% if c %}{{ c[0] }}{% endif %}{% endmacro %} +{% macro when(B, k) %}{% if B.cur[k] %}{{ dm(B.cur[k].day) }}{% if B.cur[k].stale %} · too old to use{% endif %}{% endif %}{% endmacro %} +{% macro dhref(S) %}?r={{ S.range }}&g={{ S.grain }}&d={% endmacro %} + +{# ======================= "last night / last workout" (watch.overview, src "overview") — + blocks of Sleep and Activity, meant for the Overview ======================= #} +{% macro sleep_last_score(V) %}{% set o = V.overview %} +Sleep score{{ o.night.score if o.night else "—" }}{% if o.night %}last night · {{ hm(o.night.asleep) }} asleep{% endif %}{% if o.score7 %} · 7-night average {{ o.score7 | round | int }}{% endif %}{% endmacro %} +{% macro sleep_last_night(V) %}{% set o = V.overview %}{% if o.night %}{% set t = o.night %} +
    +
    {{ hp.title("Last night", "From the band. Hover the stages for times; the score's breakdown is on the ring.") }} + {{ (t.day - t.day.resolution).strftime("%a %-d") }} → {{ t.day.strftime("%a %-d %b") }} ›
    + {{ hp.night(t, o.hyp, o.goal) }} +
    {% endif %}{% endmacro %} +{% macro act_last_workout(V) %}{% set o = V.overview %}{% if o.workout %}{% set w = o.workout %} +
    +
    {{ hp.title("Last workout", "Calories are ours (heart rate, VO₂max, weight); zones as set in Settings. Hover the graph for minute and heart rate.") }} + {{ w.name }} · {{ w.start.strftime("%a %-d %b, %H:%M") }} ›
    +
    +
    Duration
    {{ hm(w.minutes) }}
    +
    Heart rate
    {{ n(w.avg_hr, 0) if w.avg_hr else "—" }} avg · {{ w.max_hr or "—" }} max
    +
    Calories
    {{ n(w.kcal, 0) if w.kcal is not none else "—" }} active{% if w.kcal_device %} · Mi {{ n(w.kcal_device, 0) }}{% endif %}
    +
    Load
    {{ n(w.load, 0) if w.load else "—" }}{% if w.effect %} · {{ w.effect }}{% endif %}
    +
    Zones
    {{ hp.zone_strip(w.zone_pct) }}
    +
    + {{ hp.hr_graph(o.graph, "hl-hr hl-hr-s") }} +
    {% endif %}{% endmacro %} + +{# ======================= body ======================= #} +{% macro body_weight(V) %}{% set B = V.body %}{% if B.rows %} +Weight{{ n(B.cur.weight.v if B.cur.weight else none) }} kg +{% if B.weight_change %}{{ sgn(B.weight_change.delta) }} kg in {{ B.weight_change.days }} days{% endif %}{{ when(B, "weight") }}{% endif %}{% endmacro %} +{% macro body_bmi(V) %}{% set B = V.body %}{% set b, p = B.body, B.prof %}{% if B.rows %} +BMI{{ n(b.bmi) }}{% if b.bmi_class %}{{ hp.bmi_pop(b.bmi_class) }}{% else %}{{ "needs height" if not p.height else "needs weight" }}{% endif %} +{% if b.healthy %}normal range {{ n(b.healthy[0], 0) }}–{{ n(b.healthy[1], 0) }} kg{% endif %}{% endif %}{% endmacro %} +{% macro body_waist(V) %}{% set B = V.body %}{% set b = B.body %}{% if B.rows %} +Waist{{ n(B.cur.waist.v if B.cur.waist else none) }} cm +{% if B.waist_change %}{{ sgn(B.waist_change.delta) }} cm in {{ B.waist_change.days }} days · {% endif %}{{ b.waist_class or "" }}{{ when(B, "waist") }}{% endif %}{% endmacro %} +{% macro body_fat(V) %}{% set B = V.body %}{% set b = B.body %}{% if B.rows %} +Body fat{% if b.fat_mid %}{{ n(b.fat_mid) }} %{% else %}—{% endif %} +{% if b.fat_range %}{{ n(b.fat_range[0]) }}–{{ n(b.fat_range[1]) }} % · {{ b.fat_n }} formulas{% elif b.fat_n == 1 %}1 formula{% else %}add waist, neck, hips{% endif %} +{% if b.fat_class %}{{ hp.fat_pop(b.fat_class) }}{% endif %}{% endif %}{% endmacro %} +{% macro body_charts(V) %}{% set B = V.body %}{% if B.rows %} +
    +
    + +
    + {% for k in ("weight", "waist", "bmi", "fat") %} +
    {{ chart(B.charts[k], k) }}
    + {% endfor %} +
    {% endif %}{% endmacro %} +{% macro body_fat_table(V) %}{% set B = V.body %}{% set b = B.body %}{% if B.rows %} +
    +

    {{ tip("Body fat", "Tape-measure formulas only — no BMI-based ones (they count muscle as fat). None of the tape measurements includes the chest (Navy: waist, hips, neck). All are estimates (a few % either way); the trend over months says more than one number. Not medical advice.") }} {% if b.fat_mid %}middle value {{ n(b.fat_mid) }} %{% if b.fat_range %} · range {{ n(b.fat_range[0]) }}–{{ n(b.fat_range[1]) }} %{% endif %}{% if b.fat_class %} · {{ hp.fat_pop(b.fat_class) }}{% endif %}{% endif %}

    + + {% for f in b.fat %} + + {% if f.value is not none %} + {% else %}{% endif %} + {% endfor %} +
    {{ f.name }}{{ f.note }}{{ n(f.value) }} %{{ hp.fat_pop(f.class) if f.class else "" }}—needs {{ f.missing | join(", ") }}
    +
    {% endif %}{% endmacro %} +{% macro body_ratios(V) %}{% set B = V.body %}{% set b, p = B.body, B.prof %}{% if B.rows %} +
    +

    Ratios & energy

    +
    +
    Waist ÷ height
    {% if b.whtr %}{{ n(b.whtr, 2) }} · {{ b.whtr_class }} (under 0.5 is the usual aim){% else %}needs waist{{ " and height" if not p.height }}{% endif %}
    +
    Waist ÷ hips
    {% if b.whr %}{{ n(b.whr, 2) }} · {{ b.whr_class }} (WHO: under {{ "0.85" if p.sex == "female" else "0.90" }}){% else %}needs waist and hips{% endif %}
    + {% if b.fat_kg %}
    Fat · lean
    {{ n(b.fat_kg) }} kg · {{ n(b.lean_kg) }} kg (from the body-fat middle value)
    {% endif %} +
    Resting energy
    {% if b.bmr %}{{ n(b.bmr, 0) }} kcal / day Mifflin–St Jeor{% if b.bmr_katch %} · {{ n(b.bmr_katch, 0) }} Katch–McArdle{% endif %}{% else %}needs weight, height, birth date{% endif %}
    +
    +
    {% endif %}{% endmacro %} +{% macro body_measurements(V) %}{% set B = V.body %}{% if B.rows %} +
    +

    Measurements {{ B.rows | length }}

    {{ hp.pager("mp", B.mp, B.mpages, "measurements") }}CSV
    +
    + + {% for k in B.cols %}{% endfor %} + + {% for r in B.mrows %} + + + {% for k in B.cols %}{% endfor %} + + {% endfor %} + +
    Day{{ fields[k][0] }} {{ fields[k][1] }}Note
    {{ r.day.strftime("%a") }} {{ dm(r.day) }}{{ "" if r[k] is none else ("%g" | format(r[k])) }}{{ r.note }}
    +
    + {% if B.mpages > 1 %}
    {{ hp.pager("mp", B.mp, B.mpages, "measurements") }}
    {% endif %} +
    {% endif %}{% endmacro %} + +{# ======================= sleep ======================= #} +{% macro sleep_asleep(V) %}{% set S = V.sleep %}{% if S.night %} +Asleep{{ hm(S.avg.asleep) }}average · goal {{ "%g" | format(S.goal) }} h{% endif %}{% endmacro %} +{% macro sleep_deep(V) %}{% set S = V.sleep %}{% if S.night %} +Deep sleep{% if S.avg.deep is not none %}{{ S.avg.deep | round | int }} %{% else %}—{% endif %}typical 13–23 %{% endif %}{% endmacro %} +{% macro sleep_score(V) %}{% set S = V.sleep %}{% if S.night %} +Score{{ S.avg.score | round | int if S.avg.score is not none else "—" }}efficiency {{ ((S.avg.eff or 0) * 100) | round | int }} %{% endif %}{% endmacro %} +{% macro sleep_times(V) %}{% set S = V.sleep %}{% if S.night %} +Usual times{{ clock(S.avg.bed) }} → {{ clock(S.avg.wake) }}bed → up{% endif %}{% endmacro %} +{% macro sleep_stages(V) %}{% set S = V.sleep %}{% if S.night %} +
    +
    {{ hp.title("Stages per " ~ ("night" if S.grain == "d" else "week"), "Each bar is one night (weekly: the average night of that week), split into the band's stages; naps of that day on top. Dashed line: your sleep goal. Click a night to open it.") }} +
    {% for st in ("deep", "light", "asleep", "awake", "nap") %}{{ S.stage_names[st] }}{% endfor %}
    + {% set c = S.stack %} + {% if c %} + {% for t in c.yt %}{{ t.label }}{% endfor %} + {% for t in c.xt %}{{ t.label }}{% endfor %} + {% for b in c.bars %}{% endfor %} + {% if c.goal %}{% endif %} + {{ hp.hits(c, "/health/sleep" ~ dhref(S)) }} + {% else %}

    Nothing in this period.

    {% endif %} +
    {% endif %}{% endmacro %} +{% macro sleep_window(V) %}{% set S = V.sleep %}{% if S.night %} +
    +
    {{ hp.title("Bedtime → wake-up" ~ (" · average per week" if S.grain == "w" else ""), "One bar per night from falling asleep to waking up (weekly: the week's average bedtime → average wake-up). Red = under 7 h asleep. Click a night to open it.") }}
    + {{ hp.window(S.window, "/health/sleep" ~ dhref(S)) }} +
    {% endif %}{% endmacro %} +{% macro sleep_score_chart(V) %}{% set S = V.sleep %}{% if S.night %} +
    +
    {{ hp.title("Score per " ~ ("night" if S.grain == "d" else "week"), "Our 0–100 sleep score (duration 50, deep sleep 20, efficiency 15, interruptions 15). Weekly = the average. Click a night to open it.") }}
    + {{ hp.chart(S.score_chart, "score", ("/health/sleep" ~ dhref(S)) if S.grain == "d" else None) }} +
    {% endif %}{% endmacro %} +{% macro sleep_findings(V) %}{% set S = V.sleep %}{% if S.night and S.findings %} +
    + {{ hp.title("What stands out", "Worked out from your nights in this period by fixed rules (no AI): averages compared with common guidance. From the band's sleep tracking — its stages are an estimate, not a sleep lab. Not medical advice.") }} +
    {% for k, text in S.findings %}
    {{ k }}
    {{ text }}
    {% endfor %}
    +
    {% endif %}{% endmacro %} +{% macro sleep_weekday(V) %}{% set S = V.sleep %}{% if S.night %} +
    +
    {{ hp.title("By weekday", "Grouped by the evening you went to bed.") }}
    + + + {% for r in S.weekdays %} + + {% endfor %} +
    AsleepBedScore
    {{ r.name }}{{ hm(r.asleep) }}{{ clock(r.bed) }}{{ r.score | round | int if r.score is not none else "—" }}
    +
    {% endif %}{% endmacro %} + +{# ======================= heart ======================= #} +{% macro heart_resting(V) %}{% set Hh = V.heart %}{% if Hh.last %} +Resting{{ n(Hh.rest7, 0) if Hh.rest7 else "—" }} bpm7-day average · 30 days {{ n(Hh.rest30, 0) if Hh.rest30 else "—" }}{% endif %}{% endmacro %} +{% macro heart_lowest(V) %}{% set Hh = V.heart %}{% if Hh.last %} +Lowest, 30 days{{ n(Hh.low30, 0) }} bpmaverage · lowest {{ Hh.lowest30 or "—" }} · 7 days {{ n(Hh.low7, 0) }}{% endif %}{% endmacro %} +{% macro heart_highest(V) %}{% set Hh = V.heart %}{% if Hh.last %} +Highest, 30 days{{ Hh.high30 or "—" }} bpmworkouts, mostly{% endif %}{% endmacro %} +{% macro heart_bp(V) %}{% set x = V.heart.vit %} +Blood pressure +{% if x.last_bp %}{{ x.last_bp.sys }}/{{ x.last_bp.dia }} mmHg + {{ cls(x.last_bp_class) }}{% if x.bp30 and x.bp30[2] > 1 %} · 30-day average {{ x.bp30[0] }}/{{ x.bp30[1] }} ({{ x.bp30[2] }}){% endif %} + {{ dm(x.last_bp.t.date()) }} {{ x.last_bp.t.strftime("%H:%M") }} +{% else %}—{% endif %}{% endmacro %} +{% macro heart_ox(V) %}{% set x = V.heart.vit %} +Blood oxygen +{% if x.last_ox %}{{ "%g" | format(x.last_ox.spo2) }} % + {{ cls(x.last_ox_class) }} · spot check + {{ dm(x.last_ox.t.date()) }} {{ x.last_ox.t.strftime("%H:%M") }} +{% else %}—none yet{% endif %}{% endmacro %} +{% macro heart_chart(V) %}{% set Hh = V.heart %} +{% if Hh.last %}
    +
    {{ hp.title("Heart rate per " ~ {"h": "hour", "d": "day", "w": "week"}[Hh.grain], "Lowest and highest reading in each period, and the band's resting heart rate (Mi Fitness's daily value). Heart rate is read every 10 minutes all day, every minute when active. A low a few beats above your normal for several days often means poor sleep, stress, illness coming on — or the second half of the cycle.") }}
    + {{ hp.chart(Hh.chart, "heart") }} +
    {% else %}
    No heart-rate data yet — it comes from the watch import.
    {% endif %}{% endmacro %} +{% macro heart_bp_card(V) %}{% set x = V.heart.vit %} +
    +
    {{ hp.title("Blood pressure", "Upper (systolic) and lower (diastolic) number, mmHg — the day's or week's average. ESC 2024 categories: under 120 / 70 non-elevated (green band), 120–139 / 70–89 elevated, 140 / 90 and up hypertension (red band), 180 / 110 and up severe; a reading takes the higher category of its two numbers. One reading says little: the average of several, on different days, sitting and rested, is what counts. Not medical advice.") }} +
    + {% if x.bp_chart %}{{ hp.chart(x.bp_chart, "blood pressure") }} + {% else %}

    No blood pressure readings in this period{% if x.last_bp %} — the last one was {{ dm(x.last_bp.t.date()) }}{% endif %}.

    {% endif %} + {% if x.bp.n %} +

    Readings {{ x.bp.n }}, newest first

    {{ hp.pager("bp", x.bp.page, x.bp.pages, "bp") }}
    + + + {% for r in x.bp.rows %} + + + + + {% endfor %} +
    WhenmmHgNote
    {{ r.t.strftime("%a") }} {{ dm(r.t.date()) }} {{ r.t.strftime("%H:%M") }}{{ r.sys }}/{{ r.dia }}{{ cls(r.cls) }}{{ r.note }}{% if r.source %} {{ vsources.get(r.source, r.source) }}{% endif %}
    + {% endif %} +
    {% endmacro %} +{% macro heart_ox_card(V) %}{% set x = V.heart.vit %} +
    +
    {{ hp.title("Blood oxygen (SpO₂)", "Spot checks from the band (it doesn't measure all day) and readings you add. At rest 95–100 % is normal (green band), 91–94 % low, 90 % or less very low — see a doctor if that repeats. Wrist sensors read a couple of % low now and then (cold hands, movement, a loose strap): a single low reading isn't a verdict.") }} +
    + {% if x.ox_chart %}{{ hp.chart(x.ox_chart, "oxygen") }} + {% else %}

    No oxygen readings in this period{% if x.last_ox %} — the last one was {{ dm(x.last_ox.t.date()) }}{% endif %}.

    {% endif %} + {% if x.ox.n %} +

    Readings {{ x.ox.n }}, newest first

    {{ hp.pager("op", x.ox.page, x.ox.pages, "ox") }}
    + + + {% for r in x.ox.rows %} + + + + + {% endfor %} +
    When%Note
    {{ r.t.strftime("%a") }} {{ dm(r.t.date()) }} {{ r.t.strftime("%H:%M") }}{{ "%g" | format(r.spo2) }}{{ cls(r.cls) }}{{ r.note }}{% if r.source %} {{ vsources.get(r.source, r.source) }}{% endif %}
    + {% endif %} +
    {% endmacro %} + +{# ======================= activity ======================= #} +{% macro act_steps(V) %}{% set A = V.activity %} +Steps{{ n(A.steps_avg, 0) if A.steps_avg else "—" }}a day · {{ A.steps_days }} day{{ "s" if A.steps_days != 1 }} ({{ A.steps_band }} from the band){% endmacro %} +{% macro act_energy(V) %}{% set A = V.activity %} +Energy (estimate){{ n(A.energy_avg, 0) if A.energy_avg else "—" }} kcal +a day: resting {{ n(A.bmr, 0) }} + walking {{ n(A.walk_avg, 0) }} + workouts +How it's estimated + Resting: Mifflin–St Jeor (weight, height, age, sex). Walking: steps outside workouts × your step length (41 % of height) × 0.5 kcal per kg per km. Workouts: active calories from heart rate (% of heart-rate reserve × your VO₂max × weight). Everyday movement that isn't steps isn't counted, so the real number is likely a bit higher.{% endmacro %} +{% macro act_workouts(V) %}{% set A = V.activity %} +Workouts{{ A.n }}{{ hm(A.minutes) }} · {{ n(A.kcal, 0) }} kcal active{% endmacro %} +{% macro act_fitness(V) %}{% set tr = V.activity.training[1] %}{% if tr %} +Fitness · form{{ n(tr.fitness, 0) }} · {{ tr.form_label[0] }} +fatigue {{ n(tr.fatigue, 0) }} · form {{ "%+.0f" | format(tr.form) }} +Fitness, fatigue, formFitness = your training load averaged over 6 weeks, fatigue = over 1 week (Banister's model). Form = fitness − fatigue: {{ tr.form_label[1] }}. Over +10 fresh · −10 to −30 building · below −30 overload.{% endif %}{% endmacro %} +{% macro act_vitality(V) %}{% set vi = V.activity.vitality[1] %} +Vitality{{ n(vi.week, 0) }} / {{ vi.goal }}intensity minutes, last 7 days +VitalityMinutes at moderate effort (40–59 % of heart-rate reserve) + 2 × minutes at vigorous effort (60 %+), from the whole day's heart rate. WHO / ACSM recommend at least 150 a week.{% endmacro %} +{% macro act_steps_chart(V) %}{% set A = V.activity %} +
    +
    {{ hp.title("Steps", "The band's count when it has one; on days it doesn't, the phone's — never both added up. Weekly = average per day.") }}
    + {{ hp.chart(A.steps_chart, "steps") }} +
    {% endmacro %} +{% macro act_energy_chart(V) %}{% set A = V.activity %} +
    +
    {{ hp.title("Energy", "Estimated burn per day (weekly = average per day): resting + walking + workouts. Not available per hour.") }}
    + {{ hp.chart(A.energy_chart, "energy") }} +
    {% endmacro %} +{% macro act_workout_time(V) %}{% set A = V.activity %} +
    +
    {{ hp.title("Workout time", "Minutes of workouts per " ~ {"h": "hour", "d": "day", "w": "week"}[A.grain] ~ ".") }}
    + {{ hp.chart(A.week_chart, "workouts") }} +
    {% endmacro %} +{% macro act_training(V) %}{% set A = V.activity %} +
    +
    {{ hp.title("Training", "Fitness (6-week load), fatigue (1-week load) and form (fitness − fatigue). Load per workout = Banister's TRIMP: minutes × effort, hard minutes weighted much more. Rising fitness = getting fitter; form far below 0 = time to rest.") }}
    + {{ hp.chart(A.training[0], "training") }} +
    {% endmacro %} +{% macro act_vitality_chart(V) %}{% set A = V.activity %} +
    +
    {{ hp.title("Vitality", "Intensity minutes per " ~ ("week" if A.grain == "w" else "day") ~ ": moderate + 2 × vigorous, from all-day heart rate. Shaded: on track for 150 a week.") }}
    + {{ hp.chart(A.vitality[0], "vitality") }} +
    {% endmacro %} +{% macro act_workouts_list(V) %}{% set A = V.activity %} +
    + {% set tip = ("Mi Fitness said " ~ ((A.device_vs_ours * 100) | round | int) ~ " % of our calories in total for the same workouts. " if A.device_vs_ours else "") ~ ("Check on " ~ A.walk_check.n ~ " GPS walks: ours = " ~ ((A.walk_check.ratio * 100) | round | int) ~ " % of the walking equation (speed + weight — very accurate on level ground). " if A.walk_check else "") ~ "Active = on top of resting, like watches show. Load = TRIMP; effect = load vs your usual (average of the 6 weeks before): easy under 0.6×, maintaining to 0.9×, improving to 1.3×, very hard above. Click a workout for its heart rate and zones." %} +
    {{ hp.title("Workouts", tip) }}
    +
    + + {% for w in A.rows %} + + + + + + {% else %}{% endfor %} +
    DayWorkoutTimeAvg / max bpmZonesLoadEffectkcal active
    {{ w.start.strftime("%a") }} {{ dm(w.day) }} {{ w.start.strftime("%H:%M") }}{{ w.name }}{{ hm(w.minutes) }}{{ n(w.avg_hr, 0) if w.avg_hr else "—" }} / {{ w.max_hr or "—" }}{{ hp.zone_strip(w.zone_pct) }}{{ n(w.load, 0) if w.load else "—" }}{{ w.effect or "" }}{{ n(w.kcal, 0) if w.kcal is not none else "—" }}
    No workouts in this period.
    + {{ hp.more(A.more) }} +
    {% endmacro %} diff --git a/dashboard/plugins/health/templates/health/_parts.html b/dashboard/plugins/health/templates/health/_parts.html new file mode 100644 index 0000000..eaba8e5 --- /dev/null +++ b/dashboard/plugins/health/templates/health/_parts.html @@ -0,0 +1,205 @@ +{# Shared by the health pages: header (⌂ 📅 … ··· Health ··· ⚙), under it the tabs Overview|Body|Sleep|Heart|Activity; a floating + = Measurements, + number formats, the measurement dialog (health.js). Import "with context" (uses v). #} +{% from "_header.html" import nav_btns, settings_btn, title_block, subline, section_tabs %} +{% from "health/_watch.html" import hm %} +{% macro n(x, d=1) %}{% if x is none %}—{% else %}{{ ("%." ~ d ~ "f") | format(x) }}{% endif %}{% endmacro %} +{% macro sgn(x, d=1) %}{{ "+" if x > 0 else ("−" if x < 0 else "±") }}{{ ("%." ~ d ~ "f") | format(x | abs) }}{% endmacro %} +{% macro dm(d) %}{{ d.day }} {{ d.strftime("%b") }}{{ " " ~ d.year if d.year != v.today.year }}{% endmacro %} + +{# hover strips: one per bucket, health.js shows its tip (+ click opens data-href) #} +{% macro hits(c, href=None) %}{% for h in c.hits %}{% endfor %}{% endmacro %} + +{% macro chart(c, id, href=None) %} +{% if c %} + + {% for s in c.bands %}{% endfor %} + {% for t in c.yt %}{{ t.label }}{% endfor %} + {% for t in c.xt %}{{ t.label }}{% endfor %} + {% for l in c.lines %}{% for r in l.rects %}{% endfor %}{% if l.d %}{% endif %}{% for x, y in l.dots %}{% endfor %}{% endfor %} + {{ hits(c, href) }} + +{% if c.lines | length > 1 %}
    {% for l in c.lines %}{{ l.name }}{% endfor %}
    {% endif %} +{% else %}

    Nothing in this period.

    {% endif %} +{% endmacro %} + +{# sleep window: one bar per night from bedtime to wake-up (watch.window_chart) #} +{% macro window(c, href=None) %} +{% if c %} + + {% for t in c.yt %}{{ t.label }}{% endfor %} + {% for t in c.xt %}{{ t.label }}{% endfor %} + {% for r in c.rects %}{% endfor %} + {{ hits(c, href) }} + +{% else %}

    Nothing in this period.

    {% endif %} +{% endmacro %} + +{# range + grouping switches; links keep the other query values #} +{% macro qs(r=None, g=None) %}?{% set q = dict(request.args) %}{% if r %}{% set _ = q.update(r=r) %}{% endif %}{% if g %}{% set _ = q.update(g=g) %}{% endif %}{{ q | urlencode }}{% endmacro %} +{% macro ranges() %}
    +{% if v.grains is defined and v.grains | length > 1 %}{% endif %}
    {% endmacro %} + +{# a card title whose explanation shows on hover / tap #} +{% macro title(text, tip, small=None) %}

    {% if tip %}{{ text }}{{ tip }}{% else %}{{ text }}{% endif %}{% if small %} {{ small }}{% endif %}

    {% endmacro %} + +{% macro more(n) %}{% if n %}

    … and {{ n }} more — pick a shorter period to see them.

    {% endif %}{% endmacro %} + +{% macro assets() %} + +{% endmacro %} + +{# add = what the floating + opens on this tab ("measure", "bp", "ox"); hovering it lists all + three (adder() — the dialog, with a tab per kind) #} +{% macro head(sub, add="measure") %} +{% set ADD_KINDS = [("measure", "Body measurements"), ("bp", "Blood pressure"), ("ox", "Blood oxygen")] %} +
    + {{ nav_btns() }} + {{ title_block("Health", "/health") }} + {{ settings_btn("health") }} +
    +{{ subline(sub) }} +{{ section_tabs("health", {"overview": "/health", "body": "/health/body", "sleep": "/health/sleep", + "heart": "/health/heart", "activity": "/health/activity"}.get(tab, "-")) }} +
    + + +
    +{% endmacro %} + +{% macro note() %} +{% if v.prof and v.prof.missing %} +
    Set your {{ v.prof.missing | join(" and ") }} in Settings ▸ Health — BMI and most formulas need {{ "them" if v.prof.missing | length > 1 else "it" }}.
    +{% endif %} +{% endmacro %} + + +{# a table's pages: ?=N (the other query args kept), back to # #} +{% macro pager(param, cur, pages, anchor) %}{% if pages > 1 %}{% set q = dict(request.args) %} +{% endif %}{% endmacro %} + +{# The add dialog, on every health page: a tab per kind — body measurements (one row per + day; picking a day that has values loads them), blood pressure, blood oxygen (one reading + each, /health/api/vital). Editing an entry opens its tab, the tabs hidden. health.js. #} +{% macro adder() %} +{% set ADD_KINDS = [("measure", "Body measurements"), ("bp", "Blood pressure"), ("ox", "Blood oxygen")] %} +{% set today_iso = add_form.today %} + + + +{% endmacro %} + +{# ranges by age + sex: hidden, shown on hover / focus (tap on touch) over the category #} +{% macro bar(sc) %}{% if sc %}{% for s in sc.segs %}{% endfor %}{% if sc.at is not none %}{% endif %}{% endif %}{% endmacro %} + +{% macro fat_pop(label) %}{% set b = v.body %}{% if b.fat_band %}{{ label }} + Body fat, {{ "women" if v.prof.sex == "female" else "men" }} + {{ bar(b.fat_bar) }} + agelowhealthyhighvery high + {% for a, z, h, o, vo in b.fat_ranges %}{{ a }}–{{ z }}< {{ h }}{{ h }}–{{ o }}{{ o }}–{{ vo }}{{ vo }}+{% endfor %} + % · Gallagher et al. 2000{% else %}{{ label }}{% endif %}{% endmacro %} + +{% macro bmi_pop(label) %}{% set b = v.body %}{{ label }} + BMI + {{ bar(b.bmi_bar) }} + WHO, every adult: under 18.5 underweight · 18.5–25 normal · 25–30 overweight · 30+ obese. Not different for women and men. + agedesirable + {% for a, z, lo, hi in b.bmi_ages %}{{ a }}{{ "+" if z > 120 else "–" ~ z }}{{ lo }}–{{ hi }}{% endfor %} + By age: US National Research Council 1989{% endmacro %} + +{# heart-rate zones: table with a bar per zone (watch.zone_rows) / a thin strip per workout #} +{% macro zone_table(rows) %} +{% for z in rows %} + + {% endfor %}
    {{ z.name }} {% if z.from %}{{ z.from }}{{ ("–" ~ z.to) if z.to else "+" }}{% else %}< {{ z.to + 1 }}{% endif %}{{ (z.sec // 60) }} min · {{ z.pct }} %
    +{% endmacro %} +{% macro zone_strip(pct) %}{% for x in pct %}{% if x %}{% endif %}{% endfor %}{% endmacro %} + +{# what the zones are based on, e.g. "heart-rate reserve · max 187 (age) · resting 64 (watch)" #} +{% macro zone_basis(p) %}{{ "heart-rate reserve" if p.method == "hrr" else "% of max" }} · max {{ p.hrmax }} ({{ "setting" if p.max_set else "from age" }}){% if p.method == "hrr" %} · resting {{ p.rest }} ({{ "setting" if p.rest_set else "watch data" }}){% endif %}{% endmacro %} + +{# one night: score ring (breakdown on hover), numbers, the stages with hover tips — Sleep page + Overview #} +{% macro night(t, g, goal) %} +
    +
    +
    {{ t.score }}score + Sleep score {{ t.score }} / 100 + {% for k, p in t.parts.items() %}{{ k }}{{ p if p is not none else "—" }} / {{ {"Duration": 50, "Deep sleep": 20, "Efficiency": 15, "Interruptions": 15}[k] }}{% endfor %} + Duration: full at {{ "%g" | format([goal, 8] | min - 0.5) }} h+; deep: full at 20 %; efficiency: asleep ÷ in bed, full at 95 %; interruptions: −4 per wake-up. Our own formula.
    +
    +
    Asleep
    {{ hm(t.asleep) }}
    +
    In bed
    {{ t.start.strftime("%H:%M") }}–{{ t.end.strftime("%H:%M") }}
    +
    Deep
    {% if t.deep_pct is not none %}{{ hm(t.deep) }} · {{ t.deep_pct | round | int }} %{% else %}—{% endif %}
    +
    Light
    {{ hm(t.light) if t.light else "—" }}
    +
    Awake
    {{ hm(t.awake or 0) }} · {{ t.wakeups or 0 }}×
    +
    Efficiency
    {{ (t.eff * 100) | round | int }} %
    +
    +
    + + {% for l in g.lanes %}{{ l.label }}{% endfor %} + {% for l in g.lanes %}{% endfor %} + {% for b in g.blocks %}{% endfor %} + {% for t in g.ticks %}{{ t.label }}{% endfor %} + +
    +{% endmacro %} + +{# a workout: heart rate over time on the zone bands, with hover tips — workout page + Overview #} +{% macro hr_graph(g, cls="hl-hr") %} +{% if g %} + {% for b in g.bands %}{% endfor %} + {% for t in g.yt %}{{ t.label }}{% endfor %} + {% for t in g.xt %}{{ t.label }}{% endfor %} + + {{ hits(g) }} + {% else %}

    No heart rate recorded for this workout.

    {% endif %} +{% endmacro %} diff --git a/dashboard/plugins/health/templates/health/_settings.html b/dashboard/plugins/health/templates/health/_settings.html new file mode 100644 index 0000000..93b2fde --- /dev/null +++ b/dashboard/plugins/health/templates/health/_settings.html @@ -0,0 +1,28 @@ +{# Settings ▸ Health, above the fields: the Gadgetbridge import (gb.status as gb) — where it + looks, the export it found, the last import; "Import now" posts /health/api/gb/import. #} +{% macro dt(x) %}{{ x.strftime("%-d %b %H:%M") if x else "—" }}{% endmacro %} +
    +

    Gadgetbridge

    + {% if not gb.path %} +

    Off. Set Gadgetbridge export below to the folder Syncthing fills with Gadgetbridge's + database export (Gadgetbridge ▸ Settings ▸ Automations ▸ Auto export ▸ Database export) — newer exports are then + imported by themselves.

    + {% else %} +

    Folder: {{ gb.path }}
    + {% if gb.file %}Export: {{ gb.file.split("/")[-1] }}, written {{ dt(gb.file_time) }}{% else %}No export there yet.{% endif %}
    + Last import: {{ dt(gb.updated) }}{% if gb.newest %} · data up to {{ dt(gb.newest) }}{% endif %} + {% if gb.error %}
    {{ gb.error }}{% elif gb.result %}
    {{ gb.result["hr readings"] }} heart-rate readings, {{ gb.result["step days"] }} step days, nights / naps {{ gb.result["nights, naps"] | join(" / ") }}, workouts named / added {{ gb.result["workouts named, added"] | join(" / ") }}{% endif %}

    +
    + + {% endif %} +
    diff --git a/dashboard/plugins/health/templates/health/_watch.html b/dashboard/plugins/health/templates/health/_watch.html new file mode 100644 index 0000000..f8a02f6 --- /dev/null +++ b/dashboard/plugins/health/templates/health/_watch.html @@ -0,0 +1,3 @@ +{# Formats for the watch pages #} +{% macro hm(minutes) %}{% if minutes is none %}—{% else %}{% set m = minutes | round | int %}{{ m // 60 }}h {{ "%02d" | format(m % 60) }}m{% endif %}{% endmacro %} +{% macro clock(h) %}{% if h is none %}—{% else %}{% set m = (h * 60) | round | int % 1440 %}{{ "%02d:%02d" | format((m // 60 + 12) % 24, m % 60) }}{% endif %}{% endmacro %} diff --git a/dashboard/plugins/health/templates/health/block.html b/dashboard/plugins/health/templates/health/block.html new file mode 100644 index 0000000..7c0c0f0 --- /dev/null +++ b/dashboard/plugins/health/templates/health/block.html @@ -0,0 +1,3 @@ +{# One block alone (GET /health/api/block?id=&w=): what layout.js puts in place of an added + block's placeholder. #} +{% import "health/_blk.html" as blk with context %}{{ blk.block(it) }} diff --git a/dashboard/plugins/health/templates/health/report.html b/dashboard/plugins/health/templates/health/report.html new file mode 100644 index 0000000..4fc843c --- /dev/null +++ b/dashboard/plugins/health/templates/health/report.html @@ -0,0 +1,121 @@ +{% extends "base.html" %} +{% import "health/_parts.html" as hp with context %} +{% from "health/_watch.html" import hm, clock with context %} +{% block title %}Health report{% endblock %} +{% block head %}{{ hp.assets() }}{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{# A summary for a doctor (watch.report): plain values with their reference ranges and where + they come from, the cycle tracker's part when it's on (pluginhost inside(…, report=)). Print / save as PDF prints only .rp, light (health.css). #} +{% set n, dm = hp.n, hp.dm %} +{% set b, p = v.body, v.prof %} +{% macro dmy(d) %}{{ d.day }} {{ d.strftime("%b %Y") }}{% endmacro %} +{% macro cls(c) %}{% if c %}{{ c[0] }}{% endif %}{% endmacro %} +{% block page %} +{{ hp.head("report") }} +
    +
    + + +
    + +
    +
    +

    Health summary

    +

    {{ dmy(v.a) }} – {{ dmy(v.today) }} · made {{ dmy(v.today) }}

    +
    +
    Sex
    {{ p.sex | capitalize if p.sex else "—" }}
    +
    Age
    {{ p.age if p.age else "—" }}
    +
    Height
    {{ (p.height | int ~ " cm") if p.height else "—" }}
    +
    +

    Self-tracked: a Xiaomi band (heart rate, sleep, steps, workouts, oxygen spot checks) and + measurements entered by hand (weight, tape measure, home blood pressure). Wearable values are estimates.

    +
    + +
    +

    Body

    + + + + + + + + + + +
    Weight{% if v.cur.weight %}{{ "%g" | format(v.cur.weight.v) }} kg ({{ dmy(v.cur.weight.day) }}){% else %}—{% endif %}{% if v.wchange %}{{ "%+.1f" | format(v.wchange[0]) }} kg ({{ "%+.1f" | format(v.wchange[1]) }} %) since {{ dmy(v.wchange[2]) }}{% endif %}
    BMI{{ n(b.bmi) }}{{ b.bmi_class or "" }} (WHO: 18.5–24.9 normal{% if b.healthy %}; {{ n(b.healthy[0], 0) }}–{{ n(b.healthy[1], 0) }} kg at this height{% endif %})
    Waist{% if v.cur.waist %}{{ "%g" | format(v.cur.waist.v) }} cm ({{ dmy(v.cur.waist.day) }}){% else %}—{% endif %}{{ b.waist_class or "" }} (WHO, {{ "women: raised ≥ 80, high ≥ 88 cm" if p.sex == "female" else "men: raised ≥ 94, high ≥ 102 cm" }})
    Waist ÷ height{{ n(b.whtr, 2) if b.whtr else "—" }}{{ b.whtr_class or "" }} (under 0.5)
    Waist ÷ hips{{ n(b.whr, 2) if b.whr else "—" }}{{ b.whr_class or "" }} (WHO: under {{ "0.85" if p.sex == "female" else "0.90" }})
    Body fat{% if b.fat_mid %}{{ n(b.fat_mid) }} %{% else %}—{% endif %}{% if b.fat_range %}range {{ n(b.fat_range[0]) }}–{{ n(b.fat_range[1]) }} % from {{ b.fat_n }} tape-measure formulas{% endif %}{% if b.fat_class %} · {{ b.fat_class }}{% endif %} (estimates, ±3–4 %)
    + {% if v.wchart %}

    Weight

    {{ hp.chart(v.wchart, "weight") }}
    {% endif %} +
    + +
    +

    Blood pressure home readings

    + {% if v.bp %} + + + +
    Average{{ v.bp_avg[0] }}/{{ v.bp_avg[1] }} mmHg{{ cls(v.bp_cls) }} ({{ v.bp | length }} reading{{ "s" if v.bp | length != 1 }})
    Range{{ v.bp_range[0][0] }}–{{ v.bp_range[0][1] }} / {{ v.bp_range[1][0] }}–{{ v.bp_range[1][1] }}
    +

    ESC 2024: under 120/70 non-elevated · 120–139/70–89 elevated · 140/90 and up hypertension.

    + {% if v.bp_chart %}
    {{ hp.chart(v.bp_chart, "blood pressure") }}
    {% endif %} + + + {% for r in v.bp | reverse %}{% endfor %} +
    WhenmmHgNote
    {{ r.t.strftime("%a") }} {{ dm(r.t.date()) }} {{ r.t.strftime("%H:%M") }}{{ r.sys }}/{{ r.dia }}{{ r.note }}
    + {% else %}

    No readings in this period.

    {% endif %} +
    + +
    +

    Blood oxygen (SpO₂) spot checks

    + {% if v.ox %} + + +
    Readings{{ v.ox | length }}average {{ n(v.ox_avg, 0) }} % · lowest {{ "%g" | format(v.ox_min) }} %
    + {% elif v.ox_last %}

    None in this period — the last one: {{ "%g" | format(v.ox_last.spo2) }} % on {{ dmy(v.ox_last.t.date()) }}.

    + {% else %}

    No readings.

    {% endif %} +

    At rest 95–100 % is normal. Wrist sensors read low now and then (movement, cold hands).

    +
    + +
    +

    Heart rate the band, {{ v.hr_days }} days

    + {% if v.rest_avg %} + + + +
    Resting{{ n(v.rest_avg, 0) }} bpmrange {{ v.rest_range[0] }}–{{ v.rest_range[1] }} · first 30 days {{ n(v.rest_first, 0) }}, last 30 days {{ n(v.rest_last, 0) }}
    Lowest reading{{ v.hr_low or "—" }} bpm
    + {% if v.rest_chart %}
    {{ hp.chart(v.rest_chart, "resting heart rate") }}
    {% endif %} + {% else %}

    No heart-rate data in this period.

    {% endif %} +
    + +
    +

    Sleep the band{% if v.sleep %}, {{ v.sleep.n }} nights{% endif %}

    + {% set sl = v.sleep %} + {% if sl %} + + + + + + +
    Asleep{{ hm(sl.asleep) }} a night{{ sl.under7 }} nights under 7 h, {{ sl.under6 }} under 6 h (adults: 7–9 h)
    Times{{ clock(sl.bed) }} → {{ clock(sl.wake) }}bedtime ±{{ (sl.bed_sd * 60) | round | int }} min, wake-up ±{{ (sl.wake_sd * 60) | round | int }} min
    Deep sleep{{ (sl.deep | round | int ~ " %") if sl.deep is not none else "—" }}(typical 13–23 %; the band's estimate, no REM)
    Awake at night{{ "%.1f" | format(sl.wakeups) }} times{{ sl.awake | round | int }} min a night
    Naps{{ "%.1f" | format(sl.naps_week) }} a week
    + {% if v.sleep_chart %}
    {{ hp.chart(v.sleep_chart, "sleep") }}
    {% endif %} + {% else %}

    No sleep data in this period.

    {% endif %} +
    + +
    +

    Activity

    + {% set a = v.act %} + + + + {% if a.kinds %}{% endif %} +
    Steps{{ "{:,.0f}".format(a.steps) if a.steps else "—" }} a day({{ a.steps_days }} days with data)
    Workouts{{ "%.1f" | format(a.per_week) }} a week{{ a.min_week | round | int }} min a week (WHO: at least 150 min moderate)
    Kinds{% for k, c in a.kinds %}{{ k }} {{ c }}×{{ ", " if not loop.last }}{% endfor %}
    + {% if v.steps_chart %}
    {{ hp.chart(v.steps_chart, "steps") }}
    {% endif %} +
    + + {% for g in guests %}{{ g | safe }}{% endfor %} + +

    From self-tracked data. General guidance, not a diagnosis.

    +
    +
    +{% endblock %} +{% block scripts %}{{ hp.adder() }} +{% endblock %} diff --git a/dashboard/plugins/health/templates/health/tab.html b/dashboard/plugins/health/templates/health/tab.html new file mode 100644 index 0000000..7968e96 --- /dev/null +++ b/dashboard/plugins/health/templates/health/tab.html @@ -0,0 +1,47 @@ +{% extends "base.html" %} +{% import "health/_parts.html" as hp with context %} +{% import "health/_blk.html" as blk with context %} +{% block title %}{{ {"overview": "Health", "body": "Body", "sleep": "Sleep", "heart": "Heart", "activity": "Activity"}[tab] }}{% endblock %} +{% block head %}{{ hp.assets() }}{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{# Any health tab, drawn from its layout (blocks.py: an ordered list of {id, w}; the blocks + are macros in _blocks.html): a few fixed parts, the shared range bar, the tiles row, the + cards. Widths: --f = the share of the row (health.css: flex rows, exact with the gaps). + Edit mode (⋮ ▸ Edit layout, layout.js): drag, resize, add (Overview), remove (Overview), + save to /health/api/layout. #} +{% macro dq(d) %}?d={{ d.isoformat() }}&r={{ V.sleep.range }}&g={{ V.sleep.grain }}{% endmacro %} + + +{% block page %} +{{ hp.head(tab, "bp" if tab == "heart" else "measure") }} +
    +{# ---- fixed parts #} +{% if tab in ("overview", "body") %}{{ hp.note() }}{% endif %} +{% if tab == "activity" %}{% set p = V.activity.person %}{% if not (p.weight and p.age and p.height) %} +
    Calories need your weight (a measurement), height and birth date — Settings ▸ Health and the +.
    {% endif %}{% endif %} +{% if tab == "body" and not V.body.rows %} +
    No measurements yet. — a tape measure (waist, hips, neck) unlocks the body-fat formulas.
    {% endif %} +{% if tab == "sleep" %}{% set S = V.sleep %}{% if not S.night %} +
    No sleep data yet — it comes from the watch import.
    +{% else %}{% set t = S.night %} +
    +
    +

    {{ (t.day - t.day.resolution).strftime("%a %-d") }} → {{ t.day.strftime("%a %-d %b") }}{{ " " ~ t.day.year if t.day.year != v.today.year }}

    + +
    + {{ hp.night(t, S.hyp, S.goal) }} +
    {% endif %}{% endif %} + +{# ---- the range + grouping every tab shares (a cookie keeps them) #} +

    {{ v.ranges[v.range][0] }}{% if tab == "sleep" and V.sleep.night %} · {{ V.sleep.avg.n }} night{{ "s" if V.sleep.avg.n != 1 }}{% endif %}

    {{ hp.ranges() }}
    + +
    {% for it in items if B[it.id].kind == "tile" %}{{ blk.block(it) }}{% endfor %}
    +
    {% for it in items if B[it.id].kind == "card" %}{{ blk.block(it) }}{% endfor %}
    + +
    +{% endblock %} +{% block scripts %}{{ hp.adder() }}{% endblock %} diff --git a/dashboard/plugins/health/templates/health/workout.html b/dashboard/plugins/health/templates/health/workout.html new file mode 100644 index 0000000..60904f9 --- /dev/null +++ b/dashboard/plugins/health/templates/health/workout.html @@ -0,0 +1,47 @@ +{% extends "base.html" %} +{% import "health/_parts.html" as hp with context %} +{% block title %}Workout{% endblock %} +{% block head %}{{ hp.assets() }}{% endblock %} +{# One workout (watch.workout_page): heart rate over time on the zone bands, time per zone, + our calories (Keytel, from heart rate + profile) next to what Mi Fitness said. #} +{% set n, dm = hp.n, hp.dm %} +{% from "health/_watch.html" import hm with context %} +{% set w = v.w %} +{% block page %} +{{ hp.head("workout") }} +
    +
    +

    {{ w.name }} {{ w.start.strftime("%a %-d %b %Y, %H:%M") }}–{{ w.end.strftime("%H:%M") }}

    + +
    +
    +
    Duration{{ hm(w.minutes) }}{% if w.distance %}{{ "%.2f" | format(w.distance / 1000) }} km · {% endif %}{{ w.steps or 0 }} steps
    +
    Heart rate{{ n(w.avg_hr, 0) if w.avg_hr else "—" }} avgmax {{ w.max_hr or "—" }} bpm · {{ ((w.max_hr or 0) / w.hrmax * 100) | round | int }} % of your max ({{ w.hrmax }})
    +
    Load · effect{{ n(w.load, 0) if w.load else "—" }} {{ ("· " ~ w.effect) if w.effect }} + {% if w.usual %}your usual {{ n(w.usual, 0) }} (6 weeks before){% else %}not enough workouts before it{% endif %} + Training load (TRIMP)Banister's TRIMP: minutes × effort (% of heart-rate reserve), hard minutes weighted much more. Effect = this load vs the average of your workouts in the 6 weeks before: easy under 0.6×, maintaining to 0.9×, improving to 1.3×, very hard above.
    +
    Calories{{ n(w.kcal, 0) if w.kcal is not none else "—" }} kcal active + {{ n(w.kcal_total, 0) if w.kcal_total else "—" }} total incl. resting{% if w.kcal_device %} · Mi said {{ n(w.kcal_device, 0) }} active{% endif %} + How it's calculated + Each second: effort = % of heart-rate reserve (resting {{ w.person.rest }} → max {{ w.hrmax }} bpm), which matches % of oxygen use (ACSM). Oxygen = 3.5 + effort × (VO₂max {{ n(w.person.vo2max) }} − 3.5) ml/kg/min ({{ w.person.vo2_src }}{% if "BMI" in w.person.vo2_src %}: “{{ w.person.level }}”{{ " — automatic, last 12 weeks" if w.person.level_auto }}{% endif %}); × {{ n(w.person.weight) if w.person.weight else "—" }} kg × 5 kcal per litre. + Active = on top of resting — what watches show. Total adds your resting energy (Mifflin–St Jeor). Heart-rate methods are ±20–30 %; a measured VO₂max makes it much better.
    +
    +
    + +
    +
    {{ hp.title("Heart rate", "Averaged into 300 points; the coloured bands are your zones. Hover the graph for the time and heart rate.") }} +
    {% for z in v.zones[1:] %}{{ z.name }}{% endfor %}
    + {{ hp.hr_graph(v.graph) }} +
    + +
    +
    {{ hp.title("Time in zones", "Based on " ~ ("heart-rate reserve: resting " ~ w.person.rest ~ " (" ~ ("setting" if w.person.rest_set else "watch data") ~ ") → max " if w.person.method == "hrr" else "% of max heart rate: max ") ~ w.hrmax ~ " (" ~ ("setting" if w.person.max_set else "from age") ~ "). Fat burn ≈ easy, can talk; aerobic = steady cardio; anaerobic = hard, short bursts; maximum = all-out. Change it in Settings ▸ Plugins ▸ Health.") }}
    + {{ hp.zone_table(v.zones) }} +
    + +{% endblock %} +{% block scripts %}{{ hp.adder() }}{% endblock %} diff --git a/dashboard/plugins/health/views.py b/dashboard/plugins/health/views.py new file mode 100644 index 0000000..cf85913 --- /dev/null +++ b/dashboard/plugins/health/views.py @@ -0,0 +1,307 @@ +"""Health pages' view: the latest values, BMI + ratios, charts (SVG geometry worked out +here) — the overview — and body fat by every formula that has its inputs + every +measurement (/health/body). One view for both pages; each template uses its part. + +"Latest" is per field: the newest value of each, if it is at most STALE days old — so a +waist measured last week and a weight from today are used together (the page says from +when each is). +""" +from datetime import date, datetime, timedelta +from math import floor, log10 +from statistics import median + +from . import calc +from .db import FIELDS + +STALE = 90 # days a measurement is still used for "now" / carried forward +# the range every health tab shares (one value, kept in a cookie): key → (label, days back incl. +# today; None = since the first data) +RANGES = {"1d": ("1 day", 1), "1w": ("1 week", 7), "1m": ("1 month", 30), "3m": ("3 months", 91), + "1y": ("1 year", 365), "all": ("All", None)} +DEFAULT_RANGE = "1m" +W, H, ML, MR, MT, MB = 640, 210, 56, 12, 10, 24 # chart viewBox + margins +WIDE = 1300 # viewBox width of a chart filling a whole row +MISSING = {"fat_scale": "a scale reading", "height": "your height (Settings ▸ Health)"} # not measurements (FIELDS) +FAT_DAY_FIELDS = {"weight", "waist", "hip", "neck", "fat_scale"} + + +def age_on(birth, d): + if not birth: + return None + return d.year - birth.year - ((d.month, d.day) < (birth.month, birth.day)) + + +def profile(s, today): + try: + birth = date.fromisoformat(s.get("birth_date") or "") + except ValueError: + birth = None + height = s.get("height") or None + missing = [x for x, ok in (("height", height), ("birth date", birth)) if not ok] + return {"sex": s.get("sex") or calc.FEMALE, "height": height, "birth": birth, + "age": age_on(birth, today), "missing": missing} + + +def latest(rows, today): + """{field: {"v", "day", "stale"}} — the newest value of each field.""" + out = {} + for r in rows: + for k in FIELDS: + if r[k] is not None: + out[k] = {"v": r[k], "day": r["day"], "stale": (today - r["day"]).days > STALE} + return out + + +def form_data(rows): + """What the add dialog needs on every page: each field's newest value (grey placeholders) + and every measured day (picking a day that has values loads them).""" + last = {} + for r in rows: + for k in FIELDS: + if r[k] is not None: + last[k] = r[k] + return {"today": date.today().isoformat(), "last": last, + "rows": {r["day"].isoformat(): dict(r, day=r["day"].isoformat()) for r in rows}} + + +def _fresh(cur): + return {k: c["v"] for k, c in cur.items() if not c["stale"]} + + +def change(rows, key, today, days=30): + """Change of `key` from the value nearest `days` ago (at least 7 days back) to the latest.""" + pts = [(r["day"], r[key]) for r in rows if r[key] is not None] + if len(pts) < 2: + return None + last_d, last_v = pts[-1] + old = [p for p in pts if (last_d - p[0]).days >= 7] + if not old: + return None + d, v = min(old, key=lambda p: abs((last_d - p[0]).days - days)) + return {"delta": last_v - v, "since": d, "days": (last_d - d).days} + + +# ---- series + charts ------------------------------------------------------------------- + +def series(rows, prof): + """Per measured day: weight, waist, BMI, and each body-fat formula — with the other + inputs carried forward from up to STALE days before.""" + last, out = {}, {k: [] for k in ("weight", "waist", "bmi", *(f[0] for f in calc.FAT))} + for r in rows: + d = r["day"] + for k in FIELDS: + if r[k] is not None: + last[k] = (r[k], d) + m = {k: v for k, (v, day) in last.items() if (d - day).days <= STALE} + for k in ("weight", "waist"): + if r[k] is not None: + out[k].append((d, r[k])) + if r["weight"] is not None and prof["height"]: + out["bmi"].append((d, calc.bmi(r["weight"], prof["height"]))) + if any(r[k] is not None for k in FAT_DAY_FIELDS): + for f in calc.fat_all(m, prof["height"], prof["sex"], age_on(prof["birth"], d)): + if f["value"] is not None: + out[f["key"]].append((d, f["value"])) + return out + + +def span(rng, first, today): + """First day shown for a range key (at least two weeks).""" + a = max(first, today - timedelta(days=RANGES[rng][1] - 1)) if RANGES[rng][1] else first + return min(a, today - timedelta(days=14)) + + +def _nice_step(span, want=4): + raw = span / want + mag = 10 ** floor(log10(raw)) if raw > 0 else 1 + return next(m * mag for m in (1, 2, 2.5, 5, 10) if m * mag >= raw) + + +# ---- the chart engine: time axis (hours / days / weeks), lines or bars, hover tips -------- + +SLOT = {"h": 1 / 24, "d": 1, "w": 7} # bucket length in days per grain + + +def tnum(t): + """date / datetime → days (float) on one axis.""" + if isinstance(t, datetime): + return t.toordinal() + (t.hour * 3600 + t.minute * 60 + t.second) / 86400 + return float(t.toordinal()) + + +def when_label(t, grain): + if grain == "h": + return f"{t:%a %-d %b %H}:00–{(t + timedelta(hours=1)):%H}:00" + if grain == "w": + return f"Week of {t:%-d %b}" + return f"{t:%a %-d %b %Y}" if isinstance(t, date) and t.year != date.today().year else f"{t:%a %-d %b}" + + +def fmt_num(v, unit=""): + if v is None: + return "—" + s = f"{v:,.0f}" if abs(v) >= 100 or float(v).is_integer() else f"{v:.1f}" + return f"{s} {unit}".strip() + + +def xaxis(a, z, width, grain): + """Scale + ticks for a..z (dates or datetimes; z inclusive).""" + whole = not isinstance(z, datetime) # a date: up to the end of that day + a0, z0 = tnum(a), tnum(z) + (1 if whole else SLOT[grain]) + if grain == "w": # whole weeks, Monday to Sunday + a0 -= date.fromordinal(int(a0)).weekday() + z0 = tnum(z) - (z.weekday() if whole else 0) + 7 + span_d = max(z0 - a0, 1 / 24) + pw = width - ML - MR + x = lambda f: ML + pw * (f - a0) / span_d + ticks = [] + if span_d <= 1.6: # a day: every 3 hours + t = datetime.fromordinal(int(a0)) + timedelta(hours=3 * (int((a0 % 1) * 8) + 1)) + while tnum(t) < z0: + ticks.append({"x": round(x(tnum(t)), 1), "label": t.strftime("%H:%M")}) + t += timedelta(hours=3) + elif span_d <= 9: # a week: each day + d = date.fromordinal(int(a0)) + while tnum(d) < z0: + ticks.append({"x": round(x(tnum(d) + 0.5), 1), "label": d.strftime("%a %-d")}) + d += timedelta(days=1) + elif span_d <= 45: # a month: each Monday + d = date.fromordinal(int(a0)) + d += timedelta(days=(7 - d.weekday()) % 7) + while tnum(d) < z0: + ticks.append({"x": round(x(tnum(d)), 1), "label": d.strftime("%-d %b")}) + d += timedelta(days=7) + else: # months + d0 = date.fromordinal(int(a0)) + m, months = date(d0.year, d0.month, 1), [] + while tnum(m) < z0: + if tnum(m) >= a0: + months.append(m) + m = date(m.year + m.month // 12, m.month % 12 + 1, 1) + every = max(1, -(-len(months) // 8)) + ticks = [{"x": round(x(tnum(m)), 1), "label": m.strftime("%b") if m.month != 1 else str(m.year)} + for i, m in enumerate(months) if i % every == 0] + slot_w = pw * SLOT[grain] / span_d + return {"x": x, "a0": a0, "z0": z0, "ticks": ticks, "slot": slot_w, "bw": max(1.2, slot_w * 0.72)} + + +def chart(lines, a, z, unit="", bands=(), bars=False, limits=None, width=W, grain="d", fmt=None): + """SVG geometry for [(cls, name, [(t, value)])] over a..z: t = the start of a bucket + (datetime for hours, date for days / weeks — `grain`). Lines (+ dots) or bars from 0; + `bands`: shaded y ranges [(lo, hi, cls)]; `hits`: one hover strip per bucket with its + values (health.js shows them). None when there's nothing.""" + ax = xaxis(a, z, width, grain) + inr = lambda t: ax["a0"] <= tnum(t) < ax["z0"] + vals = [v for _, _, pts in lines for t, v in pts if inr(t) and v is not None] + if not vals: + return None + lo, hi = min(vals), max(vals) + if bars: + hi = max([hi] + [b for _, b, _ in bands]) + pad = max((hi - lo) * 0.12, abs(hi) * 0.02, 0.5) + lo, hi = (0, hi + pad) if bars else (lo - pad, hi + pad) + if limits: # e.g. a 0–100 score never shows 120 + lo, hi = max(lo, limits[0]), min(hi, limits[1]) + step = _nice_step(hi - lo) + lo, hi = floor(lo / step) * step, -floor(-hi / step) * step + y = lambda v: MT + (H - MT - MB) * (hi - v) / (hi - lo) + yt, t = [], lo + while t <= hi + step / 2: + yt.append({"y": round(y(t), 1), "label": f"{t:,.0f}" if step >= 1 else f"{t:g}"}) + t = round(t + step, 6) + cx = lambda t: ax["x"](tnum(t)) + ax["slot"] / 2 # middle of the bucket + out, tips = [], {} + fmt = fmt or (lambda v: fmt_num(v, unit)) + for cls, name, pts in lines: + pts = sorted((t, v) for t, v in pts if inr(t) and v is not None) + if not pts: + continue + xy = [(round(cx(t), 1), round(y(v), 1)) for t, v in pts] + rects = [{"x": round(px - ax["bw"] / 2, 1), "y": py, "w": round(ax["bw"], 1), "h": round(y(lo) - py, 1)} + for px, py in xy] if bars else [] + out.append({"cls": cls, "name": name, "d": "" if bars else "M" + " L".join(f"{px},{py}" for px, py in xy), + "dots": xy if len(xy) <= 45 and not bars else [], "rects": rects, "last": pts[-1][1], + "digits": 0 if all(float(v).is_integer() for _, v in pts) else 1}) + for t, v in pts: + tips.setdefault(t, []).append((cls, name, fmt(v))) + # tip lines: "class|text" — health.js puts a dot in the series' colour before it + hits = [{"x": round(ax["x"](tnum(t)), 1), "w": round(max(ax["slot"], 2), 1), + "tip": when_label(t, grain) + "\n" + "\n".join(f"{c}|{n}: {v}" if len(lines) > 1 else v for c, n, v in vs), + "day": t.isoformat() if grain == "d" and not isinstance(t, datetime) else None} # click → that day (href) + for t, vs in sorted(tips.items())] + shade = [{"cls": c, "y": round(y(min(b, hi)), 1), "h": round(y(max(lo2, lo)) - y(min(b, hi)), 1)} + for lo2, b, c in bands if b > lo and lo2 < hi] + return {"w": width, "h": H, "ml": ML, "mr": MR, "mt": MT, "mb": MB, "yt": yt, "xt": ax["ticks"], + "lines": out, "bands": shade, "unit": unit, "hits": hits} + + +def scale(v, lo, hi, cuts): + """A coloured bar from lo to hi cut at `cuts` [(upper bound, name)], with a marker at v: + {"segs": [{"name", "left", "width"} in %], "at": % or None}.""" + pos = lambda x: max(0, min(100, (x - lo) / (hi - lo) * 100)) + segs, a = [], lo + for top, name in cuts: + z = min(top, hi) + if z > a: + segs.append({"name": name, "left": round(pos(a), 2), "width": round(pos(z) - pos(a), 2), "from": a, "to": top}) + a = z + return {"segs": segs, "at": round(pos(v), 2) if v is not None else None} + + +# ---- the page -------------------------------------------------------------------------- + +def page(rows, s, rng="1y", today=None): + today = today or date.today() + prof = profile(s, today) + sex, height, age = prof["sex"], prof["height"], prof["age"] + cur = latest(rows, today) + m = _fresh(cur) + weight, waist, hip = m.get("weight"), m.get("waist"), m.get("hip") + + fat = calc.fat_all(m, height, sex, age) + for f in fat: + f["class"] = calc.fat_class(f["value"], sex, age) + f["missing"] = [MISSING.get(k) or FIELDS[k][0].lower() for k in f["missing"]] + est = [f["value"] for f in fat if f["value"] is not None] + fat_mid = median(est) if est else None + b = calc.bmi(weight, height) + hw = calc.healthy_weight(height) + + band = calc.fat_band(sex, age) + body = { + "bmi": b, "bmi_class": calc.bmi_class(b), "healthy": hw, + "bmi_age": calc.bmi_age_band(age), "bmi_ages": calc.BMI_AGE, + "bmi_bar": scale(b, 15, 40, [(18.5, "underweight"), (25, "normal"), (30, "overweight"), (99, "obese")]), + "fat_band": calc.fat_band(sex, age), "fat_ranges": calc.FAT_RANGES[calc._sexkey(sex)], + "whtr": calc.whtr(waist, height), "whtr_class": calc.whtr_class(calc.whtr(waist, height)), + "whr": calc.whr(waist, hip), "whr_class": calc.whr_class(calc.whr(waist, hip), sex), + "waist_class": calc.waist_class(waist, sex), + "fat": fat, "fat_mid": fat_mid, "fat_range": (min(est), max(est)) if len(est) > 1 else None, + "fat_class": calc.fat_class(fat_mid, sex, age), + "fat_bar": scale(fat_mid, 5, 50, list(zip((band or (0,) * 5)[2:] + (99,), calc.FAT_NAMES))) if band else None, "fat_n": len(est), + "fat_kg": weight * fat_mid / 100 if weight and fat_mid else None, + "lean_kg": weight * (1 - fat_mid / 100) if weight and fat_mid else None, + "bmr": calc.bmr_mifflin(weight, height, sex, age), "bmr_katch": calc.bmr_katch(weight, fat_mid), + } + + rng = rng if rng in RANGES else DEFAULT_RANGE + first = rows[0]["day"] if rows else today + a = span(rng, first, today) + sr = series(rows, prof) + charts = { + "weight": chart([("c-w", "Weight", sr["weight"])], a, today, "kg", + [(hw[0], hw[1], "ok")] if hw else (), width=WIDE), + "waist": chart([("c-x", "Waist", sr["waist"])], a, today, "cm", width=WIDE), + "bmi": chart([("c-b", "BMI", sr["bmi"])], a, today, "", [(18.5, 25, "ok")], width=WIDE), + "fat": chart([(f"c-{k}", n, sr[k]) for k, n, *_ in calc.FAT], a, today, "%", width=WIDE), + } + + used = [k for k in FIELDS if any(r[k] is not None for r in rows)] + return { + "today": today, "prof": prof, "cur": cur, "body": body, + "weight_change": change(rows, "weight", today), "waist_change": change(rows, "waist", today), + "charts": charts, "range": rng, "ranges": RANGES, + "cols": used, "rows": list(reversed(rows)), + "rows_json": {r["day"].isoformat(): dict(r, day=r["day"].isoformat()) for r in rows}, # the dialog + "last": {k: cur[k]["v"] for k in cur}, # form placeholders + } diff --git a/dashboard/plugins/health/watch.py b/dashboard/plugins/health/watch.py new file mode 100644 index 0000000..d506918 --- /dev/null +++ b/dashboard/plugins/health/watch.py @@ -0,0 +1,856 @@ +"""Views for the watch data: Sleep (with an analysis), Heart, Activity (steps, energy, +workouts), one workout (heart-rate graph + zones), the Overview tiles. + +Everything is computed here from the stored rows (db.nights / exercises / steps_days …) +and your settings (sex, age, height, weight from the measurements), so changing a +setting or adding a weight re-does every calorie. Bedtimes average around midnight +(hours from noon), so 23:30 and 00:30 average to midnight, not noon. +""" +from collections import defaultdict +from datetime import date, datetime, time, timedelta +from statistics import median + +from . import calc +from .views import (DEFAULT_RANGE, H, MB, ML, MR, MT, RANGES, WIDE, W, age_on, chart, fmt_num, profile, tnum, + when_label, xaxis) # RANGES: shared by every health tab + +SLEEP_OK = (7, 9) # hours: the usual adult recommendation +STAGES = ("deep", "light", "rem", "asleep", "awake", "nap") # stacking order, bottom up +STAGE_NAMES = {"deep": "Deep", "light": "Light", "rem": "REM", "asleep": "Asleep (no stage)", "awake": "Awake", + "nap": "Naps"} +# watch pages: range (days back, incl. today) and how values are grouped +GRAINS = {"h": "Hourly", "d": "Daily", "w": "Weekly"} +CAP = 60 # rows shown in a list + + +def period(rng, grain, today, allowed=("h", "d", "w"), default=DEFAULT_RANGE, first=None): + """(range key, grain, first day) — hourly only up to a week, weekly from a month. + "all" starts at `first` (the data's first day).""" + rng = rng if rng in RANGES else default + days = RANGES[rng][1] or max(1, (today - (first or today)).days + 1) + ok = [g for g in allowed if not (g == "h" and days > 7) and not (g == "w" and days < 28)] + grain = grain if grain in ok else ("d" if "d" in ok else ok[0]) + return rng, grain, today - timedelta(days=days - 1), ok + + +def bucket(points, grain, how="sum"): + """[(t, v)] → [(bucket start, value)]: per hour (t datetime), day or week (Monday).""" + acc = defaultdict(list) + for t, v in points: + if v is None: + continue + if grain == "h": + k = t.replace(minute=0, second=0, microsecond=0) + else: + d = t.date() if isinstance(t, datetime) else t + k = d - timedelta(days=d.weekday()) if grain == "w" else d + acc[k].append(v) + f = {"sum": sum, "avg": lambda xs: sum(xs) / len(xs), "min": min, "max": max}[how] + return sorted((k, f(v)) for k, v in acc.items()) + + +def capped(rows, n=CAP): + return rows[:n], max(0, len(rows) - n) +DEEP_OK = (13, 23) # % of sleep: a typical adult range + + +def _avg(xs): + xs = [x for x in xs if x is not None] + return sum(xs) / len(xs) if xs else None + + +def _from_noon(t): # datetime → hours since the noon before it (21:00 → 9, 07:00 → 19) + h = t.hour + t.minute / 60 + return h - 12 if h >= 12 else h + 12 + + +def _wake(n): # wake-up as hours from the noon before (07:00 → 19, 13:00 → 25): no wrap + return (n["end"] - datetime.combine(n["day"], time())).total_seconds() / 3600 + 12 + + +def clock(h): # hours since noon → "HH:MM" + if h is None: + return "—" + m = round(h * 60) % (24 * 60) + return f"{(m // 60 + 12) % 24:02d}:{m % 60:02d}" + + +def hm(minutes): + if minutes is None: + return "—" + m = round(minutes) + return f"{m // 60}h {m % 60:02d}m" + + +def spread(xs): + """Typical deviation that a few odd nights don't blow up: 1.4826 × median absolute + deviation (≈ the standard deviation for normal data).""" + if len(xs) < 3: + return 0.0 + m = median(xs) + return 1.4826 * median(abs(x - m) for x in xs) + + +def _since(rows, today, days, key="day"): + return [r for r in rows if 0 <= (today - r[key]).days < days] + + +def weight_on(weights, d): + """The weight measured nearest before d (else the first one after), kg or None.""" + before = [w for day, w in weights if day <= d] + if before: + return before[-1] + return weights[0][1] if weights else None + + +# ---- sleep: per night -------------------------------------------------------------------- + +def score(n, goal=8): + """0–100 from four parts (shown on hover): duration 50, deep sleep 20, efficiency 15, + interruptions 15. Nights without stages get the deep part pro rata from the rest.""" + h = n["asleep"] / 60 + dur = 50 * max(0.0, min(1.0, (h - 4) / (min(goal, 8) - 4 - 0.5))) + if h > 10: + dur -= min(15, (h - 10) * 10) + staged = n["light"] + n["deep"] + n["rem"] + deep_pct = n["deep"] / staged * 100 if staged else None + deep = 20 * max(0.0, min(1.0, (deep_pct - 5) / 15)) if deep_pct is not None else None + inbed = (n["end"] - n["start"]).total_seconds() / 60 + eff = n["asleep"] / inbed if inbed else 1 + effp = 15 * max(0.0, min(1.0, (eff - 0.80) / 0.15)) + intr = max(0.0, 15 - 4 * (n["wakeups"] or 0) - max(0, (n["awake"] or 0) - 20) / 4) + parts = {"Duration": dur, "Deep sleep": deep, "Efficiency": effp, "Interruptions": intr} + known = {k: v for k, v in parts.items() if v is not None} + total = sum(known.values()) * (100 / (100 - 20) if deep is None else 1) + return {"total": round(max(0, min(100, total))), "parts": {k: (round(v) if v is not None else None) for k, v in parts.items()}, + "eff": eff, "deep_pct": deep_pct, "inbed": inbed} + + +def _night(n, goal): + s = score(n, goal) + return dict(n, score=s["total"], parts=s["parts"], eff=s["eff"], deep_pct=s["deep_pct"], inbed=s["inbed"], + mid=(_from_noon(n["start"]) + _wake(n)) / 2, + unstaged=max(0, n["asleep"] - (n["light"] or 0) - (n["deep"] or 0) - (n["rem"] or 0))) + + +def hypnogram(n, runs): + """SVG geometry of one night: lanes awake / REM / light / deep, a block per stage run.""" + lanes = {"awake": 0, "rem": 1, "light": 2, "asleep": 2, "deep": 3} + a, z = n["start"] - timedelta(minutes=15), n["end"] + timedelta(minutes=15) + span_s = (z - a).total_seconds() + w, h, ml, mr, mt, mb = 900, 170, 70, 10, 8, 22 + lh = (h - mt - mb) / 4 + x = lambda t: ml + (w - ml - mr) * (t - a).total_seconds() / span_s + blocks = [{"x": round(x(s), 1), "w": round(max(0.8, x(e) - x(s)), 1), "y": round(mt + lanes[st] * lh + 2, 1), + "h": round(lh - 4, 1), "cls": f"st-{st}", + "tip": f"{STAGE_NAMES[st]}\n{s:%H:%M} – {e:%H:%M} · {hm((e - s).total_seconds() / 60)}"} + for s, e, st in runs] + ticks, t = [], (a + timedelta(minutes=59)).replace(minute=0, second=0) + step = 1 if (z - a).total_seconds() < 6 * 3600 else 2 + while t <= z: + if t.hour % step == 0: + ticks.append({"x": round(x(t), 1), "label": t.strftime("%H:%M")}) + t += timedelta(hours=1) + lanes_out = [{"y": round(mt + i * lh + lh / 2 + 4, 1), "label": l} for i, l in enumerate(("Awake", "REM", "Light", "Deep"))] + return {"w": w, "h": h, "ml": ml, "blocks": blocks, "ticks": ticks, "lanes": lanes_out, "mt": mt, "lh": round(lh, 1)} + + +def stacked(points, a, z, goal=None, grain="d"): + """Stacked bars of stages (hours) per night or per week (average): points = + [(date, {stage: minutes})]; hover = the breakdown.""" + ax = xaxis(a, z, W, grain) + pts = [(d, v) for d, v in points if ax["a0"] <= tnum(d) < ax["z0"]] + if not pts: + return None + top = max(max(sum(v.values()) for _, v in pts) / 60, goal or 0) * 1.08 + y = lambda v: MT + (H - MT - MB) * (1 - v / top) + bars, hits = [], [] + for d, v in pts: + acc, x0 = 0.0, ax["x"](tnum(d)) + ax["slot"] / 2 - ax["bw"] / 2 + for st in STAGES: + m = v.get(st) or 0 + if not m: + continue + y0, y1 = y(acc / 60), y((acc + m) / 60) + bars.append({"x": round(x0, 1), "y": round(y1, 1), "w": round(ax["bw"], 1), "h": round(y0 - y1, 1), + "cls": f"st-{st}", "day": d.isoformat()}) + acc += m + tip = [when_label(d, grain) + (" · average night" if grain == "w" else ""), + f"Asleep {hm(sum(v.get(k) or 0 for k in ('deep', 'light', 'rem', 'asleep')))}"] + tip += [f"{STAGE_NAMES[k]} {hm(v[k])}" for k in STAGES if v.get(k)] + hits.append({"x": round(ax["x"](tnum(d)), 1), "w": round(max(ax["slot"], 2), 1), "tip": "\n".join(tip), + "day": d.isoformat() if grain == "d" else None}) + step = 2 if top > 6 else 1 + yt = [{"y": round(y(t), 1), "label": f"{t}h"} for t in range(0, int(top) + 1, step)] + return {"w": W, "h": H, "ml": ML, "mr": MR, "mt": MT, "mb": MB, "bars": bars, "yt": yt, "xt": ax["ticks"], + "hits": hits, "goal": round(y(goal), 1) if goal else None} + + +def window_chart(nights, a, z, grain="d"): + """Each night as a bar from bedtime to wake-up (y = clock time, evening on top); + weekly: the average night of each week (average bedtime → average wake-up).""" + ax = xaxis(a, z, W, grain) + n = [r for r in nights if a <= r["day"] <= z] + if not n: + return None + if grain == "w": + wk = defaultdict(list) + for r in n: + wk[r["day"] - timedelta(days=r["day"].weekday())].append(r) + n = [{"day": d, "bed": _avg([_from_noon(r["start"]) for r in rs]), "up": _avg([_wake(r) for r in rs]), + "asleep": _avg([r["asleep"] for r in rs]), "n": len(rs)} for d, rs in sorted(wk.items())] + else: + n = [dict(r, bed=_from_noon(r["start"]), up=_wake(r)) for r in n] + top = min(r["bed"] for r in n) + bot = max(r["up"] for r in n) + top, bot = max(6, int(top) - 1), min(26, int(bot) + 2) + y = lambda h: MT + (H - MT - MB) * (min(max(h, top), bot) - top) / (bot - top) + step = 2 if bot - top > 8 else 1 + yt = [{"y": round(y(h), 1), "label": clock(h)} for h in range(top, bot + 1) if h % step == 0] + rects, hits = [], [] + for r in n: + x = ax["x"](tnum(r["day"])) + rects.append({"x": round(x + ax["slot"] / 2 - ax["bw"] / 2, 1), "y": round(y(r["bed"]), 1), + "w": round(ax["bw"], 1), "h": round(y(r["up"]) - y(r["bed"]), 1), + "short": r["asleep"] < SLEEP_OK[0] * 60}) + if grain == "w": + tip = (f'{when_label(r["day"], "w")} · average of {r["n"]} night{"s" if r["n"] != 1 else ""}\n' + f'{clock(r["bed"])} → {clock(r["up"])}\nAsleep {hm(r["asleep"])}') + else: + tip = f'{when_label(r["day"], "d")}\n{r["start"]:%H:%M} → {r["end"]:%H:%M}\nAsleep {hm(r["asleep"])}' + hits.append({"x": round(x, 1), "w": round(max(ax["slot"], 2), 1), + "day": r["day"].isoformat() if grain == "d" else None, "tip": tip}) + return {"w": W, "h": H, "ml": ML, "mr": MR, "mt": MT, "mb": MB, "yt": yt, "xt": ax["ticks"], "rects": rects, "hits": hits} + + +# ---- sleep: analysis ----------------------------------------------------------------------- + +WEEKDAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") + + +def findings(ns, workouts, naps, goal): + """Plain-language observations over the nights `ns` (already analysed by _night).""" + out = [] + if len(ns) < 5: + return out + hrs = [n["asleep"] / 60 for n in ns] + avg = sum(hrs) / len(hrs) + short = sum(h < SLEEP_OK[0] for h in hrs) + out.append(("Duration", f"You sleep {hm(avg * 60)} on average; {short} of {len(ns)} nights " + f"({round(short / len(ns) * 100)} %) were under 7 h." + + (" That's below the 7–9 h most adults need." if avg < 7 else " That's within the 7–9 h most adults need."))) + dp = [n["deep_pct"] for n in ns if n["deep_pct"] is not None] + if dp: + d = sum(dp) / len(dp) + where = "within" if DEEP_OK[0] <= d <= DEEP_OK[1] else ("below" if d < DEEP_OK[0] else "above") + out.append(("Deep sleep", f"{d:.0f} % of your sleep is deep sleep — {where} the typical {DEEP_OK[0]}–{DEEP_OK[1]} %. " + "No REM comes through from Mi Fitness, so “light” here likely includes your REM.")) + beds = [_from_noon(n["start"]) for n in ns] + wakes = [_wake(n) for n in ns] + sb, sw = spread(beds) * 60, spread(wakes) * 60 + reg = "fairly regular" if max(sb, sw) < 45 else ("somewhat irregular" if max(sb, sw) < 75 else "irregular") + out.append(("Regularity", f"Bedtime typically varies by ±{sb:.0f} min, wake-up by ±{sw:.0f} min — {reg}. " + "A steady schedule (within ±30 min) is one of the strongest levers for better sleep.")) + free = [n for n in ns if n["day"].weekday() >= 5 and n["mid"] is not None] # woke Sat / Sun + work = [n for n in ns if n["day"].weekday() < 5 and n["mid"] is not None] + if len(free) >= 3 and len(work) >= 3: + jl = _avg([n["mid"] for n in free]) - _avg([n["mid"] for n in work]) + dl = _avg([n["asleep"] for n in free]) - _avg([n["asleep"] for n in work]) + out.append(("Weekends", f"On weekends the middle of your sleep is {abs(jl) * 60:.0f} min {'later' if jl > 0 else 'earlier'} " + f"and you sleep {hm(abs(dl))} {'more' if dl > 0 else 'less'} than on weekdays" + + (" — “social jetlag”; over an hour is worth narrowing." if abs(jl) >= 1 else "."))) + wdays = {w["day"] for w in workouts} + after = [n for n in ns if n["day"] - timedelta(days=1) in wdays] + rest = [n for n in ns if n["day"] - timedelta(days=1) not in wdays] + if len(after) >= 5 and len(rest) >= 5: + da = _avg([n["asleep"] for n in after]) - _avg([n["asleep"] for n in rest]) + dd = (_avg([n["deep_pct"] for n in after]) or 0) - (_avg([n["deep_pct"] for n in rest]) or 0) + out.append(("Workouts", f"After a workout day you sleep {hm(abs(da))} {'longer' if da > 0 else 'shorter'} " + f"and get {abs(dd):.1f} points {'more' if dd > 0 else 'less'} deep sleep than after rest days " + f"({len(after)} vs {len(rest)} nights).")) + early = {w["day"] for w in workouts if w["start"].hour < 10} + before = [n for n in ns if n["day"] in early] + other = [n for n in ns if n["day"] not in early] + if len(before) >= 5 and len(other) >= 5: + db_ = _avg([n["asleep"] for n in before]) - _avg([n["asleep"] for n in other]) + dw = _avg([_wake(n) for n in before]) - _avg([_wake(n) for n in other]) + dbed = _avg([_from_noon(n["start"]) for n in before]) - _avg([_from_noon(n["start"]) for n in other]) + out.append(("Morning workouts", f"Before a morning workout ({len(before)} nights) you get up {abs(dw) * 60:.0f} min " + f"{'later' if dw > 0 else 'earlier'} and go to bed {abs(dbed) * 60:.0f} min {'later' if dbed > 0 else 'earlier'} " + f"than other nights — so you sleep {hm(abs(db_))} {'more' if db_ > 0 else 'less'}.")) + late_days = {w["day"] for w in workouts if w["start"].hour >= 19} + late = [n for n in ns if n["day"] - timedelta(days=1) in late_days] + if len(late) >= 3: + dl = _avg([n["asleep"] for n in late]) - _avg([n["asleep"] for n in rest]) if rest else 0 + out.append(("Late workouts", f"After evening workouts (19:00 or later, {len(late)} nights) you sleep " + f"{hm(abs(dl))} {'more' if dl > 0 else 'less'} than after rest days.")) + if naps: + out.append(("Naps", f"{len(naps)} naps in this period, {hm(_avg([p['minutes'] for p in naps]))} on average.")) + if len(ns) >= 20: + a, b = ns[-14:], ns[-28:-14] + if len(b) >= 7: + d = _avg([n["asleep"] for n in a]) - _avg([n["asleep"] for n in b]) + out.append(("Trend", f"The last two weeks you slept {hm(abs(d))} {'more' if d > 0 else 'less'} per night than the two weeks before.")) + debt = sum(max(0, goal * 60 - n["asleep"]) for n in ns[-14:]) + out.append(("Sleep debt", f"Short of your {goal:g} h goal by {hm(debt)} in total over the last {min(14, len(ns))} nights.")) + return out + + +def weekday_table(ns): + by = defaultdict(list) + for n in ns: + by[(n["day"] - timedelta(days=1)).weekday()].append(n) # the evening you went to bed + rows = [] + for i, name in enumerate(WEEKDAYS): + xs = by.get(i, []) + rows.append({"name": name, "n": len(xs), "asleep": _avg([n["asleep"] for n in xs]), + "bed": _avg([_from_noon(n["start"]) for n in xs]), "score": _avg([n["score"] for n in xs])}) + top = max((r["asleep"] or 0 for r in rows), default=1) or 1 + for r in rows: + r["pct"] = round((r["asleep"] or 0) / top * 100) + return rows + + +def sleep_page(nights, naps, stage_runs_for, workouts, s, rng, grain, day=None, today=None): + today = today or date.today() + goal = float(s.get("sleep_goal") or 8) + rng, grain, a, grains = period(rng, grain, today, ("d", "w"), first=nights[0]["day"] if nights else None) + all_n = [_night(n, goal) for n in nights] + ns = [n for n in all_n if a <= n["day"] <= today] + sel = next((n for n in all_n if n["day"] == day), None) if day else None + sel = sel or (all_n[-1] if all_n else None) + i = all_n.index(sel) if sel else -1 + rnaps = [p for p in naps if a <= p["start"].date() <= today] + nap_min = defaultdict(int) + for p in rnaps: + nap_min[p["start"].date()] += p["minutes"] + per = {n["day"]: {"deep": n["deep"] or 0, "light": n["light"] or 0, "rem": n["rem"] or 0, + "asleep": n["unstaged"], "awake": n["awake"] or 0} for n in ns} + for d, m in nap_min.items(): + per.setdefault(d, {})["nap"] = m + if grain == "w": # average night of each week + wk = defaultdict(list) + for d, v in per.items(): + wk[d - timedelta(days=d.weekday())].append(v) + per = {k: {st: sum(v.get(st, 0) for v in vs) / len(vs) for st in STAGES} for k, vs in wk.items()} + return { + "today": today, "range": rng, "ranges": RANGES, "grain": grain, "grains": grains, "goal": goal, "night": sel, + "hyp": hypnogram(sel, stage_runs_for(sel["day"])) if sel else None, + "prev": all_n[i - 1]["day"] if i > 0 else None, "next": all_n[i + 1]["day"] if 0 <= i < len(all_n) - 1 else None, + "avg": {"asleep": _avg([n["asleep"] for n in ns]), "deep": _avg([n["deep_pct"] for n in ns]), + "score": _avg([n["score"] for n in ns]), "eff": _avg([n["eff"] for n in ns]), + "bed": _avg([_from_noon(n["start"]) for n in ns]), "wake": _avg([_wake(n) for n in ns]), + "n": len(ns)}, + "stack": stacked(sorted(per.items()), a, today, goal, grain), + "window": window_chart(ns, a, today, grain), + "score_chart": chart([("c-s", "Score", bucket([(n["day"], n["score"]) for n in ns], grain, "avg"))], + a, today, "", limits=(0, 100), grain=grain, fmt=lambda v: f"{v:.0f} / 100"), + "findings": findings(ns, workouts, rnaps, goal), "weekdays": weekday_table(ns), + "naps": list(reversed(rnaps))[:CAP], + "stage_names": STAGE_NAMES, + } + + +# ---- workouts -------------------------------------------------------------------------------- + +def with_resting(s, hr, wks=()): + """Settings + what's worked out from the data: `resting_auto` = the median resting heart + rate of the last 90 days (Mi's daily value; else the daily lowest readings), used unless + resting_hr is set; `activity_auto` = activity level from your workouts (last 12 weeks), + used when activity_level is "auto".""" + recent = [r for r in hr if (date.today() - r["day"]).days <= 90] or hr + vals = [r["rest"] for r in recent if r.get("rest")] or [r["low"] for r in recent if r["low"]] + mins = sum(w["minutes"] for w in wks if 0 <= (date.today() - w["day"]).days < 84) / 12 + rest = s.get("resting_hr") or (round(median(vals)) if vals else None) + prof = profile(s, date.today()) + hrmax = calc.max_hr(prof["age"], s.get("max_hr")) + walks = [(w["distance"], w["minutes"], w["avg_hr"]) for w in wks + if calc.exercise_name(w["type"], w.get("name")) == "Walking"] + vo2, n = calc.vo2max_from_walks(walks, rest, hrmax) + return dict(s, resting_auto=round(median(vals)) if vals else None, activity_auto=calc.activity_level(mins), + workout_min_week=mins, vo2_walks=vo2, vo2_walks_n=n) + + +def _person(s, d, weights): + prof = profile(s, d) + age = age_on(prof["birth"], d) + hrmax = calc.max_hr(age, s.get("max_hr")) + rest = s.get("resting_hr") or s.get("resting_auto") + method = s.get("zones") or "hrr" + if not rest: + method = "max" + weight = weight_on(weights, d) + level = s.get("activity_level") + if level in (None, "", "auto"): + level = s.get("activity_auto") or 5 + if s.get("vo2max"): + vo2, src = s["vo2max"], "your setting" + elif s.get("vo2_walks"): + vo2, src = s["vo2_walks"], f"from {s['vo2_walks_n']} brisk GPS walks" + else: + vo2 = calc.vo2max_estimate(age, prof["sex"], weight, prof["height"], int(level)) + src = "estimated from age, sex, BMI and how much you exercise" + return {"sex": prof["sex"], "age": age, "height": prof["height"], "weight": weight, + "hrmax": hrmax, "rest": rest, "rest_set": bool(s.get("resting_hr")), "max_set": bool(s.get("max_hr")), + "method": method, "bounds": calc.zone_bounds(hrmax, rest, method), + "vo2max": vo2, "vo2_set": bool(s.get("vo2max")), "vo2_src": src, + "level": dict((str(k), v) for k, v in calc.ACTIVITY_LEVELS).get(str(level), ""), + "level_auto": s.get("activity_level") in (None, "", "auto")} + + +def enrich(w, s, weights): + """A stored workout + name, zones, our calorie estimate (needs weight, age, height).""" + p = _person(s, w["day"], weights) + z = calc.zones(w["hr_hist"], p["bounds"]) + secs = sum(z) or 1 + kcal = calc.workout_kcal(w["hr_hist"], p["weight"], p["height"], p["sex"], p["age"], p["hrmax"], p["rest"], p["vo2max"]) \ + if w["hr_hist"] else (None, None) + load = calc.trimp(w["hr_hist"], p["rest"], p["hrmax"], p["sex"]) if w["hr_hist"] else None + return dict(w, name=calc.exercise_name(w["type"], w.get("name")), hrmax=p["hrmax"], bounds=p["bounds"], zones=z, + load=load, + zone_pct=[round(x / secs * 100) for x in z], kcal=kcal[0], kcal_total=kcal[1], person=p) + + +def zone_rows(z, bounds): + secs = sum(z) or 1 + rows = [{"name": "Resting", "from": None, "to": round(bounds[0]) - 1, "cls": "z0", "sec": z[0], + "pct": round(z[0] / secs * 100)}] + for i, (name, _, cls) in enumerate(calc.ZONES): + hi = bounds[i + 1] if i + 1 < len(bounds) else None + rows.append({"name": name, "from": round(bounds[i]), "to": round(hi) - 1 if hi else None, + "cls": cls, "sec": z[i + 1], "pct": round(z[i + 1] / secs * 100)}) + return rows + + +def hr_graph(samples, w): + """Heart rate over the workout (averaged into ≤ 300 points) on zone-coloured bands.""" + if not samples: + return None + a, z = w["start"], w["end"] + dur = max(1.0, (z - a).total_seconds()) + n = 300 + buckets = defaultdict(list) + for t, b in samples: + buckets[min(n - 1, int((t - a).total_seconds() / dur * n))].append(b) + hrmax = w["hrmax"] + bounds = w["bounds"] + lo = min(min(b for _, b in samples) - 5, round(bounds[0]) - 5) + hi = max(max(b for _, b in samples) + 5, hrmax) + ww, hh, ml, mr, mt, mb = 1300, 260, 40, 10, 8, 22 + x = lambda i: ml + (ww - ml - mr) * i / (n - 1) + y = lambda v: mt + (hh - mt - mb) * (hi - v) / (hi - lo) + pts = [(round(x(i), 1), round(y(sum(v) / len(v)), 1)) for i, v in sorted(buckets.items())] + hits = [] + for i, v in sorted(buckets.items()): + sec = int(i / n * dur) + hits.append({"x": round(x(i) - (ww - ml - mr) / n / 2, 1), "w": round((ww - ml - mr) / n, 2), + "tip": f"{sec // 60}′{sec % 60:02d}″ · {round(sum(v) / len(v))} bpm"}) + bands = [] + for i, (name, _, cls) in enumerate(calc.ZONES): + b0 = bounds[i] + b1 = bounds[i + 1] if i + 1 < len(bounds) else hi + if b1 > lo: + bands.append({"cls": cls, "y": round(y(min(b1, hi)), 1), "h": round(y(max(b0, lo)) - y(min(b1, hi)), 1), "name": name}) + yt = [{"y": round(y(v), 1), "label": v} for v in range(int(lo // 20 + 1) * 20, int(hi) + 1, 20)] + mins = int(dur // 60) + step = 5 if mins <= 60 else 10 if mins <= 120 else 30 + xt = [{"x": round(ml + (ww - ml - mr) * m * 60 / dur, 1), "label": f"{m}′"} for m in range(0, mins + 1, step)] + return {"w": ww, "h": hh, "ml": ml, "mr": mr, "mt": mt, "mb": mb, "hits": hits, + "d": "M" + " L".join(f"{p},{q}" for p, q in pts), + "bands": bands, "yt": yt, "xt": xt, "max_y": round(y(max(b for _, b in samples)), 1)} + + +def workout_page(w, samples, s, weights, neighbours, all_wks=()): + ws = enriched(all_wks, s, weights) if all_wks else [] + w = next((x for x in ws if x["id"] == w["id"]), None) or enrich(w, s, weights) + return {"today": date.today(), "w": w, "graph": hr_graph(samples, w), "zones": zone_rows(w["zones"], w["bounds"]), + "prev": neighbours[0], "next": neighbours[1]} + + +_ENRICHED = [] # [(wks, weights, settings key, result)], newest first + + +def enriched(wks, s, weights): + """with_effects([enrich(…)]) of every workout — the slow part of these pages (zones, + load, calories for each one). Remembered while the same lists (the plugin keeps them + per database version, so `is` holds) and the same settings come in; the lists are + kept referenced, so their ids can't be reused.""" + skey = repr(sorted(s.items())) + for w0, wt0, k0, r in _ENRICHED: + if w0 is wks and wt0 is weights and k0 == skey: + return r + r = with_effects([enrich(x, s, weights) for x in wks]) + _ENRICHED[:] = ([(wks, weights, skey, r)] + _ENRICHED)[:4] + return r + + +def with_effects(ws): + """Each workout's effect: its load vs the average load of your workouts in the 6 weeks + before it (calc.effect).""" + ws = sorted(ws, key=lambda w: w["start"]) + for i, w in enumerate(ws): + prev = [x["load"] for x in ws[:i] if x["load"] and (w["start"] - x["start"]).days < calc.FITNESS_DAYS] + w["usual"] = sum(prev) / len(prev) if len(prev) >= 3 else None + w["effect"] = calc.effect(w["load"], w["usual"]) + return ws + + +FORM = [(-30, "Overload", "fatigue far above fitness — rest soon"), (-10, "Building", "training hard, fitness rising"), + (10, "Neutral", "steady"), (999, "Fresh", "rested, ready for a hard session")] + + +def form_label(v): + return next((name, tip) for top, name, tip in FORM if v < top) + + +def training(ws, a, z, grain): + """Load per day → fitness / fatigue / form over a..z (computed from the first workout).""" + loads = defaultdict(float) + for w in ws: + loads[w["day"]] += w["load"] or 0 + if not loads: + return None, None + series = calc.fitness_fatigue(loads, min(loads), z) + cur = series[-1] + pts = [(d, f, t, fm) for d, f, t, fm in series if d >= a] + g = grain if grain != "h" else "d" + how = "avg" + ch = chart([("c-fit", "Fitness", bucket([(d, f) for d, f, _, _ in pts], g, how)), + ("c-fat", "Fatigue", bucket([(d, t) for d, _, t, _ in pts], g, how)), + ("c-form", "Form", bucket([(d, fm) for d, _, _, fm in pts], g, how))], a, z, "", grain=g, + fmt=lambda v: f"{v:.0f}") + return ch, {"fitness": cur[1], "fatigue": cur[2], "form": cur[3], "form_label": form_label(cur[3]), + "load7": sum(loads.get(z - timedelta(days=i), 0) for i in range(7))} + + +def vitality(hr, s, weights, a, z, grain, today): + """Intensity minutes per day (moderate + 2 × vigorous, from the whole day's heart rate).""" + p = _person(s, today, weights) + per = {} + for r in hr: + if r.get("hist"): + mod, vig = calc.intensity_minutes(r["hist"], p["rest"], p["hrmax"]) + per[r["day"]] = mod + 2 * vig + week = sum(v for d, v in per.items() if 0 <= (today - d).days < 7) + g = "w" if grain == "w" else "d" + pts = bucket([(d, v) for d, v in per.items() if a <= d <= z], g) + goal = calc.VITALITY_GOAL if g == "w" else calc.VITALITY_GOAL / 7 + ch = chart([("c-vit", "Vitality", pts)], a, z, "", bands=[(goal, goal * 10, "ok")], bars=True, grain=g, + fmt=lambda v: f"{v:.0f} intensity min") + return ch, {"week": week, "goal": calc.VITALITY_GOAL} + + +# ---- activity: steps, energy, workouts ----------------------------------------------------- + +def day_energy(d, steps, workouts, s, weights): + """Estimated energy for a day: resting (Mifflin–St Jeor) + walking (steps outside + workouts) + workouts (heart-rate based, above resting). None without weight / age.""" + p = _person(s, d, weights) + bmr = calc.bmr_mifflin(p["weight"], p["height"], p["sex"], p["age"]) + if not bmr: + return None + walk = calc.steps_kcal(max(0, (steps["steps"] - steps["workout_steps"]) if steps else 0), p["weight"], p["height"], p["sex"]) + act = sum(w["kcal"] or 0 for w in workouts) + return {"bmr": bmr, "walk": walk, "workouts": act, "total": bmr + walk + act} + + +def day_activity(d, steps, wks, s, weights): + """One day's activity for the food diary (Health provides it as "day"): steps, the + workouts (name, minutes, our kcal) and the day's energy (day_energy: resting + walking + + workouts); None when nothing was recorded that day.""" + sd = next((x for x in steps if x["day"] == d), None) + ws = [w for w in enriched(wks, s, weights) if w["day"] == d] + if not sd and not ws: + return None + e = day_energy(d, sd, ws, s, weights) + return {"steps": sd["steps"] if sd else None, + "workouts": [{"id": w["id"], "name": w["name"], "minutes": round(w["minutes"]), + "kcal": round(w["kcal"]) if w["kcal"] else None} for w in ws], + "energy": {k: round(v) for k, v in e.items()} if e else None} + + +def energy_summary(steps, wks, s, weights, days=28, today=None): + """What the food diary's calorie target starts from (Health provides it as "energy"): + the latest weight, resting energy now, and the average daily energy (day_energy) over + the last `days` full days that have step data — None parts when the profile is missing.""" + today = today or date.today() + p = _person(s, today, weights) + w_day = max((d for d, _ in weights if d <= today), default=None) + by_day = defaultdict(list) + for w in enriched(wks, s, weights): + by_day[w["day"]].append(w) + sd = {x["day"]: x for x in steps} + per = [] + for i in range(1, days + 1): # yesterday back: today isn't over yet + d = today - timedelta(days=i) + if d in sd: + e = day_energy(d, sd[d], by_day.get(d, []), s, weights) + if e: + per.append(e) + return {"weight": p["weight"], "weight_day": w_day, "height": p["height"], "sex": p["sex"], "age": p["age"], + "bmr": calc.bmr_mifflin(p["weight"], p["height"], p["sex"], p["age"]), + "tdee": round(_avg([e["total"] for e in per])) if per else None, "days": len(per), "of_days": days, + "walk": round(_avg([e["walk"] for e in per])) if per else None, + "workouts": round(_avg([e["workouts"] for e in per])) if per else None} + + +def activity_page(steps, wks, s, weights, rng, grain, hourly_steps, hr=(), today=None): + """hourly_steps(a, z) → {hour: steps} (only asked for the hourly view).""" + today = today or date.today() + rng, grain, a, grains = period(rng, grain, today, first=min([x["day"] for x in steps[:1]] + [w["day"] for w in wks[:1]], default=None)) + ws = enriched(wks, s, weights) + rs = [x for x in steps if a <= x["day"] <= today] + rw = [w for w in ws if a <= w["day"] <= today] + by_day = defaultdict(list) + for w in ws: + by_day[w["day"]].append(w) + sd = {x["day"]: x for x in steps} + energy = [] + d = a + while d <= today: + e = day_energy(d, sd.get(d), by_day.get(d, []), s, weights) + if e and (d in sd or d in by_day): + energy.append((d, e)) + d += timedelta(days=1) + p = _person(s, today, weights) + if grain == "h": + hs = hourly_steps(datetime.combine(a, time()), datetime.combine(today + timedelta(days=1), time())) + step_pts = sorted(hs.items()) + wk_pts = [] + for w in rw: # workout minutes per hour + t = w["start"] + while t < w["end"]: + h = t.replace(minute=0, second=0, microsecond=0) + nxt = min(w["end"], h + timedelta(hours=1)) + wk_pts.append((h, (nxt - t).total_seconds() / 60)) + t = nxt + wk_pts = bucket(wk_pts, "h") + en_pts = [] + else: + how = "avg" if grain == "w" else "sum" + step_pts = bucket([(x["day"], x["steps"]) for x in rs], grain, how) + en_pts = bucket([(d, e["total"]) for d, e in energy], grain, how) + wk_pts = bucket([(w["day"], w["minutes"]) for w in rw], grain) + per = " a day" if grain == "w" else "" + rows, more = capped(list(reversed(rw))) + return { + "today": today, "range": rng, "ranges": RANGES, "grain": grain, "grains": grains, "person": p, + "n": len(rw), "minutes": sum(w["minutes"] for w in rw), "kcal": sum(w["kcal"] or 0 for w in rw), + "steps_avg": _avg([x["steps"] for x in rs]), "steps_days": len(rs), + "steps_band": sum(1 for x in rs if x["source"] == "band"), + "energy_avg": _avg([e["total"] for _, e in energy]), "walk_avg": _avg([e["walk"] for _, e in energy]), + "bmr": calc.bmr_mifflin(p["weight"], p["height"], p["sex"], p["age"]), + "steps_chart": chart([("c-st", "Steps", step_pts)], a, today, "", bars=True, grain=grain, + fmt=lambda v: f"{v:,.0f} steps{per}"), + "energy_chart": chart([("c-en", "Energy", en_pts)], a, today, "", bars=True, grain=grain, + fmt=lambda v: f"{v:,.0f} kcal{per}") if en_pts else None, + "week_chart": chart([("c-a", "Workouts", wk_pts)], a, today, "", bars=True, grain=grain, + fmt=lambda v: f"{hm(v)} of workouts"), + "rows": rows, "more": more, + "training": training(ws, a, today, grain), "vitality": vitality(hr, s, weights, a, today, grain, today), + "device_vs_ours": (lambda ps: sum(a for a, _ in ps) / sum(b for _, b in ps) if ps else None)( + [(w["kcal_device"], w["kcal"]) for w in rw if w["kcal_device"] and w["kcal"]]), # ratio of totals + "walk_check": walk_check(ws), + } + + +def walk_check(ws): + """How our heart-rate energy compares with the walking equation (speed + weight, very + accurate on level ground) on GPS walks — a check of the heart-rate method on you.""" + pairs = [] + for w in ws: + if w["name"] == "Walking" and w["distance"] and w["minutes"] >= 5 and w["kcal"] and w["person"]["weight"]: + speed = w["distance"] / w["minutes"] + if 40 <= speed <= 110: + ref = (calc.walk_vo2(speed) - 3.5) * w["person"]["weight"] / 1000 * 5 * w["minutes"] + pairs.append((w["kcal"], ref)) + if len(pairs) < 3: + return None + return {"n": len(pairs), "ratio": sum(a for a, _ in pairs) / sum(b for _, b in pairs)} + + +# ---- heart --------------------------------------------------------------------------------- + +def _paged(rows, page, per): + pages = max(1, -(-len(rows) // per)) + page = min(max(1, page), pages) + return rows[(page - 1) * per:page * per], page, pages + + +def vitals_view(vs, a, z, grain, bp_page=1, ox_page=1, per=10): + """Blood pressure + oxygen for the Heart page — two kinds of reading, kept apart: the + latest of each (with its category), the 30-day blood-pressure average, a chart each over + a..z (grain: per reading day, or weekly average; hourly ranges use days) and each kind's + readings, newest first, `per` a page (spot checks are sparse: a range would often show none).""" + g = "d" if grain == "h" else grain + today = z if isinstance(z, date) else z.date() + bp = [v for v in vs if v["sys"]] + ox = [v for v in vs if v["spo2"]] + def avg_bp(days): + r = [v for v in bp if (today - v["t"].date()).days < days] + return (round(_avg([v["sys"] for v in r])), round(_avg([v["dia"] for v in r])), len(r)) if r else None + rv = [v for v in vs if a <= v["t"].date() <= today] + rb, ro = [v for v in rv if v["sys"]], [v for v in rv if v["spo2"]] + last_bp, last_ox = (bp[-1] if bp else None), (ox[-1] if ox else None) + bp_chart = chart([("c-bs", "Systolic", bucket([(v["t"].date(), v["sys"]) for v in rb], g, "avg")), + ("c-bd", "Diastolic", bucket([(v["t"].date(), v["dia"]) for v in rb], g, "avg"))], + a, today, "mmHg", grain=g, limits=(50, 170), + bands=[(0, 120, "ok"), (140, 300, "high")]) if rb else None + ox_chart = chart([("c-ox", "Oxygen", bucket([(v["t"].date(), v["spo2"]) for v in ro], g, "avg"))], + a, today, "%", grain=g, limits=(88, 100), bands=[(95, 101, "ok")], + fmt=lambda x: f"{x:.0f} %") if ro else None + bp_rows, bp_page, bp_pages = _paged(list(reversed(bp)), bp_page, per) + ox_rows, ox_page, ox_pages = _paged(list(reversed(ox)), ox_page, per) + return { + "any": bool(vs), "last_bp": last_bp, "last_ox": last_ox, + "last_bp_class": calc.bp_class(last_bp["sys"], last_bp["dia"]) if last_bp else None, + "last_ox_class": calc.spo2_class(last_ox["spo2"]) if last_ox else None, + "bp7": avg_bp(7), "bp30": avg_bp(30), "bp_chart": bp_chart, "ox_chart": ox_chart, + "bp": {"rows": [dict(v, cls=calc.bp_class(v["sys"], v["dia"])) for v in bp_rows], "n": len(bp), + "page": bp_page, "pages": bp_pages}, + "ox": {"rows": [dict(v, cls=calc.spo2_class(v["spo2"])) for v in ox_rows], "n": len(ox), + "page": ox_page, "pages": ox_pages}, + "json": {str(v["id"]): {"id": v["id"], "kind": "bp" if v["sys"] else "ox", "day": v["t"].date().isoformat(), + "time": v["t"].strftime("%H:%M"), "sys": v["sys"], "dia": v["dia"], "spo2": v["spo2"], + "note": v["note"]} for v in bp_rows + ox_rows}, + } + + +def heart_page(hr, rng, grain, samples_for, today=None, vitals=(), bp_page=1, ox_page=1): + """samples_for(a, z) → [(datetime, bpm)] (only for the hourly view); vitals = db.vitals().""" + today = today or date.today() + rng, grain, a, grains = period(rng, grain, today, first=hr[0]["day"] if hr else None) + rh = [r for r in hr if a <= r["day"] <= today] + w7, w30 = _since(hr, today, 7), _since(hr, today, 30) + lows = [r for r in hr if r["low"]] + if grain == "h": + sm = samples_for(datetime.combine(a, time()), datetime.combine(today + timedelta(days=1), time())) + lo_pts, hi_pts = bucket(sm, "h", "min"), bucket(sm, "h", "max") + else: + lo_pts = bucket([(r["day"], r["low"]) for r in rh], grain, "min") + hi_pts = bucket([(r["day"], r["high"]) for r in rh], grain, "max") + rest_pts = bucket([(r["day"], r["rest"]) for r in rh if r.get("rest")], "d" if grain == "h" else grain, "avg") + return { + "today": today, "range": rng, "ranges": RANGES, "grain": grain, "grains": grains, + "last": lows[-1] if lows else None, + "low7": _avg([r["low"] for r in w7]), "low30": _avg([r["low"] for r in w30]), + "lowest30": min((r["low"] for r in w30 if r["low"]), default=None), + "high30": max((r["high"] for r in w30 if r["high"]), default=None), + "chart": chart([("c-hl", "Lowest", lo_pts), ("c-hr", "Resting", rest_pts if grain != "h" else []), + ("c-hh", "Highest", hi_pts)], a, today, "bpm", width=WIDE, grain=grain), + "rest7": _avg([r["rest"] for r in w7 if r.get("rest")]), "rest30": _avg([r["rest"] for r in w30 if r.get("rest")]), + "vit": vitals_view(vitals, a, today, grain, bp_page, ox_page), + } + + +# ---- overview ------------------------------------------------------------------------------- + +def overview(nights, stage_runs_for, wks, samples_for, steps, s, weights, hr=(), today=None): + """Overview: this month's workouts, steps, last night (score + stages), last workout + (heart rate on its zones). samples_for(a, z) → the workout's heart-rate samples.""" + today = today or date.today() + goal = float(s.get("sleep_goal") or 8) + night = _night(nights[-1], goal) if nights else None + n7 = [_night(n, goal) for n in _since(nights, today, 7)] + mon = [w for w in wks if w["day"].strftime("%Y-%m") == today.strftime("%Y-%m")] + allw = enriched(wks, s, weights) + mon_e = [w for w in allw if w["day"].strftime("%Y-%m") == today.strftime("%Y-%m")] + last = allw[-1] if allw else None + a = today - timedelta(days=6) + sd = {x["day"]: x["steps"] for x in steps} + return { + "goal": goal, "night": night, "hyp": hypnogram(night, stage_runs_for(night["day"])) if night else None, + "score7": _avg([n["score"] for n in n7]), + "month_n": len(mon), "month_min": sum(w["minutes"] for w in mon), "month_kcal": sum(w["kcal"] or 0 for w in mon_e), + "steps7": _avg([x["steps"] for x in _since(steps, today, 7)]), "steps_today": sd.get(today), + "workout": last, "graph": hr_graph(samples_for(last["start"], last["end"]), last) if last else None, + "training": training(allw, a, today, "d")[1], "vitality": vitality(hr, s, weights, a, today, "d", today)[1], + } + + +# ---- report for a doctor ---------------------------------------------------------------------- + +REPORT_RANGES = {"3m": ("3 months", 91), "6m": ("6 months", 182), "1y": ("12 months", 365)} + + +def report(rows, s, nights, naps, wks, steps, hr, vitals, weights, rng="3m", today=None): + """One printable summary of everything, for a doctor: plain values with their reference + ranges (WHO, ESC 2024, sleep / activity recommendations) and where they come from — no + verdicts, no scores of our own.""" + from . import views + today = today or date.today() + rng = rng if rng in REPORT_RANGES else "3m" + days = REPORT_RANGES[rng][1] + a = today - timedelta(days=days - 1) + weeks = days / 7 + grain = "w" if days > 100 else "d" + goal = float(s.get("sleep_goal") or 8) + prof = views.profile(s, today) + + # body + b = views.page(rows, s, "1y", today) + cur, body = b["cur"], b["body"] + rw = [(r["day"], r["weight"]) for r in rows if r["weight"] is not None and a <= r["day"] <= today] + wchange = (rw[-1][1] - rw[0][1], (rw[-1][1] - rw[0][1]) / rw[0][1] * 100, rw[0][0]) if len(rw) > 1 else None + + # blood pressure, oxygen + rv = [v for v in vitals if a <= v["t"].date() <= today] + bp, ox = [v for v in rv if v["sys"]], [v for v in rv if v["spo2"]] + bp_avg = (round(_avg([v["sys"] for v in bp])), round(_avg([v["dia"] for v in bp]))) if bp else None + bp_cls = calc.bp_class(*bp_avg) if bp_avg else None + all_ox = [v for v in vitals if v["spo2"]] + + # heart rate (the band) + rh = [r for r in hr if a <= r["day"] <= today] + rest = [r["rest"] for r in rh if r.get("rest")] + rest_first = _avg([r["rest"] for r in rh if r.get("rest") and (r["day"] - a).days < 30]) + rest_last = _avg([r["rest"] for r in rh if r.get("rest") and (today - r["day"]).days < 30]) + rest_avg = _avg(rest) + rest_chart = chart([("c-hr", "Resting", bucket([(r["day"], r["rest"]) for r in rh if r.get("rest")], grain, "avg"))], + a, today, "bpm", grain=grain, width=WIDE, fmt=lambda v: f"{v:.0f} bpm") if rest else None + + # sleep (the band) + ns = [_night(n, goal) for n in nights if a <= n["day"] <= today] + rnaps = [p for p in naps if a <= p["start"].date() <= today] + sl = None + if ns: + asleep = _avg([n["asleep"] for n in ns]) + sl = {"n": len(ns), "asleep": asleep, "under7": sum(n["asleep"] < 420 for n in ns), + "under6": sum(n["asleep"] < 360 for n in ns), "bed": _avg([_from_noon(n["start"]) for n in ns]), + "wake": _avg([_wake(n) for n in ns]), "bed_sd": spread([_from_noon(n["start"]) for n in ns]), + "wake_sd": spread([_wake(n) for n in ns]), "deep": _avg([n["deep_pct"] for n in ns]), + "wakeups": _avg([n["wakeups"] or 0 for n in ns]), "awake": _avg([n["awake"] or 0 for n in ns]), + "naps_week": len(rnaps) / weeks} + sleep_chart = chart([("c-s", "Asleep", bucket([(n["day"], n["asleep"] / 60) for n in ns], grain, "avg"))], + a, today, "h", grain=grain, limits=(0, 10), bands=[(7, 9, "ok")], width=WIDE, + fmt=lambda v: hm(v * 60)) if ns else None + + # activity + rs = [x for x in steps if a <= x["day"] <= today] + rw_ = [w for w in enriched(wks, s, weights) if a <= w["day"] <= today] + kinds = defaultdict(int) + for w in rw_: + kinds[w["name"]] += 1 + act = {"steps": _avg([x["steps"] for x in rs]), "steps_days": len(rs), "n": len(rw_), + "per_week": len(rw_) / weeks, "min_week": sum(w["minutes"] for w in rw_) / weeks, + "kinds": sorted(kinds.items(), key=lambda kv: -kv[1])} + steps_chart = chart([("c-st", "Steps", bucket([(x["day"], x["steps"]) for x in rs], grain, "avg"))], + a, today, "", bars=True, grain=grain, width=WIDE, fmt=lambda v: f"{v:,.0f} steps a day") if rs else None + wchart = chart([("c-w", "Weight", [(d, w) for d, w in rw])], a, today, "kg", grain="d", width=WIDE) if rw else None + bp_chart = chart([("c-bs", "Systolic", bucket([(v["t"].date(), v["sys"]) for v in bp], grain, "avg")), + ("c-bd", "Diastolic", bucket([(v["t"].date(), v["dia"]) for v in bp], grain, "avg"))], + a, today, "mmHg", grain=grain, limits=(50, 170), width=WIDE, + bands=[(0, 120, "ok"), (140, 300, "high")]) if bp else None + + return { + "today": today, "range": rng, "ranges": REPORT_RANGES, "a": a, "prof": prof, + "cur": cur, "body": body, "wchange": wchange, "wchart": wchart, "measures": len(rw), + "bp": bp, "bp_avg": bp_avg, "bp_cls": bp_cls, "bp_range": ((min(v["sys"] for v in bp), max(v["sys"] for v in bp)), + (min(v["dia"] for v in bp), max(v["dia"] for v in bp))) if bp else None, + "bp_chart": bp_chart, "ox": ox, "ox_avg": _avg([v["spo2"] for v in ox]), "ox_min": min((v["spo2"] for v in ox), default=None), + "ox_last": all_ox[-1] if all_ox else None, + "rest_avg": rest_avg, "rest_first": rest_first, "rest_last": rest_last, + "rest_range": (min(rest), max(rest)) if rest else None, "rest_chart": rest_chart, + "hr_low": min((r["low"] for r in rh if r["low"]), default=None), "hr_days": len(rh), + "sleep": sl, "sleep_chart": sleep_chart, "act": act, "steps_chart": steps_chart, + } diff --git a/dashboard/plugins/notes/__init__.py b/dashboard/plugins/notes/__init__.py new file mode 100644 index 0000000..a6d01dd --- /dev/null +++ b/dashboard/plugins/notes/__init__.py @@ -0,0 +1,137 @@ +"""Notes: markdown notes in folders, with #tags, pinned notes, checklists, search and a trash — +synced with the phone app (where they're written most). + + /notes the list (folders, tags, pinned, trash, search) + the editor: markdown text + with a toolbar, or the preview (its checkboxes tick); saves as you type + /notes/export.zip every note as a .md file, in its folders + /notes/api/… JSON (same-origin writes, like the core's) + +Data: dash_data/notes/notes.db (SQLite, see db.py). Made at start-up, so notes written on the phone +arrive even before the plugin is switched on here. Two versions of one note written at the same +time (here and on the phone, before they synced) are both kept: syncdb's "fork". +""" +import io +import os +import re +import zipfile +from contextlib import closing +from datetime import date + +from flask import Response, abort, jsonify, render_template, request + +from . import db + +META = { + "title": "Notes", + "glyph": "🗒", + "glyph_color": "#e8d27a", + "glyph_svg": {"viewBox": "-12 -12 24 24", # a page with a folded corner and three lines + "d": "M-7 -10 H3 L8 -5 V10 H-7 Z M-4 -3 V-1.4 H5 V-3 Z M-4 1.6 V3.2 H5 V1.6 Z " + "M-4 6.2 V7.8 H1.5 V6.2 Z"}, + "description": "Markdown notes in folders, with #tags, pinned notes, checklists and search — " + "written here or in the phone app, synced both ways.", + "links": [{"label": "Open notes", "href": "/notes"}], + "settings": [], + # one row per note; "fork": the text is versioned — two edits at once keep both (syncdb.py) + "sync": {"notes.db": {"note": {"fork": ["body", "updated"]}}}, +} + + +def register(ctx): + bp = ctx.blueprint("/notes") + ctx.warm("/notes") + ctx.nav("Notes", "/notes") + here = os.path.dirname(os.path.abspath(__file__)) + db.connect(ctx.data_path("notes.db")).close() # the sync needs the file before the first note + + @bp.context_processor + def asset_version(): # cache-buster for notes.css / .js + st = os.path.join(here, "static") + return {"asset_v": "%x" % int(max(os.path.getmtime(os.path.join(st, f)) for f in os.listdir(st)))} + + def con(): + return closing(db.connect(ctx.data_path("notes.db"))) + + def body(): + if not ctx.same_origin(): + abort(403) + return request.get_json(silent=True) or {} + + def answer(fn): + try: + return fn() + except db.Invalid as e: + return jsonify(error=str(e), field=e.field), 400 + + @bp.route("/", strict_slashes=False) + @ctx.cached_page("notes.db") + def index(): + with con() as c: + notes = db.all_notes(c) + return render_template("notes/index.html", notes=notes, page="notes") + + @bp.route("/api/list") + def api_list(): # the page re-reads it when it comes back to the screen + with con() as c: + return jsonify(notes=db.all_notes(c)) + + @bp.route("/api/save", methods=["POST"]) + def api_save(): # {id?, body?, folder?, pinned?, base?} → {note, conflict} + d = body() + def go(): + with con() as c: + note, conflict = db.save(c, d) + return jsonify(note=note, conflict=conflict) + return answer(go) + + @bp.route("/api/trash", methods=["POST"]) + def api_trash(): # {id, on}: into the trash / back + d = body() + with con() as c: + db.trash(c, d.get("id"), bool(d.get("on", True))) + return jsonify(note=db.get(c, d.get("id"))) + + @bp.route("/api/delete", methods=["POST"]) + def api_delete(): # {id} — from the trash, for good + d = body() + with con() as c: + db.delete(c, d.get("id")) + return jsonify(ok=True) + + @bp.route("/api/empty-trash", methods=["POST"]) + def api_empty(): + body() + with con() as c: + return jsonify(deleted=db.empty_trash(c)) + + @bp.route("/api/keep", methods=["POST"]) + def api_keep(): # {id}: a conflicted copy becomes an ordinary note + d = body() + with con() as c: + db.keep_copy(c, d.get("id")) + return jsonify(note=db.get(c, d.get("id"))) + + @bp.route("/api/folder", methods=["POST"]) + def api_folder(): # {from, to}: rename / move a folder with everything in it + d = body() + def go(): + with con() as c: + return jsonify(moved=db.rename_folder(c, d.get("from"), d.get("to"))) + return answer(go) + + @bp.route("/export.zip") + def export_zip(): # every note outside the trash as /.md + with con() as c: + notes = [n for n in db.all_notes(c) if not n["trashed"]] + buf, used = io.BytesIO(), set() + with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z: + for n in notes: + name = re.sub(r'[\\/:*?"<>|\x00-\x1f]+', " ", db.title(n["body"])).strip(" .")[:80] or "Untitled" + path, i = f"{n['folder'] + '/' if n['folder'] else ''}{name}", 1 + while path.lower() in used: + i += 1 + path = f"{n['folder'] + '/' if n['folder'] else ''}{name} ({i})" + used.add(path.lower()) + z.writestr(f"notes/{path}.md", n["body"]) + return Response(buf.getvalue(), mimetype="application/zip", + headers={"Content-Disposition": f'attachment; filename="notes-{date.today()}.zip"'}) diff --git a/dashboard/plugins/notes/db.py b/dashboard/plugins/notes/db.py new file mode 100644 index 0000000..b1f92bf --- /dev/null +++ b/dashboard/plugins/notes/db.py @@ -0,0 +1,188 @@ +"""Notes storage: one SQLite file (dash_data/notes/notes.db), one `note` row per note. + +A note is markdown text; its title is its first line, its tags the #words in it (both worked +out on read — the page and the app do it the same way). `folder` is a path ("Work/Acme", +'' = no folder): a folder exists while a note is in it. + +Versions (for the sync's "keep both copies", syncdb "fork"): a change of the text gets a new +`rev` once the old one has been seen elsewhere (`_known`), appended to `revs` (the last REVS, +space-separated). A save says which rev it was written +on (`base`); when the note changed meanwhile (a sync came in while you typed), the save becomes a +copy instead — `origin` = its rev marks it as a conflicted copy. The same marker comes from the +sync when two devices changed one note before they met. Pinning, moving, trashing don't make a +rev (they go by the plain last-change-wins). + +Trash: `trashed` = when (UTC); deleted for good only from the trash. +""" +import os +import secrets +import sqlite3 +import threading +from datetime import datetime, timezone + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS note ( + id INTEGER PRIMARY KEY, + folder TEXT NOT NULL DEFAULT '', + body TEXT NOT NULL DEFAULT '', + pinned INTEGER NOT NULL DEFAULT 0, + created TEXT NOT NULL, -- UTC, 2026-10-21T09:30:00Z + updated TEXT NOT NULL, -- the text's last change + rev TEXT NOT NULL, + revs TEXT NOT NULL DEFAULT '', + origin TEXT, -- a conflicted copy: the rev it keeps + trashed TEXT -- in the trash since +); +""" +REVS = 200 # versions remembered per note (a device further behind gets an extra copy) +MAX_BODY = 1_000_000 +MAX_FOLDER = 200 +_init_lock = threading.Lock() +_ready = set() + + +class Invalid(ValueError): + def __init__(self, field, msg): + super().__init__(msg) + self.field = field + + +def connect(path): + """A connection for one request (sqlite3 connections don't cross threads).""" + con = sqlite3.connect(path, timeout=10) + con.row_factory = sqlite3.Row + if path not in _ready: + with _init_lock: + con.executescript(SCHEMA) + con.commit() + _ready.add(path) + os.chmod(path, 0o600) + return con + + +def now(): + return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def new_rev(): + return secrets.token_hex(6) + + +def _row(r): + return {k: r[k] for k in ("id", "folder", "body", "pinned", "created", "updated", "rev", "origin", "trashed")} + + +def all_notes(con): + return [_row(r) for r in con.execute("SELECT * FROM note ORDER BY updated DESC")] + + +def get(con, nid): + r = con.execute("SELECT * FROM note WHERE id = ?", (nid,)).fetchone() + return _row(r) if r else None + + +def clean_folder(f): + """ " Work / Acme/ " → "Work/Acme".""" + parts = [p.strip() for p in str(f or "").replace("\\", "/").split("/")] + out = "/".join(p for p in parts if p) + if len(out) > MAX_FOLDER: + raise Invalid("folder", "That folder name is too long.") + return out + + +def save(con, d): + """{id?, body?, folder?, pinned?, base?} → (note, conflict). New note: no id. Fields left out + stay. A text written on an older version (base ≠ the note's rev) is saved as a copy.""" + if "body" in d: + body = str(d["body"] or "") + if len(body) > MAX_BODY: + raise Invalid("body", "The note is too long (1 MB at most).") + t = now() + if not d.get("id"): + rev = new_rev() + cur = con.execute("INSERT INTO note (folder, body, pinned, created, updated, rev, revs) VALUES (?, ?, ?, ?, ?, ?, ?)", + (clean_folder(d.get("folder")), str(d.get("body") or ""), int(bool(d.get("pinned"))), + t, t, rev, rev)) + con.commit() + return get(con, cur.lastrowid), False + r = con.execute("SELECT * FROM note WHERE id = ?", (d["id"],)).fetchone() + if not r: + raise Invalid("id", "That note is gone (deleted on another device?).") + sets = {} + if "folder" in d: + sets["folder"] = clean_folder(d["folder"]) + if "pinned" in d: + sets["pinned"] = int(bool(d["pinned"])) + if "body" in d and body != r["body"]: + if d.get("base") and d["base"] != r["rev"]: # changed meanwhile: keep yours beside it + rev = new_rev() + cur = con.execute("INSERT INTO note (folder, body, pinned, created, updated, rev, revs, origin) " + "VALUES (?, ?, 0, ?, ?, ?, ?, ?)", + (sets.get("folder", r["folder"]), body, t, t, rev, rev, rev)) + con.commit() + return get(con, cur.lastrowid), True + if _known(con, r): + rev = new_rev() + sets.update(rev=rev, revs=" ".join((r["revs"].split() + [rev])[-REVS:])) + sets.update(body=body, updated=t) + if sets: + con.execute(f"UPDATE note SET {', '.join(f'{k} = ?' for k in sets)} WHERE id = ?", (*sets.values(), r["id"])) + con.commit() + return get(con, r["id"]), False + + +def _known(con, r): + """Has another device seen this version (it came from one, or went out)? Then a change is a new + version; until then typing goes on in the same one — a rev per sync, not per keystroke, so REVS + reach far back.""" + try: + m = dict(con.execute("SELECT k, v FROM _sync_meta WHERE k IN ('dev', 'pushed')").fetchall()) + except sqlite3.Error: # no sync groundwork yet + return True + return r["_dev"] != m.get("dev") or (r["_hlc"] or 0) <= (m.get("pushed") or 0) + + +def keep_copy(con, nid): + """A conflicted copy becomes an ordinary note.""" + con.execute("UPDATE note SET origin = NULL WHERE id = ?", (nid,)) + con.commit() + + +def trash(con, nid, on=True): + con.execute("UPDATE note SET trashed = ? WHERE id = ?", (now() if on else None, nid)) + con.commit() + + +def delete(con, nid): + """For good — only notes in the trash.""" + con.execute("DELETE FROM note WHERE id = ? AND trashed IS NOT NULL", (nid,)) + con.commit() + + +def empty_trash(con): + n = con.execute("DELETE FROM note WHERE trashed IS NOT NULL").rowcount + con.commit() + return n + + +def rename_folder(con, old, new): + """Every note in `old` and its sub-folders moves to `new` (same sub-paths).""" + old, new = clean_folder(old), clean_folder(new) + if not old: + raise Invalid("folder", "Pick a folder to rename.") + n = 0 + for r in con.execute("SELECT id, folder FROM note WHERE folder = ? OR folder LIKE ? ESCAPE '\\'", + (old, old.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + "/%")).fetchall(): + con.execute("UPDATE note SET folder = ? WHERE id = ?", (clean_folder(new + r["folder"][len(old):]), r["id"])) + n += 1 + con.commit() + return n + + +def title(body): + """The first line with text, without its heading marks.""" + for line in (body or "").splitlines(): + s = line.strip().lstrip("#").strip() + if s: + return s[:120] + return "Untitled" diff --git a/dashboard/plugins/notes/static/notes.css b/dashboard/plugins/notes/static/notes.css new file mode 100644 index 0000000..3795ba4 --- /dev/null +++ b/dashboard/plugins/notes/static/notes.css @@ -0,0 +1,146 @@ +/* Notes — on top of dash.css (its tokens and header). Real px. Wide: three columns that fill the + window, each scrolling on its own; < 1100 px the left column folds behind the list's heading; + < 760 px one column at a time (list or note). */ +#page.page-notes { height: 100vh; display: flex; flex-direction: column; gap: 12px; font-size: 15px; } +.nt { flex: 1; min-height: 0; display: grid; grid-template-columns: 230px 330px minmax(0, 1fr); gap: 12px; position: relative; } +.nt-side, .nt-list, .nt-ed, .nt-blank { background: var(--card); border-radius: 14px; min-height: 0; } + +/* ---- where ------------------------------------------------------------------------------ */ +.nt-side { display: flex; flex-direction: column; padding: 12px; gap: 8px; overflow: auto; } +.nt-q, .nt-folder, .nt-renbox { box-sizing: border-box; background: #10131a; color: var(--fg); border: 1px solid #262d3b; + border-radius: 8px; padding: 8px 10px; font: 15px "DejaVu Web", sans-serif; } +.nt-q { width: 100%; } +.nt-q:focus, .nt-folder:focus, .nt-renbox:focus { outline: none; border-color: var(--accent); } +.nt-nav { display: flex; flex-direction: column; gap: 2px; } +.nt-nv { display: flex; align-items: center; gap: 8px; border: 0; background: none; color: var(--fg); text-align: left; + padding: 7px 8px; border-radius: 8px; font: 15px "DejaVu Web", "Symbola Web", sans-serif; cursor: pointer; } +.nt-nv:hover { background: #1d222d; } +.nt-nv.on { background: #262d3b; color: var(--accent); } +.nt-nl { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.nt-nc { color: var(--dim); font-size: 13px; } +.nt-fi { display: inline-block; margin-left: calc(var(--d) * 14px); margin-right: 6px; color: var(--dim); font-size: 11px; } +.nt-cap { margin: 10px 8px 2px; color: var(--dim); font-size: 12px; text-transform: uppercase; } +.nt-cap:empty { margin: 6px 0; border-top: 1px solid #262d3b; } +.nt-tags { display: flex; flex-wrap: wrap; gap: 5px; padding: 2px 6px; } +.nt-tagb { border: 0; border-radius: 999px; background: #262d3b; color: var(--cool); padding: 3px 9px; + font: 13px "DejaVu Web", sans-serif; cursor: pointer; } +.nt-tagb span { color: var(--dim); } +.nt-tagb.on { background: #4a3b1e; color: var(--accent); } +.nt-export { margin-top: auto; padding: 8px; color: var(--muted); font-size: 13px; text-decoration: none; } +.nt-export:hover { color: var(--fg); } + +/* ---- the list --------------------------------------------------------------------------- */ +.nt-list { display: flex; flex-direction: column; overflow: hidden; } +.nt-lh { display: flex; align-items: center; gap: 8px; padding: 12px 12px 8px; } +.nt-where { flex: 1; min-width: 0; border: 0; background: none; color: var(--fg); text-align: left; padding: 0; + font: 700 18px "DejaVu Web", sans-serif; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; cursor: default; } +.nt-renbox { flex: 1; min-width: 0; font-weight: 700; } +.nt-ren, .nt-new, .nt-empty { border: 0; border-radius: 8px; background: #262d3b; color: var(--fg); padding: 7px 12px; + font: 14px "DejaVu Web", sans-serif; cursor: pointer; white-space: nowrap; } +.nt-new { background: var(--accent); color: var(--bg); font-weight: 700; } +.nt-empty.armed { background: #ff7a7a; color: var(--bg); } +.nt-items { flex: 1; overflow: auto; padding: 0 8px 10px; display: flex; flex-direction: column; gap: 2px; } +.nt-it { display: flex; flex-direction: column; gap: 3px; border: 0; background: none; color: var(--fg); text-align: left; + padding: 9px 10px; border-radius: 10px; cursor: pointer; font: 15px "DejaVu Web", "Symbola Web", sans-serif; } +.nt-it:hover { background: #1d222d; } +.nt-it.on { background: #262d3b; } +.nt-it1 { display: flex; align-items: baseline; gap: 6px; min-width: 0; } +.nt-it1 b { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.nt-it1 time { color: var(--dim); font-size: 12px; flex: none; } +.nt-pinmark, .nt-warn { font-size: 12px; flex: none; } +.nt-warn { color: var(--warm); } +.nt-it2 { color: var(--muted); font-size: 13px; line-height: 1.35; display: -webkit-box; -webkit-line-clamp: 2; + -webkit-box-orient: vertical; overflow: hidden; } +.nt-it3 { display: flex; flex-wrap: wrap; gap: 4px 8px; font-size: 12px; color: var(--cool); } +.nt-fold { color: var(--dim); } +.nt-fold::before { content: "▸ "; } +.nt-none { color: var(--muted); padding: 10px; margin: 0; } + +/* ---- the note --------------------------------------------------------------------------- */ +.nt-ed { display: flex; flex-direction: column; overflow: hidden; } +.nt-ed[hidden], .nt-blank[hidden] { display: none; } +.nt-blank { display: flex; align-items: center; justify-content: center; color: var(--muted); } +.nt-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 10px 12px; border-bottom: 1px solid #262d3b; } +.nt-bar button { border: 0; border-radius: 8px; background: none; color: var(--fg); min-width: 34px; height: 34px; + padding: 0 8px; font: 15px "DejaVu Web", "Symbola Web", sans-serif; cursor: pointer; } +.nt-bar button:hover { background: #1d222d; } +.nt-back { display: none; font-size: 22px !important; } +.nt-mode { display: flex; border-radius: 8px; overflow: hidden; background: #10131a; } +.nt-mode a { padding: 7px 14px; color: var(--muted); text-decoration: none; font-size: 14px; } +.nt-mode a.on { background: #262d3b; color: var(--accent); } +.nt-mode[hidden], .nt-tools[hidden] { display: none; } +.nt-tools { display: flex; gap: 2px; } +.nt-gap { flex: 1; } +.nt-folder { width: 170px; padding: 6px 9px; font-size: 14px; } +.nt-pin { filter: grayscale(1); opacity: .45; } +.nt-pin.on { filter: none; opacity: 1; background: #262d3b !important; } +.nt-restore { background: #262d3b !important; } +.nt-purge.armed { background: #ff7a7a !important; color: var(--bg) !important; } +.nt-banner, .nt-trashed { margin: 10px 12px 0; padding: 10px 12px; border-radius: 10px; background: #3a2a17; color: #f4d6a8; + font-size: 14px; line-height: 1.45; } +.nt-trashed { background: #262d3b; color: var(--muted); } +.nt-banner[hidden], .nt-trashed[hidden] { display: none; } +.nt-keep { border: 0; background: none; color: var(--accent); padding: 0; font: inherit; text-decoration: underline; cursor: pointer; } +.nt-text { flex: 1; min-height: 0; resize: none; border: 0; outline: none; background: none; color: var(--fg); padding: 16px 20px; + font: 15px/1.55 "DejaVu Sans Mono", monospace; tab-size: 4; } +.nt-text[hidden] { display: none; } +.nt-view { flex: 1; min-height: 0; overflow: auto; padding: 8px 22px 20px; } +.nt-view[hidden] { display: none; } +.nt-foot { padding: 6px 14px; border-top: 1px solid #262d3b; font-size: 12px; color: var(--dim); } +.nt-state.bad { color: var(--warm); } + +/* ---- rendered markdown ------------------------------------------------------------------ */ +.md { line-height: 1.55; max-width: 820px; overflow-wrap: anywhere; } +.md h1, .md h2, .md h3, .md h4, .md h5, .md h6 { margin: 1em 0 .4em; line-height: 1.25; } +.md h1 { font-size: 26px; color: var(--accent); } .md h2 { font-size: 21px; } .md h3 { font-size: 18px; } +.md h4, .md h5, .md h6 { font-size: 15px; color: var(--muted); } +.md p { margin: .55em 0; } +.md a { color: var(--cool); } +.md code { background: #10131a; border-radius: 5px; padding: 1px 5px; font: 13.5px "DejaVu Sans Mono", monospace; } +.md pre { background: #10131a; border-radius: 10px; padding: 12px 14px; overflow: auto; } +.md pre code { background: none; padding: 0; } +.md blockquote { margin: .6em 0; padding: 2px 14px; border-left: 3px solid #3a4253; color: var(--muted); } +.md hr { border: 0; border-top: 1px solid #262d3b; margin: 1.2em 0; } +.md ul, .md ol { margin: .4em 0; padding-left: 1.6em; } +.md li { margin: .15em 0; } +.md li.task { list-style: none; margin-left: -1.4em; display: flex; gap: 8px; align-items: baseline; } +.md li.task > ul, .md li.task > ol { flex-basis: 100%; } +.md li.task { flex-wrap: wrap; } +.md li.task input { width: 17px; height: 17px; accent-color: var(--accent); cursor: pointer; transform: translateY(2px); } +.md li.task.done > span { color: var(--dim); text-decoration: line-through; } +.md mark { background: #4a3b1e; color: var(--fg); padding: 0 2px; border-radius: 3px; } +.md del { color: var(--dim); } +.md .nt-tag { color: var(--cool); cursor: pointer; } +.md .nt-tag:hover { text-decoration: underline; } +.md .nt-table { overflow: auto; } +.md table { border-collapse: collapse; margin: .6em 0; } +.md th, .md td { border: 1px solid #262d3b; padding: 5px 10px; text-align: left; } +.md th { background: #10131a; } + +/* ---- smaller windows -------------------------------------------------------------------- */ +@media (max-width: 1099px) { + .nt { grid-template-columns: 320px minmax(0, 1fr); } + .nt-side { display: none; position: absolute; z-index: 3; left: 0; top: 48px; width: 300px; max-height: 70vh; + box-shadow: 0 10px 30px rgba(0, 0, 0, .55); border: 1px solid #262d3b; } + .nt.nav-open .nt-side { display: flex; } + .nt-where { cursor: pointer; } + .nt-where::after { content: " ▾"; color: var(--dim); font-weight: 400; } +} +@media (max-width: 759px) { + #page.page-notes { height: auto; min-height: 100vh; } + .nt { grid-template-columns: minmax(0, 1fr); } + .nt[data-view="list"] .nt-ed, .nt[data-view="list"] .nt-blank, .nt[data-view="note"] .nt-list { display: none; } + .nt-blank { display: none !important; } + .nt-side { width: auto; right: 0; } + .nt-list, .nt-ed { min-height: calc(100vh - 170px); } + .nt-back { display: inline-block; } + .nt-gap { display: none; } + .nt-folder { width: auto; flex: 1; min-width: 0; } + .nt-tools { order: 9; width: 100%; overflow-x: auto; } + .nt-text { min-height: 60vh; } +} +@media print { + .head, .nt-side, .nt-list, .nt-bar, .nt-foot, .nt-banner { display: none !important; } + .nt { display: block; } .nt-ed { background: none; } + .md, .md * { color: #000 !important; background: none !important; } +} diff --git a/dashboard/plugins/notes/static/notes.js b/dashboard/plugins/notes/static/notes.js new file mode 100644 index 0000000..37360fe --- /dev/null +++ b/dashboard/plugins/notes/static/notes.js @@ -0,0 +1,523 @@ +// Notes page (/notes). Left: search, All / Pinned / folders / tags / conflicts / Trash. Middle: the +// notes there (pinned first, newest change first). Right: the note — markdown text with a toolbar +// (Edit) or rendered (Preview: its checkboxes tick). Saves as you type (0.7 s after the last key, +// one save at a time, Ctrl+S now); each save names the version it was written on, so a text +// written while another device changed the note comes back as a separate copy (db.save). +// The list is re-read when the tab comes back and every minute (the phone's notes arrive with +// the Pi's sync). Narrow windows show one column at a time. No browser dialogs. +(function () { + const $ = (s, el = document) => el.querySelector(s); + const root = $(".nt"); + let notes = JSON.parse($("#nt-data").textContent); + const S = { filter: { kind: "all" }, q: "", cur: null, mode: "view", dirty: false, timer: null, + queue: null, run: null, navOpen: false }; + + const post = async (url, data) => { + const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw new Error(j.error || `Error ${r.status}`); + return j; + }; + + // ---- what a note shows ------------------------------------------------------------------ + const esc = (s) => s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" }[c])); + const fold = (s) => s.normalize("NFD").replace(/\p{M}/gu, "").toLowerCase(); + const titleOf = (b) => { + for (const l of (b || "").split("\n")) { const s = l.trim().replace(/^#+/, "").trim(); if (s) return s.slice(0, 120); } + return "Untitled"; + }; + const TAG = /(^|\s)#(\p{L}[\p{L}\p{N}_\/-]*)/gu; + function tagsOf(b) { + const plain = (b || "").replace(/```[\s\S]*?(```|$)/g, "").replace(/`[^`\n]*`/g, ""); + const out = new Set(); + for (const m of plain.matchAll(TAG)) out.add(m[2].toLowerCase()); + return [...out]; + } + function snippet(b, q) { + const lines = (b || "").split("\n"); + const first = lines.findIndex((l) => l.trim()); + let text = lines.slice(first + 1).map((l) => l.replace(/^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?/, "")) + .join(" ").replace(/[#>*_`~=\[\]]|\(http[^)]*\)/g, "").replace(/\s+/g, " ").trim(); + if (q) { + const at = fold(text).indexOf(fold(q.split(/\s+/)[0])); + if (at > 40) text = "…" + text.slice(at - 30); + } + return text.slice(0, 160); + } + function when(iso) { + const d = new Date(iso), now = new Date(); + if (d.toDateString() === now.toDateString()) return d.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); + const o = { day: "numeric", month: "short" }; + if (d.getFullYear() !== now.getFullYear()) o.year = "numeric"; + return d.toLocaleDateString([], o); + } + + // ---- markdown → HTML (the app's markdown.dart reads it the same way) --------------------- + const SAFE = /^(https?:|mailto:)/i; + function inline(s) { + const keep = []; + const hold = (html) => `\u0000${keep.push(html) - 1}\u0000`; + s = s.replace(/`([^`]+)`/g, (_, c) => hold(`<code>${esc(c)}</code>`)); + s = s.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (m, t, u) => + SAFE.test(u) ? hold(`<a href="${esc(u)}" target="_blank" rel="noopener noreferrer">${esc(t)}</a>`) : m); + s = s.replace(/\bhttps?:\/\/[^\s<>()]+[^\s<>().,;:!?'"]/g, (u) => + hold(`<a href="${esc(u)}" target="_blank" rel="noopener noreferrer">${esc(u)}</a>`)); + s = esc(s) + .replace(/\*\*(.+?)\*\*|__(.+?)__/g, (_, a, b) => `<strong>${a ?? b}</strong>`) + .replace(/(^|[^*\w])\*(?!\s)(.+?)\*(?!\w)/g, "$1<em>$2</em>") + .replace(/(^|[^_\w])_(?!\s)(.+?)_(?!\w)/g, "$1<em>$2</em>") + .replace(/~~(.+?)~~/g, "<del>$1</del>") + .replace(/==(.+?)==/g, "<mark>$1</mark>") + .replace(TAG, (_, a, t) => `${a}<span class="nt-tag" data-tag="${t.toLowerCase()}">#${t}</span>`); + return s.replace(/\u0000(\d+)\u0000/g, (_, i) => keep[+i]); + } + const RE = { + fence: /^\s*(```|~~~)/, head: /^(#{1,6})\s+(.*)$/, hr: /^\s*([-*_])(\s*\1){2,}\s*$/, quote: /^\s*>/, + item: /^(\s*)([-*+]|\d+[.)])\s+(.*)$/, tsep: /^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$/, + }; + const cells = (l) => l.trim().replace(/^\||\|$/g, "").split("|").map((c) => c.trim()); + function md(src, st = { task: 0 }) { + const L = src.replace(/\r\n?/g, "\n").split("\n"); + const out = []; + let i = 0; + const starts = (l) => RE.fence.test(l) || RE.head.test(l) || RE.hr.test(l) || RE.quote.test(l) || RE.item.test(l); + while (i < L.length) { + const l = L[i]; + if (!l.trim()) { i++; continue; } + let m; + if ((m = l.match(RE.fence))) { + const code = []; + for (i++; i < L.length && !L[i].trim().startsWith(m[1]); i++) code.push(L[i]); + i++; + out.push(`<pre><code>${esc(code.join("\n"))}</code></pre>`); + } else if ((m = l.match(RE.head))) { + out.push(`<h${m[1].length}>${inline(m[2].replace(/\s#+\s*$/, ""))}</h${m[1].length}>`); + i++; + } else if (RE.hr.test(l)) { + out.push("<hr>"); + i++; + } else if (RE.quote.test(l)) { + const q = []; + for (; i < L.length && RE.quote.test(L[i]); i++) q.push(L[i].replace(/^\s*>\s?/, "")); + out.push(`<blockquote>${md(q.join("\n"), st)}</blockquote>`); + } else if (l.includes("|") && i + 1 < L.length && RE.tsep.test(L[i + 1])) { + const head = cells(l); + let h = `<table><thead><tr>${head.map((c) => `<th>${inline(c)}</th>`).join("")}</tr></thead><tbody>`; + for (i += 2; i < L.length && L[i].includes("|") && L[i].trim(); i++) { + h += `<tr>${cells(L[i]).map((c) => `<td>${inline(c)}</td>`).join("")}</tr>`; + } + out.push(`<div class="nt-table">${h}</tbody></table></div>`); + } else if (RE.item.test(l)) { + const items = []; + while (i < L.length) { + const x = L[i]; + if ((m = x.match(RE.item))) { + items.push({ ind: m[1].replace(/\t/g, " ").length, tag: /\d/.test(m[2]) ? "ol" : "ul", text: m[3] }); + } else if (x.trim() && /^\s/.test(x) && items.length) { + items[items.length - 1].text += "\n" + x.trim(); // a wrapped line of the item above + } else break; + i++; + } + out.push(list(items, st)); + } else { + const p = []; + for (; i < L.length && L[i].trim() && !(p.length && starts(L[i])); i++) p.push(L[i]); + out.push(`<p>${p.map(inline).join("<br>")}</p>`); + } + } + return out.join(""); + } + function list(items, st) { + let h = ""; + const stack = []; + for (const it of items) { + let top = stack[stack.length - 1]; + while (top && it.ind < top.ind) { h += `</li></${stack.pop().tag}>`; top = stack[stack.length - 1]; } + if (top && it.ind === top.ind && top.tag !== it.tag) { h += `</li></${stack.pop().tag}>`; top = stack[stack.length - 1]; } + if (!top || it.ind > top.ind) { h += `<${it.tag}>`; stack.push({ ind: it.ind, tag: it.tag }); } + else h += "</li>"; + const t = it.text.match(/^\[([ xX])\](\s+|$)([\s\S]*)$/); + const body = (s) => s.split("\n").map(inline).join("<br>"); + h += t ? `<li class="task${t[1] !== " " ? " done" : ""}"><input type="checkbox" data-task="${st.task++}"${t[1] !== " " ? " checked" : ""}><span>${body(t[3])}</span>` + : `<li>${body(it.text)}`; + } + while (stack.length) h += `</li></${stack.pop().tag}>`; + return h; + } + /** Tick / untick the n-th checkbox in the text (counted like md: outside code blocks). */ + function toggleTask(src, n) { + const L = src.split("\n"); + let k = 0, fence = null; + for (let i = 0; i < L.length; i++) { + const f = L[i].match(RE.fence); + if (fence) { if (L[i].trim().startsWith(fence)) fence = null; continue; } + if (f) { fence = f[1]; continue; } + const m = L[i].match(/^(\s*(?:>\s*)*(?:[-*+]|\d+[.)])\s+\[)([ xX])(\].*)$/); + if (m && k++ === n) { L[i] = m[1] + (m[2] === " " ? "x" : " ") + m[3]; break; } + } + return L.join("\n"); + } + + // ---- the left column --------------------------------------------------------------------- + const live = () => notes.filter((n) => !n.trashed); + function folderTree() { + const tree = { kids: {}, n: 0 }; + for (const n of live()) { + if (!n.folder) continue; + let t = tree; + for (const part of n.folder.split("/")) { + t = t.kids[part] = t.kids[part] || { kids: {}, n: 0 }; + t.n++; + } + } + return tree; + } + const same = (a, b) => a.kind === b.kind && (a.value ?? null) === (b.value ?? null); + function navItem(f, label, count, extra = "") { + return `<button type="button" class="nt-nv${same(f, S.filter) ? " on" : ""}" data-f='${esc(JSON.stringify(f))}'${extra}>` + + `<span class="nt-nl">${label}</span>${count ? `<span class="nt-nc">${count}</span>` : ""}</button>`; + } + function renderNav() { + const L = live(); + let h = navItem({ kind: "all" }, "All notes", L.length); + const pinned = L.filter((n) => n.pinned).length; + if (pinned) h += navItem({ kind: "pinned" }, "📌 Pinned", pinned); + const copies = L.filter((n) => n.origin).length; + if (copies) h += navItem({ kind: "conflicts" }, "⚠ Conflicted copies", copies); + const tree = folderTree(); + const walk = (t, path, depth) => Object.keys(t.kids).sort((a, b) => a.localeCompare(b)).forEach((k) => { + const p = path ? `${path}/${k}` : k; + h += navItem({ kind: "folder", value: p }, `<span class="nt-fi" style="--d:${depth}">▸</span>${esc(k)}`, t.kids[k].n, + ` data-folder="${esc(p)}"`); + walk(t.kids[k], p, depth + 1); + }); + if (Object.keys(tree.kids).length) { h += `<div class="nt-cap">Folders</div>`; walk(tree, "", 0); } + const tags = {}; + for (const n of L) for (const t of tagsOf(n.body)) tags[t] = (tags[t] || 0) + 1; + const names = Object.keys(tags).sort(); + if (names.length) { + h += `<div class="nt-cap">Tags</div><div class="nt-tags">` + + names.map((t) => `<button type="button" class="nt-tagb${same({ kind: "tag", value: t }, S.filter) ? " on" : ""}" data-f='${esc(JSON.stringify({ kind: "tag", value: t }))}'>#${esc(t)} <span>${tags[t]}</span></button>`).join("") + + `</div>`; + } + const trashed = notes.length - L.length; + h += `<div class="nt-cap"></div>` + navItem({ kind: "trash" }, "🗑 Trash", trashed); + $(".nt-nav").innerHTML = h; + $("#nt-folders").innerHTML = [...new Set(L.map((n) => n.folder).filter(Boolean))].sort() + .map((f) => `<option value="${esc(f)}">`).join(""); + } + function whereLabel() { + const f = S.filter; + return { all: "All notes", pinned: "Pinned", conflicts: "Conflicted copies", trash: "Trash", + folder: f.value, tag: "#" + f.value }[f.kind]; + } + + // ---- the list ---------------------------------------------------------------------------- + function shown() { + const f = S.filter; + let L = f.kind === "trash" ? notes.filter((n) => n.trashed) : live(); + if (f.kind === "pinned") L = L.filter((n) => n.pinned); + if (f.kind === "conflicts") L = L.filter((n) => n.origin); + if (f.kind === "folder") L = L.filter((n) => n.folder === f.value || n.folder.startsWith(f.value + "/")); + if (f.kind === "tag") L = L.filter((n) => tagsOf(n.body).includes(f.value)); + const words = fold(S.q).split(/\s+/).filter(Boolean); + if (words.length) L = L.filter((n) => { const t = fold(n.body + " " + n.folder); return words.every((w) => t.includes(w)); }); + return L.sort((a, b) => (f.kind !== "trash" && b.pinned - a.pinned) || (b.trashed || b.updated).localeCompare(a.trashed || a.updated)); + } + function renderList() { + const L = shown(); + $(".nt-where").textContent = whereLabel(); + $(".nt-new").hidden = S.filter.kind === "trash"; + $(".nt-empty").hidden = S.filter.kind !== "trash" || !L.length; + $(".nt-ren").hidden = S.filter.kind !== "folder"; + const showFolder = S.filter.kind !== "folder"; + $(".nt-items").innerHTML = L.length ? L.map((n) => { + const tags = tagsOf(n.body).slice(0, 4); + return `<button type="button" class="nt-it${S.cur && S.cur.id === n.id ? " on" : ""}" data-id="${n.id}"> + <span class="nt-it1">${n.pinned && S.filter.kind !== "trash" ? '<span class="nt-pinmark">📌</span>' : ""}${n.origin ? '<span class="nt-warn" title="Conflicted copy">⚠</span>' : ""}<b>${esc(titleOf(n.body))}</b><time>${when(n.trashed || n.updated)}</time></span> + <span class="nt-it2">${esc(snippet(n.body, S.q)) || " "}</span> + ${(showFolder && n.folder) || tags.length ? `<span class="nt-it3">${showFolder && n.folder ? `<span class="nt-fold">${esc(n.folder)}</span>` : ""}${tags.map((t) => `<span>#${esc(t)}</span>`).join("")}</span>` : ""} + </button>`; + }).join("") : `<p class="nt-none">${S.q ? "Nothing matches." : S.filter.kind === "trash" ? "The trash is empty." : "No notes here yet."}</p>`; + } + + // ---- the editor -------------------------------------------------------------------------- + const ta = $(".nt-text"), view = $(".nt-view"); + function setState(t, bad) { const e = $(".nt-state"); e.textContent = t; e.classList.toggle("bad", !!bad); } + function open(n, mode) { + flush(); + S.cur = n ? { ...n } : null; + S.dirty = false; + root.dataset.view = n ? "note" : "list"; + $(".nt-ed").hidden = !n; + $(".nt-blank").hidden = !!n; + if (!n) { renderList(); return; } + const trashed = !!n.trashed; + S.mode = trashed ? "view" : mode || (n.body.trim() ? "view" : "edit"); + ta.value = n.body; + ta.readOnly = trashed; + $(".nt-folder").value = n.folder; + $(".nt-folder").disabled = trashed; + $(".nt-pin").hidden = trashed; + $(".nt-pin").classList.toggle("on", !!n.pinned); + $(".nt-del").hidden = trashed; + $(".nt-restore").hidden = $(".nt-purge").hidden = !trashed; + $(".nt-mode").hidden = trashed; + $(".nt-banner").hidden = !n.origin || trashed; + $(".nt-trashed").hidden = !trashed; + setState(n.id ? `Edited ${when(n.updated)}` : "New note"); + showMode(); + renderList(); + } + function showMode() { + const edit = S.mode === "edit"; + root.dataset.mode = S.mode; + ta.hidden = !edit; + view.hidden = edit; + $(".nt-tools").hidden = !edit; + document.querySelectorAll(".nt-mode a").forEach((a) => a.classList.toggle("on", a.dataset.m === S.mode)); + if (edit) ta.focus(); + else view.innerHTML = md(ta.value) || `<p class="nt-none">Empty — switch to Edit to write.</p>`; + } + + function changed() { + if (!S.cur || S.cur.trashed) return; + S.dirty = true; + setState("Editing…"); + clearTimeout(S.timer); + S.timer = setTimeout(flush, 700); + } + /** Save what's typed: the text is taken now (so switching notes can't mix them up), the saves + * run one after another — a promise for when they're all in. */ + function flush() { + clearTimeout(S.timer); + if (S.cur && S.dirty) { + S.dirty = false; + if (S.cur.id || ta.value.trim()) S.queue = { cur: S.cur, body: ta.value }; // an empty new note: nothing to keep + } + if (S.queue && !S.run) S.run = drain().finally(() => { S.run = null; }); + return S.run || Promise.resolve(); + } + async function drain() { + while (S.queue) { + const { cur, body } = S.queue; + S.queue = null; + const data = cur.id ? { id: cur.id, body, base: cur.rev } : { body, folder: cur.folder, pinned: cur.pinned }; + if (S.cur === cur) setState("Saving…"); + try { + const j = await post("/notes/api/save", data); + put(j.note); + // a conflict: the note changed elsewhere meanwhile — what was typed is a copy now, and stays open + Object.assign(cur, { id: j.note.id, rev: j.note.rev, updated: j.note.updated, origin: j.note.origin }); + if (S.cur === cur) { + setState(j.conflict ? "Changed on another device — yours is kept as a copy" : "Saved", j.conflict); + $(".nt-banner").hidden = !cur.origin; + } + if (j.conflict) reload(); // the other version of the original + renderList(); + } catch (x) { + if (S.cur === cur) S.dirty = true; // tried again on the next key / leaving the box + setState(x.message, true); + } + } + } + function put(n) { + const i = notes.findIndex((x) => x.id === n.id); + if (i >= 0) notes[i] = n; else notes.unshift(n); + renderNav(); + } + async function setField(data) { + const cur = S.cur; + if (!cur) return; + if (!cur.id) { Object.assign(cur, data); return; } // a new note: goes with its first save + await flush(); + try { + const j = await post("/notes/api/save", { id: cur.id, ...data }); + put(j.note); + Object.assign(cur, data); + renderList(); + } catch (x) { setState(x.message, true); } + } + + // ---- toolbar: wrap the selection or mark the lines ----------------------------------------- + function wrap(a, b = a, ph = "text") { + const s = ta.selectionStart, e = ta.selectionEnd, sel = ta.value.slice(s, e) || ph; + ta.setRangeText(a + sel + b, s, e, "end"); + ta.setSelectionRange(s + a.length, s + a.length + sel.length); + ta.focus(); + changed(); + } + function lines(fn) { + const v = ta.value, s = v.lastIndexOf("\n", ta.selectionStart - 1) + 1; + let e = v.indexOf("\n", ta.selectionEnd); + if (e < 0) e = v.length; + const block = v.slice(s, e).split("\n").map(fn).join("\n"); + ta.setRangeText(block, s, e, "end"); + ta.focus(); + changed(); + } + const TOOLS = { + h: () => lines((l) => (/^#{1,5}\s/.test(l) ? "#" + l : /^#{6}\s/.test(l) ? l.replace(/^#+\s/, "") : "# " + l)), + b: () => wrap("**"), i: () => wrap("*"), s: () => wrap("~~"), code: () => wrap("`", "`", "code"), + ul: () => lines((l) => (/^\s*[-*+]\s/.test(l) ? l.replace(/^(\s*)[-*+]\s+(\[[ xX]\]\s+)?/, "$1") : "- " + l)), + task: () => lines((l) => (/^\s*[-*+]\s\[[ xX]\]/.test(l) ? l.replace(/^(\s*)[-*+]\s\[[ xX]\]\s?/, "$1") + : l.replace(/^(\s*)(?:[-*+]\s+)?/, "$1- [ ] "))), + quote: () => lines((l) => (/^>\s?/.test(l) ? l.replace(/^>\s?/, "") : "> " + l)), + link: () => wrap("[", "](https://)", "link"), + }; + // Enter in a list item continues the list (an empty item ends it) + ta.addEventListener("keydown", (e) => { + if ((e.ctrlKey || e.metaKey) && e.key === "s") { e.preventDefault(); flush(); return; } + if (e.key === "Escape" && innerWidth < 760) { e.preventDefault(); open(null); return; } + if (e.key !== "Enter" || e.shiftKey || ta.selectionStart !== ta.selectionEnd) return; + const v = ta.value, p = ta.selectionStart, s = v.lastIndexOf("\n", p - 1) + 1; + const m = v.slice(s, p).match(/^(\s*)([-*+]|\d+[.)])(\s+)(\[[ xX]\]\s+)?(.*)$/); + if (!m) return; + e.preventDefault(); + if (!m[5].trim()) { ta.setRangeText("", s, p, "end"); changed(); return; } // empty item: list ends + const num = m[2].match(/^(\d+)([.)])$/); + const mark = num ? `${+num[1] + 1}${num[2]}` : m[2]; + ta.setRangeText(`\n${m[1]}${mark}${m[3]}${m[4] ? "[ ] " : ""}`, p, p, "end"); + changed(); + }); + ta.addEventListener("input", changed); + ta.addEventListener("blur", flush); + + // ---- clicks ------------------------------------------------------------------------------ + root.addEventListener("click", async (e) => { + const t = e.target; + const nv = t.closest("[data-f]"); + if (nv) { + S.filter = JSON.parse(nv.dataset.f); + S.navOpen = false; + root.classList.remove("nav-open"); + renderNav(); + if (S.cur && !shown().some((n) => n.id === S.cur.id)) open(null); else renderList(); + return; + } + const it = t.closest(".nt-it"); + if (it) { open(notes.find((n) => n.id === +it.dataset.id)); return; } + const tag = t.closest(".nt-tag"); + if (tag) { S.filter = { kind: "tag", value: tag.dataset.tag }; renderNav(); renderList(); return; } + const box = t.closest("input[data-task]"); + if (box && S.cur && !S.cur.trashed) { + ta.value = toggleTask(ta.value, +box.dataset.task); + box.closest("li").classList.toggle("done", box.checked); + changed(); + return; + } + const mode = t.closest(".nt-mode a"); + if (mode) { e.preventDefault(); S.mode = mode.dataset.m; showMode(); return; } + const tool = t.closest("[data-tool]"); + if (tool) { TOOLS[tool.dataset.tool](); return; } + if (t.closest(".nt-new")) { + const f = S.filter.kind === "folder" ? S.filter.value : ""; + open({ id: null, body: S.filter.kind === "tag" ? `\n\n#${S.filter.value}` : "", folder: f, + pinned: S.filter.kind === "pinned" ? 1 : 0, rev: null, updated: new Date().toISOString() }, "edit"); + ta.setSelectionRange(0, 0); + return; + } + if (t.closest(".nt-back")) { open(null); return; } + if (t.closest(".nt-where")) { S.navOpen = !S.navOpen; root.classList.toggle("nav-open", S.navOpen); return; } + if (t.closest(".nt-pin")) { setField({ pinned: S.cur.pinned ? 0 : 1 }); t.closest(".nt-pin").classList.toggle("on"); return; } + if (t.closest(".nt-del")) { + if (!S.cur.id) { open(null); return; } + await flush(); + const j = await post("/notes/api/trash", { id: S.cur.id, on: true }); + put(j.note); + open(null); + return; + } + if (t.closest(".nt-restore")) { + const j = await post("/notes/api/trash", { id: S.cur.id, on: false }); + S.filter = { kind: "all" }; // the trash no longer holds it + put(j.note); + open(j.note); + return; + } + const purge = t.closest(".nt-purge"); + if (purge) { // click twice + if (!purge.classList.contains("armed")) { purge.classList.add("armed"); purge.textContent = "Click again to delete"; return; } + await post("/notes/api/delete", { id: S.cur.id }); + notes = notes.filter((n) => n.id !== S.cur.id); + renderNav(); + open(null); + return; + } + const empty = t.closest(".nt-empty"); + if (empty) { + if (!empty.classList.contains("armed")) { empty.classList.add("armed"); empty.textContent = "Click again: delete them all"; return; } + await post("/notes/api/empty-trash", {}); + notes = notes.filter((n) => !n.trashed); + empty.classList.remove("armed"); + empty.textContent = "Empty the trash"; + renderNav(); + open(null); + return; + } + if (t.closest(".nt-keep")) { + const j = await post("/notes/api/keep", { id: S.cur.id }); + put(j.note); + S.cur.origin = null; + $(".nt-banner").hidden = true; + renderList(); + return; + } + const ren = t.closest(".nt-ren"); + if (ren) { renameFolder(); return; } + }); + document.querySelectorAll(".nt-purge, .nt-empty").forEach((b) => b.addEventListener("mouseleave", () => { + b.classList.remove("armed"); + b.textContent = b.classList.contains("nt-purge") ? "Delete for good" : "Empty the trash"; + })); + $(".nt-folder").addEventListener("change", (e) => setField({ folder: e.target.value })); + $(".nt-q").addEventListener("input", (e) => { S.q = e.target.value; renderList(); }); + + // rename the folder you're in: the list heading becomes a text box (Enter saves, Esc cancels) + function renameFolder() { + const old = S.filter.value, h = $(".nt-where"); + const box = document.createElement("input"); + box.className = "nt-renbox"; + box.value = old; + h.replaceWith(box); + box.focus(); + box.select(); + const done = async (save) => { + box.replaceWith(h); + const to = box.value.trim(); + if (!save || !to || to === old) return; + try { + await post("/notes/api/folder", { from: old, to }); + await reload(); + S.filter = { kind: "folder", value: to.split("/").map((p) => p.trim()).filter(Boolean).join("/") }; + renderNav(); + renderList(); + } catch (x) { setState(x.message, true); } + }; + box.addEventListener("keydown", (e) => { if (e.key === "Enter") done(true); if (e.key === "Escape") done(false); }); + box.addEventListener("blur", () => done(true), { once: true }); + } + + // ---- the phone's notes arrive through the Pi's sync: re-read now and then ---------------- + async function reload() { + try { + const r = await fetch("/notes/api/list", { cache: "no-store" }); + notes = (await r.json()).notes; + } catch (x) { return; } + renderNav(); + renderList(); + const cur = S.cur && S.cur.id && notes.find((n) => n.id === S.cur.id); + if (S.cur && S.cur.id && !cur) { open(null); return; } // deleted elsewhere + if (cur && cur.rev !== S.cur.rev && !S.dirty && !S.run) { // changed elsewhere, nothing typed here + const at = ta.selectionStart; + open(cur, S.mode); + ta.setSelectionRange(at, at); + } + } + document.addEventListener("visibilitychange", () => { if (!document.hidden) reload(); }); + setInterval(() => { if (!document.hidden && !S.dirty) reload(); }, 60000); + addEventListener("beforeunload", (e) => { if (S.dirty || S.run) { flush(); e.preventDefault(); } }); + + renderNav(); + open(null); +})(); diff --git a/dashboard/plugins/notes/templates/notes/index.html b/dashboard/plugins/notes/templates/notes/index.html new file mode 100644 index 0000000..41fb68f --- /dev/null +++ b/dashboard/plugins/notes/templates/notes/index.html @@ -0,0 +1,69 @@ +{% extends "base.html" %} +{% from "_header.html" import nav_btns, settings_btn, title_block %} +{% block title %}Notes{% endblock %} +{% block head %}<link rel="stylesheet" href="{{ url_for('notes.static', filename='notes.css') }}?v={{ asset_v }}">{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{# Three columns: where (search, folders, tags) | the notes there | the note. notes.js draws the + first two from #nt-data and keeps them up to date; narrow windows show one column at a time. #} +{% block page %} +<header class="head nt-head"> + {{ nav_btns() }} + {{ title_block("Notes", "/notes") }} + {{ settings_btn() }} +</header> + +<div class="nt" data-view="list" data-mode="view"> + <aside class="nt-side"> + <input type="search" class="nt-q" placeholder="Search notes" aria-label="Search notes"> + <nav class="nt-nav"></nav> + <a class="nt-export" href="/notes/export.zip" title="Every note as a .md file, in its folders">Export all (.zip)</a> + </aside> + + <section class="nt-list"> + <div class="nt-lh"> + <button type="button" class="nt-where" title="Folders and tags">All notes</button> + <button type="button" class="nt-ren" title="Rename this folder" hidden>✎</button> + <button type="button" class="nt-new">+ New</button> + <button type="button" class="nt-empty" hidden>Empty the trash</button> + </div> + <div class="nt-items"></div> + </section> + + <section class="nt-ed" hidden> + <div class="nt-bar"> + <button type="button" class="nt-back" title="Back to the list" aria-label="Back">‹</button> + <nav class="nt-mode"><a href="#" data-m="edit">Edit</a><a href="#" data-m="view">Preview</a></nav> + <span class="nt-tools" hidden> + <button type="button" data-tool="h" title="Heading (again: smaller)"><b>H</b></button> + <button type="button" data-tool="b" title="Bold"><b>B</b></button> + <button type="button" data-tool="i" title="Italic"><i>I</i></button> + <button type="button" data-tool="s" title="Strikethrough"><s>S</s></button> + <button type="button" data-tool="ul" title="List">•</button> + <button type="button" data-tool="task" title="Checklist">☐</button> + <button type="button" data-tool="quote" title="Quote">❝</button> + <button type="button" data-tool="code" title="Code"></></button> + <button type="button" data-tool="link" title="Link">🔗</button> + </span> + <span class="nt-gap"></span> + <input class="nt-folder" list="nt-folders" placeholder="No folder" title="Folder (a/b for a sub-folder)" aria-label="Folder"> + <button type="button" class="nt-pin" title="Pin to the top">📌</button> + <button type="button" class="nt-del" title="Move to the trash">🗑</button> + <button type="button" class="nt-restore" hidden>Restore</button> + <button type="button" class="nt-purge" hidden>Delete for good</button> + </div> + <div class="nt-banner" hidden> + <b>⚠ Conflicted copy.</b> This note was changed on two devices at once; this is the version that + didn't win — the other one kept the original. Take what you need from it, then + <button type="button" class="nt-keep">keep it as a normal note</button> or move it to the trash. + </div> + <div class="nt-trashed" hidden>In the trash — restore it to edit.</div> + <textarea class="nt-text" spellcheck="true" placeholder="Write in markdown: # heading, **bold**, - [ ] a task, #tag …" hidden></textarea> + <article class="nt-view md"></article> + <div class="nt-foot"><span class="nt-state"></span></div> + </section> + <div class="nt-blank"><p>Pick a note, or <b>+ New</b>.</p></div> +</div> +<datalist id="nt-folders"></datalist> +<script type="application/json" id="nt-data">{{ notes | tojson }}</script> +{% endblock %} +{% block scripts %}<script src="{{ url_for('notes.static', filename='notes.js') }}?v={{ asset_v }}"></script>{% endblock %} diff --git a/dashboard/plugins/stations/__init__.py b/dashboard/plugins/stations/__init__.py new file mode 100644 index 0000000..f4c3ab2 --- /dev/null +++ b/dashboard/plugins/stations/__init__.py @@ -0,0 +1,184 @@ +"""Measurement stations (built in): temperature + humidity from the sources of Settings ▸ Sensors +(sources.py: termix, a JSON URL, Home Assistant, MQTT, a DS18B20 on the Pi — polled every 30 s, +sensors.py), kept as 5-minute rows in dash_data/stations/readings.db (db.py) so they can be +graphed over any time. + + /stations a card per sensor: now, lowest / highest, the graph (?r=1d|7d|30d|1y) + +Also the Home's stations row and main temperature (regions "stations", "main"), +the outdoor readings in the weather box (provide("outdoor") → the weather plugin asks), +the 3.5" Temp screen (grid → a sensor's 24 h graph) and the 3.5" Home's indoor corner. +The sensor slots (Store.sources: the indoor sensors; Store.outdoor; Store.main: the big one on Home) +are built by sensors.build_slots from the config, again whenever it changes (no restart); the +24 h in-memory history (dash_history.json) still feeds the 3.5" graph and seeds an empty +readings.db. Settings ▸ Sensors is one of the Settings page's own panes (settings_tab), filled +by static/sensors.js from /stations/api/… (admin only). +""" +import time +from contextlib import closing + +from flask import abort, jsonify, render_template, request + +import auth + +from . import db, screens, sensors, sources, views + +META = { + "title": "Measurement stations", + "glyph": "🌡", + "glyph_color": "#5cc8ff", + "glyph_svg": {"viewBox": "-12 -12 24 24", + "d": "M-2.5 -10 A2.5 2.5 0 0 1 2.5 -10 V2.2 A5 5 0 1 1 -2.5 2.2 Z M-1 -9 V3.4 A3.6 3.6 0 1 0 1 3.4 V-9 Z"}, + "description": "Temperature and humidity from your sensors (Home Assistant, MQTT, a JSON URL, a DS18B20 on the Pi, " + "termix): the Home boxes, the 3.5\" Temp screen, and a page with each sensor's graphs (kept from now on).", + "default_on": True, + "settings_tab": "sensors", + "links": [{"label": "Open", "href": "/stations"}], + "sync": {"readings.db": db.PHONE_SYNC}, # the phone app's Weather ▸ stations — written here only +} +SAMPLE_EVERY = 60 # s +FRESH = 900 # s: older readings (a sensor offline) aren't kept + + +def register(ctx): + store = ctx.store + store.sources, store.outdoor = [], [] + sensors.build_slots(store, sources.config(store.cfg)) + sensors.load_history(store) # the 24 h history, before the poller writes + path = ctx.data_path("readings.db") + acc = {"bucket": None, "samples": {}} + + def flush(): + b, samples = acc["bucket"], acc["samples"] + rows = [] + for did, xs in samples.items(): + ts = [t for t, _ in xs if t is not None] + hs = [h for _, h in xs if h is not None] + if ts or hs: + rows.append((did, b, sum(ts) / len(ts) if ts else None, min(ts) if ts else None, + max(ts) if ts else None, sum(hs) / len(hs) if hs else None, len(xs))) + if rows: + with closing(db.connect(path)) as con: + db.store_buckets(con, rows) + acc["samples"] = {} + + def slots(): + return [(s, "indoor") for s in store.sources if s.device_id is not None] + [(s, "outdoor") for s in store.outdoor] + + def seed(): # an empty readings.db: start from the 24 h history + with closing(db.connect(path)) as con: + if not db.empty(con): + return + rows = [] + for s, _ in slots(): + by = {} + for ts, t in list(s.hist): + by.setdefault(int(ts // db.BUCKET * db.BUCKET), []).append(t) + rows += [(s.device_id, b, sum(v) / len(v), min(v), max(v), None, len(v)) for b, v in by.items()] + if rows: + db.store_buckets(con, rows) + + with closing(db.connect(path)): # the tables exist before the sync stamps them + pass + + def sampler(_ctx): + """One sample a minute of every sensor's live values; a 5-minute row each per bucket; for the + phone: the complete hours and, every PHONE_NOW seconds, the latest values (db.phone_*).""" + seed() + named = 0 + phoned = time.time() - db.PHONE_NOW + 120 # the first "now" rows after the sensors' first polls + while True: + now = time.time() + b = int(now // db.BUCKET * db.BUCKET) + if acc["bucket"] is not None and b != acc["bucket"]: + flush() + acc["bucket"] = b + with store.lock: + live = [(s.device_id, s.name, kind, s.t, s.h, s.age_s) for s, kind in slots()] + for did, _, _, t, h, age in live: + if (t is not None or h is not None) and (age is None or age < FRESH): + acc["samples"].setdefault(did, []).append((t, h)) + if now - named > 3600: # names / kinds now and then + with closing(db.connect(path)) as con: + db.set_devices(con, [(did, name, kind) for did, name, kind, *_ in live]) + named = now + if now - phoned >= db.PHONE_NOW and ctx.primary(): # the other dashboard gets them synced + try: + with closing(db.connect(path)) as con: + db.phone_hours(con) + db.phone_now(con, [(did, name, kind, t, h, age) for did, name, kind, t, h, age in live + if age is None or age < FRESH]) + except Exception as e: + print(f"stations: phone rows failed: {e}", flush=True) + phoned = now + time.sleep(SAMPLE_EVERY) + + ctx.worker(lambda c: sensors.sensors_worker(store)) + ctx.worker(sampler) + ctx.on_exit(lambda: (sensors.save_history(store), flush() if acc["bucket"] else None)) + + def outdoor(): + return [views._reading(s, store.units) for s in store.outdoor[:3]] + ctx.provide("outdoor", outdoor) + ctx.provide("status", lambda: store.sensors_status) + + ctx.home("stations", lambda: render_template("stations/_home_row.html", rows=views._stations(store))) + ctx.home("main", lambda: render_template("stations/_home_main.html", m=views._main_temp(store)) + if store.main is not None and store.main.device_id is not None else "") + ctx.screen("Temp", screens.icon, screens.screen, key=lambda ch: screens.key(store, ch), + on_open=lambda: setattr(store, "temp_tab", -1), stay=lambda: store.temp_tab == -1, order=10) # the grid stays + ctx.home_screen("indoor", screens.home_indoor) + + bp = ctx.blueprint("/stations") + ctx.nav("Stations", "/stations") + ctx.inside("weather") # a tab of Weather, like Cycle / Food in Health + + @bp.route("/", strict_slashes=False) + def page(): + rng = request.args.get("r", "1d") + rng = rng if rng in db.RANGES else "1d" + now = int(time.time()) + with closing(db.connect(path)) as con: + devs = db.devices(con) + live = {s.device_id: s for s, _ in slots()} + v = views.page(store, devs, lambda did: db.series(con, did, rng, now), rng, now, live) + return render_template("stations/page.html", v=v, page="stations") + + # ---- Settings ▸ Sensors (static/sensors.js) — admin only + def admin_body(): + if not auth.is_admin(): + abort(403) + if request.method == "POST" and not ctx.same_origin(): + abort(403) + return request.get_json(silent=True) or {} + + @bp.route("/api/config") + def api_config(): + admin_body() + conf = sources.config(store.cfg) + with store.lock: + live = {s.device_id: {"t": s.t, "h": s.h, "name": s.name} for s in list(store.sources) + list(store.outdoor)} + return jsonify(types=sources.types_view(), status=dict(sensors.source_status), live=live, **sources.public(conf)) + + @bp.route("/api/test", methods=["POST"]) + def api_test(): + d = admin_body() + src = sources.with_secrets(d.get("source") or {}, sources.config(store.cfg)) + try: + return jsonify(found=sources.discover(src)) + except sources.SourceError as e: + return jsonify(error=str(e)), 400 + except Exception as e: + return jsonify(error=f"{type(e).__name__}: {e}"), 400 + + @bp.route("/api/save", methods=["POST"]) + def api_save(): + d = admin_body() + import settings + try: + conf = sources.clean(d, sources.config(store.cfg)) + except ValueError as e: + return jsonify(error=str(e)), 400 + settings.save_part(store, "sensors", conf) + sensors.wake.set() + return jsonify(ok=True, **sources.public(conf)) diff --git a/dashboard/plugins/stations/db.py b/dashboard/plugins/stations/db.py new file mode 100644 index 0000000..ca0c03d --- /dev/null +++ b/dashboard/plugins/stations/db.py @@ -0,0 +1,138 @@ +"""The stations' readings, kept: dash_data/stations/readings.db. + +The termix API answers with the latest values only, so the plugin keeps its own history: +every BUCKET seconds one row per sensor — the average, lowest and highest temperature and +the average humidity of the samples taken in that time (one a minute, sampler in +__init__.py). Rows are never thrown away (≈ 105 000 a year per sensor). `device` remembers +each sensor's name and whether it's indoor (Store.sources) or outdoor (Store.outdoor). +""" +import os +import sqlite3 +import time + +BUCKET = 300 # s +SCHEMA = """ +CREATE TABLE IF NOT EXISTS reading ( + device_id INTEGER NOT NULL, + t INTEGER NOT NULL, -- the bucket's start (UTC epoch seconds) + temp REAL, temp_min REAL, temp_max REAL, -- °C + hum REAL, -- % + n INTEGER NOT NULL, -- samples averaged + PRIMARY KEY (device_id, t) +); +CREATE TABLE IF NOT EXISTS device ( + device_id INTEGER PRIMARY KEY, + name TEXT NOT NULL DEFAULT '', + kind TEXT NOT NULL DEFAULT 'indoor', -- indoor / outdoor + updated INTEGER +);-- for the phone app (synced one way, META "sync"): the hours (written once each is complete) + each +-- sensor's latest values (every PHONE_NOW seconds) — the 5-minute rows stay here +CREATE TABLE IF NOT EXISTS hourly ( + device_id INTEGER NOT NULL, + t INTEGER NOT NULL, -- the hour's start (UTC epoch seconds) + temp REAL, temp_min REAL, temp_max REAL, hum REAL, + PRIMARY KEY (device_id, t) +); +CREATE TABLE IF NOT EXISTS now ( + device_id INTEGER PRIMARY KEY, + name TEXT NOT NULL DEFAULT '', + kind TEXT NOT NULL DEFAULT 'indoor', + t INTEGER, -- when measured (UTC epoch seconds) + temp REAL, hum REAL +); +""" +# a graph's range → (seconds, bucket of the points shown) +RANGES = {"1d": (86400, BUCKET), "7d": (7 * 86400, 1800), "30d": (30 * 86400, 7200), "1y": (365 * 86400, 86400)} + + +PHONE_NOW = 900 # s between the phone's "now" rows +PHONE_SYNC = { # META["sync"]["readings.db"] + "hourly": {"key": "'h:' || NEW.device_id || ':' || NEW.t"}, + "now": {"key": "'now:' || NEW.device_id"}, +} + + +def connect(path): + os.makedirs(os.path.dirname(path) or ".", exist_ok=True) + con = sqlite3.connect(path, timeout=10) + con.execute("PRAGMA journal_mode=WAL") + con.executescript(SCHEMA) + os.chmod(path, 0o600) + return con + + +def store_buckets(con, rows): + """rows = [(device_id, t, temp, temp_min, temp_max, hum, n)] — a bucket written twice + (a restart inside it) keeps the larger sample.""" + con.executemany("INSERT INTO reading VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(device_id, t) DO UPDATE SET " + "temp=excluded.temp, temp_min=excluded.temp_min, temp_max=excluded.temp_max, hum=excluded.hum, " + "n=excluded.n WHERE excluded.n >= reading.n", rows) + con.commit() + + +def set_devices(con, devices): + """devices = [(device_id, name, kind)].""" + now = int(time.time()) + con.executemany("INSERT INTO device VALUES (?, ?, ?, ?) ON CONFLICT(device_id) DO UPDATE SET " + "name=CASE WHEN excluded.name != '' THEN excluded.name ELSE device.name END, kind=excluded.kind, " + "updated=excluded.updated", [(d, n or "", k, now) for d, n, k in devices]) + con.commit() + + +def devices(con): + return [{"id": r[0], "name": r[1], "kind": r[2]} for r in con.execute( + "SELECT device_id, name, kind FROM device ORDER BY kind DESC, device_id")] + + +def series(con, device_id, rng, now=None): + """Points of one sensor for a range: [(t, temp avg, temp min, temp max, hum avg)], + one per the range's bucket, oldest first.""" + span, step = RANGES[rng] + now = now or int(time.time()) + return con.execute( + "SELECT (t / ?) * ?, AVG(temp), MIN(temp_min), MAX(temp_max), AVG(hum) FROM reading " + "WHERE device_id = ? AND t >= ? GROUP BY t / ? ORDER BY 1", + (step, step, device_id, now - span, step)).fetchall() + + +def first_t(con): + r = con.execute("SELECT MIN(t) FROM reading").fetchone() + return r[0] + + +def empty(con): + return con.execute("SELECT 1 FROM reading LIMIT 1").fetchone() is None + + +def phone_hours(con, since=None): + """The complete hours since `since` (default: the last one written, else everything) → hourly; + only rows whose numbers changed are written (the sync sends what's written).""" + if since is None: + since = (con.execute("SELECT max(t) FROM hourly").fetchone()[0] or 0) + top = int(time.time()) // 3600 * 3600 # the hour going on isn't complete + rows = con.execute("SELECT device_id, t / 3600 * 3600 AS h, round(sum(temp * n) / sum(n), 2), min(temp_min), max(temp_max), " + "round(avg(hum), 1) FROM reading WHERE t >= ? AND t < ? AND temp IS NOT NULL GROUP BY device_id, h", + (since, top)).fetchall() + n = 0 + for r in rows: + old = con.execute("SELECT temp, temp_min, temp_max, hum FROM hourly WHERE device_id = ? AND t = ?", r[:2]).fetchone() + if old is None or tuple(old) != tuple(r[2:]): + con.execute("INSERT OR REPLACE INTO hourly (device_id, t, temp, temp_min, temp_max, hum) VALUES (?, ?, ?, ?, ?, ?)", r) + n += 1 + con.commit() + return n + + +def phone_now(con, live): + """live = [(device_id, name, kind, temp, hum, age_s)] → now (only what changed).""" + t = int(time.time()) + for did, name, kind, temp, hum, age in live: + if temp is None and hum is None: + continue + r = (round(temp, 1) if temp is not None else None, round(hum) if hum is not None else None) + old = con.execute("SELECT name, kind, temp, hum FROM now WHERE device_id = ?", (did,)).fetchone() + if old is not None and tuple(old) == (name or "", kind, *r): + continue + con.execute("INSERT OR REPLACE INTO now (device_id, name, kind, t, temp, hum) VALUES (?, ?, ?, ?, ?, ?)", + (did, name or "", kind, t - int(age or 0), *r)) + con.commit() diff --git a/dashboard/plugins/stations/screens.py b/dashboard/plugins/stations/screens.py new file mode 100644 index 0000000..4ef3a9d --- /dev/null +++ b/dashboard/plugins/stations/screens.py @@ -0,0 +1,125 @@ +"""The stations on the 3.5" panel: the Temp screen (a grid of sensor cards, tap one for its +24 h graph) and the 3.5" Home's bottom-right corner (the main temperature) — moved +from the core's screens.py.""" +from config import NAV_H, THEME +from panel import disp_temp, draw_graph, fit_text, ic_home, ic_thermo, temp_colour, text_r +from store import hit + +icon = ic_thermo +INDOOR_LAST_Y = 220 # the humidity shares the 3.5" Home agenda's last row baseline + + +def home_indoor(img, d, panel, store): + """The main sensor (store.main, Settings ▸ Sensors): label / temperature / humidity, right-aligned.""" + house = store.main + if house is None: + return + rx = panel.w - 16 + name = house.name or "—" + nx = rx - d.textlength(name, font=panel.f["sm"]) + d.text((nx, 166), name, font=panel.f["sm"], fill=THEME["muted"]) + ic_home(d, nx - 14, 174, 9, THEME["accent"] if house.t is not None else THEME["dim"]) + if house.t is not None: + ht, hu = disp_temp(house.t, store.units) + text_r(d, rx, 184, f"{ht:.1f}{hu}", panel.f["lg"], temp_colour(house.t)) + if house.h is not None: + text_r(d, rx, INDOOR_LAST_Y, f"{house.h:.0f}%", panel.f["sm"], THEME["cool"]) + else: + text_r(d, rx, 184, "—", panel.f["lg"], THEME["dim"]) + + +def key(store, ch): + """← back to the grid, → the next sensor's detail.""" + if ch == "right" and store.temp_tab >= 0 and store.sources: + store.temp_tab = (store.temp_tab + 1) % len(store.sources) + elif ch == "left": + store.temp_tab = -1 + + +def screen(img, d, panel, store): + """Dispatcher: grid landing, or detail view of one sensor.""" + if 0 <= store.temp_tab < len(store.sources): + _temp_detail(img, d, panel, store) + else: + _temp_grid(img, d, panel, store) + + +def _temp_grid(img, d, panel, store): + """Grid of sensor cards (label on top, temp + humidity side-by-side). Tap to drill in. + + Fixed 2 columns; cell height sized so 3-4 rows fit in the visible area — + handles up to 6 sensors today, room to add scrolling if the count grows. + """ + srcs = store.sources + margin, gap = 16, 12 + cols = 2 + cell_w = (panel.w - 2 * margin - gap * (cols - 1)) // cols # 218 px + cell_h = 68 # 3 rows fit cleanly + y_top = 12 + + for i, src in enumerate(srcs): + r, c = divmod(i, cols) + x0 = margin + c * (cell_w + gap) + y0 = y_top + r * (cell_h + gap) + x1, y1 = x0 + cell_w, y0 + cell_h + + d.rounded_rectangle([x0, y0, x1, y1], radius=10, fill=THEME["card"]) + name = fit_text(d, src.name or f"#{src.device_id}", + panel.f["sm"], cell_w - 24) + d.text((x0 + 12, y0 + 8), name, font=panel.f["sm"], fill=THEME["muted"]) + + if src.t is not None: + t, u = disp_temp(src.t, store.units) + temp_s = f"{t:.1f}{u}" + d.text((x0 + 12, y0 + 28), temp_s, font=panel.f["lg"], fill=THEME["warm"]) + if src.h is not None: + tw = d.textlength(temp_s, font=panel.f["lg"]) + d.text((x0 + 12 + tw + 14, y0 + 42), f"{src.h:.0f}%", + font=panel.f["sm"], fill=THEME["cool"]) + else: + d.text((x0 + 12, y0 + 28), "—", font=panel.f["lg"], fill=THEME["dim"]) + + hit(store, (x0, y0, x1, y1), lambda i=i: setattr(store, "temp_tab", i)) + + +def _temp_detail(img, d, panel, store): + """Drill-in: back button (with sensor name), current values, 24 h graph.""" + s = store.sources[store.temp_tab] + + # The xl temperature anchors the top bar (top y=8, bottom y≈62). + # The back button is shorter (44) and vertically centered against it. + top_y, top_h, bh = 8, 54, 44 + by = top_y + (top_h - bh) // 2 + + raw_label = "‹ " + (s.name or f"#{s.device_id}") + label = fit_text(d, raw_label, panel.f["md"], 180 - 24) + text_w = d.textlength(label, font=panel.f["md"]) + bx = 16 + bw = int(text_w + 24) + d.rounded_rectangle([bx, by, bx + bw, by + bh], radius=8, fill=THEME["card"]) + # anchor="lm" centres on rendered-glyph middle, not bbox top — avoids the + # "more gray above than below" look from PIL's default top-of-bbox y origin. + d.text((bx + 12, by + bh // 2), label, + font=panel.f["md"], fill=THEME["fg"], anchor="lm") + hit(store, (bx, by, bx + bw, by + bh), + lambda: setattr(store, "temp_tab", -1)) + + # Big temp + humidity (right of the back button — same layout as before). + val_x = bx + bw + 16 + if s.t is not None: + t, u = disp_temp(s.t, store.units) + temp_s = f"{t:.1f}{u}" + d.text((val_x, top_y), temp_s, font=panel.f["xl"], fill=THEME["warm"]) + tw = d.textlength(temp_s, font=panel.f["xl"]) + if s.h is not None: + d.text((val_x + tw + 16, top_y + 32), f"{s.h:.0f}%", + font=panel.f["md"], fill=THEME["cool"]) + else: + d.text((val_x, top_y), "—", font=panel.f["xl"], fill=THEME["dim"]) + d.text((val_x, top_y + 36), store.sensors_status, + font=panel.f["sm"], fill=THEME["dim"]) + + # 24 h rolling graph fills the rest of the screen + vals = [t for _ts, t in s.hist] + draw_graph(d, panel, (16, 76, panel.w - 16, panel.h - NAV_H - 8), + vals, store.units) diff --git a/dashboard/plugins/stations/sensors.py b/dashboard/plugins/stations/sensors.py new file mode 100644 index 0000000..59aaa89 --- /dev/null +++ b/dashboard/plugins/stations/sensors.py @@ -0,0 +1,123 @@ +"""The sensor poller: every POLL_INTERVAL_S asks each source of Settings ▸ Sensors (sources.py: termix, a +JSON URL, Home Assistant, MQTT, 1-wire) and writes the latest temperature + humidity into the sensor slots +(Store.sources = the indoor ones; Store.outdoor = up to 3 outdoor ones; Store.main = the big one on Home). A change in +Settings is picked up at the next poll (or at once: `wake`) — the slots are rebuilt, each sensor keeping its +24 h history. + +Keeps a rolling 24 h history per sensor persisted to `dash_history.json` +so the graph survives a restart (saved every 10 polls ≈ 5 min, plus +once more on graceful shutdown from `dash.main()`'s `finally`). On load, +anything older than 24 h is dropped. +""" +import json +import os +import threading +import time +from datetime import datetime + +from config import HISTORY_FILE +from store import HISTORY_MAXLEN, POLL_INTERVAL_S, TempSource + +from . import sources + +SAVE_EVERY_N_POLLS = 10 # ~5 min at 30 s polls +HISTORY_MAX_AGE_S = 24 * 3600 # discard older points on load +wake = threading.Event() # Settings ▸ Sensors saved: poll now +source_status = {} # source id → "ok · 14:05" / what went wrong + + +def build_slots(store, conf): + """Store.sources / Store.outdoor from the config, keeping the TempSource (its history) of each sensor id.""" + with store.lock: + old = {s.device_id: s for s in list(store.sources) + list(store.outdoor) if s.device_id is not None} + made, by_id = {}, {} + for x in conf.get("list") or []: + if x["place"] == "hidden": + continue + src = old.get(x["id"]) or TempSource(device_id=x["id"]) + src.fixed_name = x.get("name") or "" + if src.fixed_name: + src.name = src.fixed_name + made.setdefault(x["place"], []).append(src) + by_id[x["id"]] = src + store.sources = made.get("indoor") or [TempSource(name="(no sensors)")] + store.outdoor = (made.get("outdoor") or [])[:sources.MAX_OUTDOOR] + store.main = by_id.get(sources.main_id(conf)) or store.sources[0] + + +def sensors_worker(store): + """Poll every source; rebuild the slots when Settings ▸ Sensors changed.""" + built, poll_n = None, 0 + while True: + conf = sources.config(store.cfg) + key = json.dumps(conf, sort_keys=True) + if key != built: + build_slots(store, conf) + built = key + if not conf.get("list"): + store.sensors_status = "not configured — Settings ▸ Sensors" + else: + readings, status = sources.read_all(conf) + source_status.clear() + source_status.update(status) + with store.lock: + for s in list(store.sources) + list(store.outdoor): + if s.device_id is None: + continue + r = readings.get(s.device_id) + if r is None: + s.update(None, None, None, None) # offline + else: + s.update(getattr(s, "fixed_name", "") or r["name"], r["t"], r["h"], r["age"]) + bad = [v for v in status.values() if not v.startswith("ok")] + store.sensors_status = ("ok · " + datetime.now().strftime("%H:%M")) if not bad else \ + (bad[0] if len(status) == 1 else f"{len(status) - len(bad)} of {len(status)} sources ok — {bad[0]}") + poll_n += 1 + if poll_n % SAVE_EVERY_N_POLLS == 0: + save_history(store) + wake.wait(POLL_INTERVAL_S) + wake.clear() + + +def load_history(store): + """Restore each source's 24 h deque from disk; silent no-op if missing/corrupt.""" + if not os.path.exists(HISTORY_FILE): + return + try: + with open(HISTORY_FILE) as f: + data = json.load(f) + except Exception: + return + cutoff = time.time() - HISTORY_MAX_AGE_S + by_did = {entry["device_id"]: entry for entry in data.get("sources", []) + if entry.get("device_id") is not None} + for src in list(store.sources) + list(store.outdoor): + entry = by_did.get(src.device_id) + if not entry: + continue + if entry.get("name") and not getattr(src, "fixed_name", ""): + src.name = entry["name"] + for ts, t in entry.get("hist", [])[-HISTORY_MAXLEN:]: + if ts >= cutoff: + src.hist.append((ts, t)) + + +def save_history(store): + """Snapshot current 24 h history to disk; called periodically + on shutdown.""" + try: + with store.lock: + payload = { + "saved_at": time.time(), + "sources": [ + {"device_id": src.device_id, "name": src.name, + "hist": list(src.hist)} + for src in list(store.sources) + list(store.outdoor) + if src.device_id is not None + ], + } + tmp = HISTORY_FILE + ".tmp" + with open(tmp, "w") as f: + json.dump(payload, f) + os.replace(tmp, HISTORY_FILE) # atomic swap + except Exception: + pass diff --git a/dashboard/plugins/stations/sources.py b/dashboard/plugins/stations/sources.py new file mode 100644 index 0000000..32eb421 --- /dev/null +++ b/dashboard/plugins/stations/sources.py @@ -0,0 +1,526 @@ +"""Where the readings come from: Settings ▸ Sensors (dash_config.json "sensors"): + + "sensors": { + "sources": [{"id": "s1", "type": "termix", "url": "…", "api_key": "…", "ids": "2, 3"}, …], + "list": [{"id": 2, "source": "s1", "temp": "2", "hum": null, "name": "", "place": "indoor"}, …] + } + +A source is one place to ask (a type below + its fields); a sensor is one thing shown: its source, the +reference of its temperature there (`temp`) and, if it's elsewhere, of its humidity (`hum`), a name (empty = +the source's), and where it goes — "indoor" (the Home boxes; the first is the big main temperature), +"outdoor" (next to the weather, up to 3) or "hidden" (kept, not shown). `id` is the integer the readings are +kept under (readings.db, the phone app) — termix sensors keep their termix id; others get one from 1000 up. + +Every type answers `read(src, refs)` → {ref: {"t": °C, "h": %, "age": s or None, "name": …}} for the refs +asked, and `discover(src)` → [{"ref", "name", "t", "h"}] for the picker (Settings ▸ Sensors ▸ Test). +""" +import glob +import json +import os +import threading +import time +import urllib.parse +import urllib.request + +TIMEOUT = 10 +FIRST_ID = 1000 # ids of sensors that aren't termix devices +PLACES = ("indoor", "outdoor", "hidden") +MAX_OUTDOOR = 3 + + +class SourceError(Exception): + pass + + +def _get_json(url, headers=None): + req = urllib.request.Request(url, headers={"Accept": "application/json", **(headers or {})}) + try: + with urllib.request.urlopen(req, timeout=TIMEOUT) as r: + return json.load(r) + except urllib.error.HTTPError as e: + raise SourceError(f"HTTP {e.code}") from None + except urllib.error.URLError as e: + raise SourceError(f"can't reach it ({e.reason})") from None + except ValueError: + raise SourceError("the answer isn't JSON") from None + + +def _num(v): + try: + f = float(v) + except (TypeError, ValueError): + return None + return f if f == f and abs(f) < 1e6 else None # not NaN, not absurd + + +def _celsius(v, unit): + v = _num(v) + if v is None: + return None + return round((v - 32) * 5 / 9, 2) if unit in ("°F", "F", "fahrenheit") else v + + +# ---- termix (stm32.php): {"devices": [{"id", "name", "items": [{"code": "1"|"2", "value", "age_s"}]}]} --------- + +def termix_read(src, refs): + ids = sorted({r for r in refs if str(r).isdigit()} | {i.strip() for i in str(src.get("ids") or "").split(",") if i.strip().isdigit()}) + if not ids: + return {} + qs = urllib.parse.urlencode({"key": src.get("api_key") or "", "devices": ",".join(ids)}) + data = _get_json(f"{src.get('url')}?{qs}") + out = {} + for dev in data.get("devices") or []: + items = {str(it.get("code")): it for it in dev.get("items") or []} + t, h = items.get("1") or {}, items.get("2") or {} + out[str(dev.get("id"))] = {"t": _num(t.get("value")), "h": _num(h.get("value")), + "age": (t or h).get("age_s"), "name": dev.get("name") or ""} + return out + + +def termix_discover(src): + return [{"ref": k, **v} for k, v in termix_read(src, []).items()] + + +# ---- any JSON URL: the values by their path in the answer ("sensors.0.temp", "temperature") ------------- + +def _walk(j, path=""): + if isinstance(j, dict): + for k, v in j.items(): + yield from _walk(v, f"{path}.{k}" if path else str(k)) + elif isinstance(j, list): + for i, v in enumerate(j[:50]): + yield from _walk(v, f"{path}.{i}" if path else str(i)) + elif _num(j) is not None and not isinstance(j, bool): + yield path, _num(j) + + +def _at(j, path): + for k in str(path).split("."): + if isinstance(j, list) and k.isdigit() and int(k) < len(j): + j = j[int(k)] + elif isinstance(j, dict) and k in j: + j = j[k] + else: + return None + return j + + +def _json_headers(src): + h = (src.get("header") or "").strip() + return {h.split(":", 1)[0].strip(): h.split(":", 1)[1].strip()} if ":" in h else {} + + +GENERIC_KEYS = {"t", "temp", "temperature", "tc", "h", "hum", "humidity", "rh", "value", "val", "state", "v"} + + +def _json_name(ref): + """A sensor's default name from its JSON path: "living.t" → "living", "sensors.0.temperature" → "sensors 0".""" + parts = [p for p in ref.split(".") if p] + while len(parts) > 1 and parts[-1].lower() in GENERIC_KEYS: + parts.pop() + return " ".join(parts[-2:]) if parts and parts[-1].isdigit() else (parts[-1] if parts else ref) + + +def json_read(src, refs): + j = _get_json(src.get("url"), _json_headers(src)) + unit = "°F" if src.get("fahrenheit") else "°C" + out = {} + for r in refs: + v = _at(j, r) + out[r] = {"t": _celsius(v, unit), "h": _num(v), "age": None, "name": _json_name(r)} + return out + + +def json_discover(src): + j = _get_json(src.get("url"), _json_headers(src)) + return [{"ref": p, "label": p, "name": _json_name(p), "t": v, "h": v} for p, v in list(_walk(j))[:200]] + + +# ---- Home Assistant: entities' states (GET /api/states, a long-lived token) -------------------------------- + +def _ha_states(src): + url = (src.get("url") or "").rstrip("/") + return _get_json(f"{url}/api/states", {"Authorization": f"Bearer {src.get('token') or ''}"}) + + +def _ha_one(e): + a = e.get("attributes") or {} + unit = a.get("unit_of_measurement") + v = e.get("state") + return {"t": _celsius(v, unit) if unit in ("°C", "°F") else None, "h": _num(v) if unit == "%" else None, + "age": None, "name": a.get("friendly_name") or e.get("entity_id"), "unit": unit, + "class": a.get("device_class")} + + +def ha_read(src, refs): + by = {e.get("entity_id"): e for e in _ha_states(src) if isinstance(e, dict)} + return {r: _ha_one(by[r]) for r in refs if r in by} + + +def ha_discover(src): + out = [] + for e in _ha_states(src): + if not isinstance(e, dict): + continue + one = _ha_one(e) + if one["class"] in ("temperature", "humidity") or one["unit"] in ("°C", "°F", "%") and one["class"] is None: + out.append({"ref": e.get("entity_id"), "name": one["name"], "t": one["t"], "h": one["h"]}) + return sorted(out, key=lambda x: x["name"].lower())[:300] + + +# ---- MQTT (Zigbee2MQTT, Tasmota, ESPHome …): "topic" or "topic|field.path" for a JSON payload ----------- +# A subscriber per source runs in the background (python3-paho-mqtt); reading = the latest seen. + +_mqtt = {} # source id → {"client", "seen": {topic: (payload, time)}, "conf"} +_mqtt_lock = threading.Lock() +MQTT_SETTLE = 4 # s after (re)subscribing before the first reading + + +def _paho(): + try: + import paho.mqtt.client as mqtt + except ImportError: + raise SourceError("MQTT needs python3-paho-mqtt (sudo apt install python3-paho-mqtt)") from None + return mqtt + + +def _mqtt_client(src, topics, seen): + mqtt = _paho() + try: + c = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2) + except AttributeError: # paho-mqtt 1.x + c = mqtt.Client() + if src.get("user"): + c.username_pw_set(src.get("user"), src.get("password") or None) + if src.get("tls"): + c.tls_set() + + def on_connect(client, *_a): + for t in topics: + client.subscribe(t) + + def on_message(_c, _u, msg): + seen[msg.topic] = (msg.payload[:4096], time.time()) + c.on_connect = on_connect + c.on_message = on_message + c.connect_async(src.get("host") or "localhost", int(src.get("port") or 1883), 60) + c.loop_start() + return c + + +def mqtt_start(src, refs): + """(Re)start this source's subscriber for the topics its sensors use → True when it was (re)started.""" + topics = sorted({r.split("|", 1)[0] for r in refs}) + conf = json.dumps([src, topics], sort_keys=True) + with _mqtt_lock: + old = _mqtt.get(src["id"]) + if old and old["conf"] == conf: + return False + if old: + old["client"].loop_stop() + old["client"].disconnect() + seen = {} + _mqtt[src["id"]] = {"client": _mqtt_client(src, topics, seen), "seen": seen, "conf": conf} + return True + + +def mqtt_stop_others(keep): + with _mqtt_lock: + for sid in [k for k in _mqtt if k not in keep]: + _mqtt[sid]["client"].loop_stop() + _mqtt[sid]["client"].disconnect() + del _mqtt[sid] + + +def _mqtt_value(payload, field): + try: + text = payload.decode("utf-8", "replace").strip() + except AttributeError: + text = str(payload) + if not field: + return _num(text) + try: + return _num(_at(json.loads(text), field)) + except ValueError: + return None + + +def mqtt_read(src, refs): + m = _mqtt.get(src["id"]) + if not m: + raise SourceError("not connected yet") + unit = "°F" if src.get("fahrenheit") else "°C" + out = {} + for r in refs: + topic, _, field = r.partition("|") + got = m["seen"].get(topic) + if got: + v = _mqtt_value(got[0], field) + out[r] = {"t": _celsius(v, unit), "h": v, "age": int(time.time() - got[1]), "name": _topic_base(topic).split("/")[-1]} + return out + + +def _topic_base(topic): + """"home/bedroom/temperature" → "home/bedroom": the thing measured, without the reading's own name.""" + parts = topic.split("/") + return "/".join(parts[:-1]) if len(parts) > 1 and parts[-1].lower() in GENERIC_KEYS else topic + + +def mqtt_discover(src, listen=6): + """Listen to everything (#) for a few seconds: each numeric payload / JSON field seen.""" + seen = {} + c = _mqtt_client(src, ["#"], seen) + try: + time.sleep(listen) + finally: + c.loop_stop() + c.disconnect() + out = [] + for topic, (payload, _) in sorted(seen.items()): + v = _mqtt_value(payload, "") + if v is not None: + base = _topic_base(topic) + out.append({"ref": topic, "label": topic, "name": base.split("/")[-1], "group": base, "t": v, "h": v}) + continue + try: + j = json.loads(payload) + except ValueError: + continue + out += [{"ref": f"{topic}|{p}", "label": f"{topic} · {p}", "name": topic.split("/")[-1], "group": topic, "t": x, "h": x} + for p, x in _walk(j)] + if not seen: + raise SourceError("connected, but nothing arrived in a few seconds (wrong host / login?)") + return out[:300] + + +# ---- 1-wire (DS18B20 on the Pi's GPIO 4: dtoverlay=w1-gpio in config.txt) ---------------------------------- + +W1 = "/sys/bus/w1/devices" + + +def _w1_temp(dev): + base = os.path.join(W1, dev) + try: + with open(os.path.join(base, "temperature")) as f: + return int(f.read().strip()) / 1000 + except (OSError, ValueError): + pass + try: + with open(os.path.join(base, "w1_slave")) as f: + lines = f.read().splitlines() + if lines and lines[0].endswith("YES") and "t=" in lines[-1]: + return int(lines[-1].split("t=")[1]) / 1000 + except (OSError, ValueError, IndexError): + pass + return None + + +def w1_read(src, refs): + return {r: {"t": _w1_temp(r), "h": None, "age": None, "name": r} for r in refs} + + +def w1_discover(src): + devs = [os.path.basename(p) for p in glob.glob(os.path.join(W1, "28-*"))] + if not devs: + raise SourceError("no DS18B20 found (dtoverlay=w1-gpio in /boot/firmware/config.txt, then reboot)") + return [{"ref": d, "name": d, "t": _w1_temp(d), "h": None} for d in devs] + + +# ---- the types: fields for the Settings panel (secret ones never go back to the browser) ------------------- + +TYPES = { + "termix": {"label": "termix (stm32.php)", "about": "The termix sensor server's API.", "read": termix_read, "discover": termix_discover, "both": True, + "fields": [{"key": "url", "label": "API URL", "type": "url", "required": True}, + {"key": "api_key", "label": "API key", "secret": True}, + {"key": "ids", "label": "Device IDs to look for (comma separated)", "placeholder": "2, 3"}]}, + "json": {"label": "A JSON URL (ESPHome, Tasmota, your own script …)", + "about": "Any address that answers JSON: ESPHome's web server, Tasmota, a script of your own.", "read": json_read, "discover": json_discover, + "fields": [{"key": "url", "label": "URL", "type": "url", "required": True}, + {"key": "header", "label": "Header (optional)", "placeholder": "Authorization: Bearer …", "secret": True}, + {"key": "fahrenheit", "label": "Temperatures are in °F", "type": "check"}]}, + "homeassistant": {"label": "Home Assistant", + "about": "Every temperature and humidity entity, with a long-lived access token.", "read": ha_read, "discover": ha_discover, + "fields": [{"key": "url", "label": "Home Assistant URL", "type": "url", "required": True, + "placeholder": "http://homeassistant.local:8123"}, + {"key": "token", "label": "Long-lived access token (your profile ▸ Security)", "secret": True, + "required": True}]}, + "mqtt": {"label": "MQTT (Zigbee2MQTT, Tasmota …)", + "about": "A broker's topics: Zigbee2MQTT, Tasmota, Shelly, ESPHome …", "read": mqtt_read, "discover": mqtt_discover, + "fields": [{"key": "host", "label": "Broker", "required": True, "placeholder": "192.168.1.10"}, + {"key": "port", "label": "Port", "type": "number", "placeholder": "1883"}, + {"key": "user", "label": "User (optional)"}, + {"key": "password", "label": "Password (optional)", "secret": True}, + {"key": "tls", "label": "TLS", "type": "check"}, + {"key": "fahrenheit", "label": "Temperatures are in °F", "type": "check"}]}, + "w1": {"label": "DS18B20 on this Pi (1-wire)", "about": "Temperature probes on the Pi's 1-wire bus (GPIO 4 by default).", "read": w1_read, "discover": w1_discover, "fields": []}, +} +SECRET_KEYS = {f["key"] for t in TYPES.values() for f in t["fields"] if f.get("secret")} + + +def types_view(): + return {k: {"label": t["label"], "about": t.get("about", ""), "fields": t["fields"], "both": bool(t.get("both"))} + for k, t in TYPES.items()} + + +# ---- the config --------------------------------------------------------------------------------------------- + +def config(cfg): + """The "sensors" section — made from the old "termix" settings when there's none yet (same ids, same order).""" + s = cfg.get("sensors") + if isinstance(s, dict) and "sources" in s: + return s + t = cfg.get("termix") or {} + if not t.get("url"): + return {"sources": [], "list": []} + ids = list(t.get("device_ids") or []) + [i for i in (t.get("outdoor_ids") or []) if i not in (t.get("device_ids") or [])] + src = {"id": "s1", "type": "termix", "url": t.get("url"), "api_key": t.get("api_key", ""), + "ids": ", ".join(map(str, ids))} + out = [{"id": int(d), "source": "s1", "temp": str(d), "hum": None, "name": "", "place": "indoor"} + for d in t.get("device_ids") or []] + out += [{"id": int(d), "source": "s1", "temp": str(d), "hum": None, "name": "", "place": "outdoor"} + for d in (t.get("outdoor_ids") or [])[:MAX_OUTDOOR]] + return {"sources": [src], "list": out} + + +def main_id(conf): + """The sensor shown big on Home: the one chosen (not hidden), else the first indoor one, else the first outdoor one.""" + shown = [x for x in conf.get("list") or [] if x.get("place") != "hidden"] + if any(x["id"] == conf.get("main") for x in shown): + return conf["main"] + first = next((x for x in shown if x["place"] == "indoor"), None) or next(iter(shown), None) + return first["id"] if first else None + + +def public(conf): + """For the browser: the secrets only as set / not set.""" + srcs = [] + for s in conf.get("sources") or []: + srcs.append({k: (bool(v) if k in SECRET_KEYS else v) for k, v in s.items()} + | {"secret_set": {k: bool(s.get(k)) for k in SECRET_KEYS if k in s}}) + return {"sources": srcs, "list": conf.get("list") or [], "main": main_id(conf)} + + +def _merge_secrets(new, old): + """A secret left empty in the form keeps the saved one.""" + was = {s.get("id"): s for s in old.get("sources") or []} + for s in new: + prev = was.get(s.get("id")) or {} + if prev.get("type") != s.get("type"): # another kind of source under that id: nothing to keep + continue + for k in SECRET_KEYS: + if not s.get(k) and k in prev: + s[k] = prev[k] + + +def clean(d, old): + """The panel's {sources, list} → a valid "sensors" section (raises ValueError with what's wrong).""" + sources, seen = [], set() + for i, s in enumerate(d.get("sources") or []): + typ = s.get("type") + if typ not in TYPES: + raise ValueError(f"Source {i + 1}: which kind?") + sid = str(s.get("id") or "").strip() or f"s{i + 1}" + if sid in seen or len(sid) > 20: + raise ValueError(f"Source {i + 1}: its id is taken.") + seen.add(sid) + out = {"id": sid, "type": typ, "label": str(s.get("label") or "").strip()[:60]} + for f in TYPES[typ]["fields"]: + v = s.get(f["key"]) + if f.get("type") == "check": + out[f["key"]] = bool(v) + continue + v = "" if v is None or v is True or v is False else str(v).strip()[:500] + if f.get("type") == "url" and v and not v.startswith(("http://", "https://")): + raise ValueError(f"{out['label'] or TYPES[typ]['label']}: the URL starts with http:// or https://") + if f.get("type") == "number" and v and not v.isdigit(): + raise ValueError(f"{out['label'] or TYPES[typ]['label']}: {f['label']} is a number.") + out[f["key"]] = v + sources.append(out) + _merge_secrets(sources, old) + for s in sources: + for f in TYPES[s["type"]]["fields"]: + if f.get("required") and not s.get(f["key"]): + raise ValueError(f"{s['label'] or TYPES[s['type']]['label']}: {f['label']} is needed.") + ids = {s["id"] for s in sources} + out, used, main = [], set(), None + for x in d.get("list") or []: + if x.get("source") not in ids: + raise ValueError("A sensor's source is gone — remove the sensor or pick another source.") + temp = str(x.get("temp") or "").strip()[:200] + if not temp: + raise ValueError("Each sensor needs what to read.") + place = x.get("place") if x.get("place") in PLACES else "indoor" + try: + sid = int(x.get("id")) + except (TypeError, ValueError): + sid = None + if sid is None or sid in used: + src = next(s for s in sources if s["id"] == x["source"]) + sid = int(temp) if src["type"] == "termix" and temp.isdigit() and int(temp) not in used else None + if sid is None: + sid = max([FIRST_ID - 1, *used, *(int(y.get("id") or 0) for y in d.get("list") or [] if str(y.get("id") or "").isdigit())]) + 1 + used.add(sid) + if x.get("main") and place != "hidden": + main = sid + out.append({"id": sid, "source": x["source"], "temp": temp, "hum": (str(x.get("hum") or "").strip()[:200] or None), + "name": str(x.get("name") or "").strip()[:40], "place": place}) + if sum(1 for x in out if x["place"] == "outdoor") > MAX_OUTDOOR: + raise ValueError(f"Up to {MAX_OUTDOOR} outdoor sensors (they sit next to the weather).") + return {"sources": sources, "list": out, "main": main} + + +def with_secrets(src, old): + """A source from the panel's Test button: its empty secrets filled from the saved one.""" + s = dict(src) + _merge_secrets([s], old) + return s + + +def discover(src): + typ = TYPES.get(src.get("type")) + if not typ: + raise SourceError("which kind?") + if src.get("type") == "mqtt": + src = dict(src, id=src.get("id") or "test") + return typ["discover"](src) + + +def read_all(conf): + """Every source asked once for what its sensors need → ({sensor id: reading}, {source id: status}).""" + refs = {} + for x in conf.get("list") or []: + refs.setdefault(x["source"], set()).update([x["temp"]] + ([x["hum"]] if x.get("hum") else [])) + keep, started = set(), False + got, status = {}, {} + for s in conf.get("sources") or []: # MQTT subscribers first: the first messages come meanwhile + if s.get("type") == "mqtt": + keep.add(s["id"]) + try: + started = mqtt_start(s, refs.get(s["id"]) or set()) or started + except SourceError as e: + status[s["id"]] = str(e) + mqtt_stop_others(keep) + if started: + time.sleep(MQTT_SETTLE) + for s in conf.get("sources") or []: + typ = TYPES.get(s.get("type")) + if not typ or s["id"] in status: + continue + try: + got[s["id"]] = typ["read"](s, sorted(refs.get(s["id"]) or set())) + status[s["id"]] = "ok · " + time.strftime("%H:%M") + except SourceError as e: + status[s["id"]] = str(e) + except Exception as e: + status[s["id"]] = type(e).__name__ + out = {} + for x in conf.get("list") or []: + r = got.get(x["source"]) or {} + rt, rh = r.get(x["temp"]), r.get(x["hum"]) if x.get("hum") else None + if rt is None and rh is None: + continue + both = TYPES[next((s["type"] for s in conf["sources"] if s["id"] == x["source"]), "json")].get("both") + out[x["id"]] = {"t": (rt or {}).get("t"), + "h": (rh or {}).get("h") if x.get("hum") else ((rt or {}).get("h") if both else None), + "age": (rt or rh or {}).get("age"), "name": x.get("name") or (rt or rh or {}).get("name") or ""} + return out, status diff --git a/dashboard/plugins/stations/static/sensors.js b/dashboard/plugins/stations/static/sensors.js new file mode 100644 index 0000000..650aaba --- /dev/null +++ b/dashboard/plugins/stations/static/sensors.js @@ -0,0 +1,184 @@ +// Settings ▸ Sensors (plugins/stations: sources.py, /stations/api/…): the sources (termix, a JSON URL, +// Home Assistant, MQTT, 1-wire; "+ Add sensor source" picks the kind) and the sensors shown — name, +// indoor / outdoor / hidden, order. "Test" asks a +// source what it has; "+ Add" makes a sensor of a reading. Any shown sensor can be the main one (the big temperature +// on Home; by default the first indoor one). One Save for the whole pane; applied without a restart. +(() => { + const root = document.getElementById("st-sensors"); + if (!root) return; + const el = (tag, attrs = {}, ...kids) => { + const e = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (k === "class") e.className = v; else if (k === "text") e.textContent = v; + else if (k.startsWith("on")) e.addEventListener(k.slice(2), v); else if (v !== false && v != null) e.setAttribute(k, v === true ? "" : v); + } + kids.flat().forEach((k) => k != null && e.append(k)); + return e; + }; + const post = async (url, body) => { + let r; + try { r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); } + catch (_) { return { error: "No answer from the dashboard." }; } + const d = await r.json().catch(() => ({ error: `Failed (${r.status}).` })); + if (!r.ok && !d.error) d.error = `Failed (${r.status}).`; + return d; + }; + const fmt = (v, unit) => v == null ? "—" : `${Math.round(v * 10) / 10}${unit}`; + let S = null, dirty = false, picking = false, fresh = null; + const msg = el("span", { class: "st-msg" }); + const touch = () => { dirty = true; msg.textContent = "Not saved yet"; msg.classList.remove("bad"); }; + const srcName = (s) => s.label || S.types[s.type].label; + const both = (sid) => { const s = S.sources.find((x) => x.id === sid); return s && S.types[s.type].both; }; + const nextSid = () => { let i = 1; while (S.sources.some((s) => s.id === `s${i}`)) i++; return `s${i}`; }; + + // ---- a source: its fields, Test, what it found ---- + function sourceCard(s) { + const t = S.types[s.type]; + const found = el("div", { class: "sn-found" }); + const label = el("input", { value: s.label || "", placeholder: t.label, oninput: (e) => { s.label = e.target.value; touch(); } }); + const fields = t.fields.map((f) => { + if (f.type === "check") { + return el("label", { class: "st-check" }, el("input", { type: "checkbox", checked: !!s[f.key], + onchange: (e) => { s[f.key] = e.target.checked; touch(); } }), f.label); + } + const set = (s.secret_set || {})[f.key]; + const inp = el("input", { type: f.secret ? "password" : (f.type === "number" ? "number" : "text"), + value: f.secret ? (typeof s[f.key] === "string" ? s[f.key] : "") : (s[f.key] ?? ""), autocomplete: "off", + placeholder: f.secret ? (set ? "•••••••• saved — type to replace" : (f.placeholder || "not set")) : (f.placeholder || ""), + oninput: (e) => { s[f.key] = e.target.value; touch(); } }); + if (f.secret && typeof s[f.key] !== "string") s[f.key] = ""; // from the server: set / not set; empty = keep it + return el("label", { class: "us-f" }, f.label, inp); + }); + const test = el("button", { type: "button", class: "st-btn", text: "Test" }); + test.addEventListener("click", async () => { + test.disabled = true; + found.replaceChildren(el("p", { class: "st-note", text: s.type === "mqtt" ? "Listening for a few seconds…" : "Asking…" })); + const d = await post("/stations/api/test", { source: s }); + test.disabled = false; + if (d.error) { found.replaceChildren(el("p", { class: "st-note st-bad", text: d.error })); return; } + found.replaceChildren(foundList(s, d.found)); + }); + const del = el("button", { type: "button", class: "us-link us-del", text: "Remove" }); + del.addEventListener("click", () => { + const n = S.list.filter((x) => x.source === s.id).length; + if (!del.classList.contains("armed")) { del.classList.add("armed"); del.textContent = n ? `Click again: also its ${n} sensor${n > 1 ? "s" : ""}` : "Click again to remove"; return; } + S.sources = S.sources.filter((x) => x !== s); S.list = S.list.filter((x) => x.source !== s.id); touch(); render(); + }); + const st = S.status[s.id]; + return el("section", { class: "st-card", "data-sid": s.id }, + el("h2", {}, srcName(s), el("small", { class: "st-status" + (st && !st.startsWith("ok") ? " st-bad" : ""), text: st || (s.new ? "new" : "") })), + el("label", { class: "us-f" }, "Name of this source (optional)", label), ...fields, + el("div", { class: "us-bar" }, el("div", { class: "us-left" }, del), test), found); + } + + const HUM = /(^|[.|/_ ])(h|hum|humidity|rh|relative_humidity)$/i; + function foundList(s, items) { + if (!items.length) return el("p", { class: "st-note", text: "It answered, but with nothing to read." }); + const used = new Set(S.list.filter((x) => x.source === s.id).flatMap((x) => [x.temp, x.hum])); + return el("div", { class: "sn-list" }, items.map((it) => { + const add = el("button", { type: "button", class: "us-link", text: used.has(it.ref) ? "in use" : "+ Add", disabled: used.has(it.ref) }); + add.addEventListener("click", () => { + // a humidity reading of the same thing ("living.h" next to "living.t") goes with it + const hum = both(s.id) || HUM.test(it.ref) ? null : + items.find((o) => o !== it && (o.group ?? o.name) === (it.group ?? it.name) && HUM.test(o.ref) && !used.has(o.ref)); + S.list.push({ id: null, source: s.id, temp: it.ref, hum: hum ? hum.ref : null, + name: it.name && it.name !== it.ref ? it.name : "", place: "indoor" }); + if (hum) used.add(hum.ref); + add.textContent = "added"; add.disabled = true; touch(); renderSensors(); + }); + const val = it.t != null && it.h != null && it.t === it.h ? fmt(it.t, "") : [it.t != null ? fmt(it.t, "°") : null, it.h != null ? fmt(it.h, "%") : null].filter(Boolean).join(" · "); + return el("div", { class: "sn-item" }, el("span", { class: "sn-ref", text: it.label || it.name || it.ref, title: it.ref }), + el("span", { class: "st-note", text: val || "—" }), add); + })); + } + + // ---- the sensors shown ---- + const sensorsBox = el("div", { class: "sn-rows" }); + // the main one: the one picked (if not hidden), else the first indoor one, else the first shown — as sources.main_id + const mainOf = () => { + const shown = S.list.filter((x) => x.place !== "hidden"); + return shown.find((x) => x.main) || shown.find((x) => x.place === "indoor") || shown[0] || null; + }; + function renderSensors() { + const main = mainOf(); + const rows = S.list.map((x, i) => { + const live = S.live[x.id]; + const name = el("input", { value: x.name, placeholder: (live && live.name) || x.temp, oninput: (e) => { x.name = e.target.value; touch(); } }); + const place = el("select", { onchange: (e) => { x.place = e.target.value; touch(); renderSensors(); } }, + [["indoor", "Indoor"], ["outdoor", "Outdoor (next to the weather)"], ["hidden", "Hidden"]].map(([v, l]) => + el("option", { value: v, text: l, selected: x.place === v }))); + const src = el("select", { onchange: (e) => { x.source = e.target.value; touch(); renderSensors(); } }, + S.sources.map((s) => el("option", { value: s.id, text: srcName(s), selected: x.source === s.id }))); + const temp = el("input", { value: x.temp, oninput: (e) => { x.temp = e.target.value; touch(); }, title: "What to read: a device id, entity, topic, JSON path…" }); + const hum = el("input", { value: x.hum || "", placeholder: "(none)", oninput: (e) => { x.hum = e.target.value || null; touch(); } }); + const move = (d) => { const j = i + d; if (j < 0 || j >= S.list.length) return; [S.list[i], S.list[j]] = [S.list[j], S.list[i]]; touch(); renderSensors(); }; + const pick = el("label", { class: "st-check sn-main", title: x.place === "hidden" ? "A hidden sensor can't be the main one" : "" }, + el("input", { type: "radio", name: "sn-main", checked: x === main, disabled: x.place === "hidden", + onchange: () => { S.list.forEach((y) => { y.main = y === x; }); touch(); renderSensors(); } }), "Main"); + const del = el("button", { type: "button", class: "us-link us-del", text: "✕", title: "Remove" , onclick: () => { S.list.splice(i, 1); touch(); renderSensors(); } }); + const now = live ? [fmt(live.t, "°"), live.h != null ? fmt(live.h, "%") : null].filter(Boolean).join(" · ") : "—"; + return el("div", { class: "sn-row" }, + el("div", { class: "sn-head" }, el("b", { text: x === main ? "Main (the big one on Home)" : `Sensor ${i + 1}` }), + el("span", { class: "st-note", text: now }), pick, + el("span", { class: "sn-move" }, el("button", { type: "button", class: "us-link", text: "↑", title: "Up", onclick: () => move(-1) }), + el("button", { type: "button", class: "us-link", text: "↓", title: "Down", onclick: () => move(1) }), del)), + el("div", { class: "us-two" }, el("label", { class: "us-f" }, "Name", name), el("label", { class: "us-f" }, "Where", place)), + el("div", { class: "us-two" }, el("label", { class: "us-f" }, "Source", src), el("label", { class: "us-f" }, "Temperature from", temp)), + both(x.source) ? null : el("label", { class: "us-f" }, "Humidity from (optional)", hum)); + }); + sensorsBox.replaceChildren(...(rows.length ? rows : [el("p", { class: "st-note", text: "None yet — + Add sensor source, Test it, then + Add the readings you want." })])); + } + + // "+ Add sensor source": a box with one tile per kind; picking one adds that source's box, ready to fill and Test + function picker() { + return el("section", { class: "st-card st-span sn-pick" }, + el("h2", {}, "Add a sensor source", el("button", { type: "button", class: "us-link sn-close", text: "Cancel", + onclick: () => { picking = false; render(); } })), + el("p", { class: "st-note", text: "Where the readings come from. After adding it, fill it in and press Test to see what it has." }), + el("div", { class: "sn-kinds" }, Object.entries(S.types).map(([k, t]) => + el("button", { type: "button", class: "sn-kind", onclick: () => { + const s = { id: nextSid(), type: k, label: "", new: true }; + S.sources.push(s); picking = false; fresh = s.id; touch(); render(); + } }, el("b", { text: t.label }), el("span", { text: t.about || "" }))))); + } + const addBtn = (cls) => el("button", { type: "button", class: cls, text: "+ Add sensor source", + onclick: () => { picking = true; render(); root.querySelector(".sn-pick")?.scrollIntoView({ behavior: "smooth", block: "nearest" }); } }); + + function render() { + const save = el("button", { type: "button", class: "st-btn", text: "Save" }); + save.addEventListener("click", async () => { + save.disabled = true; + const d = await post("/stations/api/save", { sources: S.sources, list: S.list }); + save.disabled = false; + if (d.error) { msg.textContent = d.error; msg.classList.add("bad"); return; } + dirty = false; msg.textContent = "Saved — reading in a moment"; setTimeout(load, 4000); + }); + renderSensors(); + root.replaceChildren( + el("section", { class: "st-card st-span" }, el("h2", {}, "Sensors", el("small", { class: "st-status", text: S.statusLine || "" })), + el("p", { class: "st-note", text: "In this order on Home and the 3.5\" screen. Pick which one is Main: the big temperature " + + "on Home (by default the first indoor one). " + + "Up to 3 outdoor ones sit next to the weather. Saving applies at once." }), + sensorsBox, el("div", { class: "us-bar" }, el("div", { class: "us-left" }, picking ? null : addBtn("us-link sn-add")), msg, save)), + ...(picking ? [picker()] : []), + ...(S.sources.length ? [el("div", { class: "st-cols sn-srcs" }, S.sources.map(sourceCard))] : [])); + if (fresh) { + const card = root.querySelector(`[data-sid="${fresh}"]`); + fresh = null; + card?.scrollIntoView({ behavior: "smooth", block: "center" }); + card?.querySelector("input")?.focus({ preventScroll: true }); + } + } + + async function load() { + try { S = await (await fetch("/stations/api/config", { cache: "no-store" })).json(); } + catch (_) { root.replaceChildren(el("p", { class: "st-note", text: "Could not load the sensors." })); return; } + const st = Object.values(S.status); + S.list.forEach((x) => { x.main = x.id === S.main; }); + if (!S.sources.length) picking = true; // nothing set up yet: show the kinds straight away + S.statusLine = st.length ? (st.every((x) => x.startsWith("ok")) ? st[0] : st.find((x) => !x.startsWith("ok"))) : ""; + render(); + } + window.addEventListener("beforeunload", (e) => { if (dirty) { e.preventDefault(); e.returnValue = ""; } }); + load(); +})(); diff --git a/dashboard/plugins/stations/static/stations.css b/dashboard/plugins/stations/static/stations.css new file mode 100644 index 0000000..683db39 --- /dev/null +++ b/dashboard/plugins/stations/static/stations.css @@ -0,0 +1,40 @@ +/* The stations page — on top of dash.css (its tokens, header, tab row). Real px. */ +.page-stations { display: flex; flex-direction: column; gap: 14px; font-size: 15px; } +.sp-sub { display: flex; flex-direction: column; gap: 14px; } +@media (min-width: 1000px) { /* the same spot as on the weather page (dash.css .page-weather .headwrap) */ + .page-stations { gap: var(--gap); } + .sp-sub { position: relative; margin-top: calc(var(--k) * -4); } + .sp-sub > .tabs { position: absolute; left: 0; bottom: calc(var(--k) * -6); border-bottom: 0; } + .sp-sub > .tabs a { padding: calc(var(--k) * 2) calc(var(--k) * 18) calc(var(--k) * 4); } +} +.sp-ranges { align-self: flex-end; display: inline-flex; background: var(--card); border-radius: 9px; padding: 3px; gap: 2px; } +.sp-ranges a { padding: 5px 12px; border-radius: 7px; color: var(--muted); font-size: 13.5px; } +.sp-ranges a:hover { color: var(--fg); } +.sp-ranges a.on { background: #10131a; color: var(--accent); } +.sp { display: grid; grid-template-columns: repeat(auto-fit, minmax(420px, 1fr)); gap: 14px; } +.sp-card { background: var(--card); border-radius: 14px; padding: 16px 18px; display: flex; flex-direction: column; gap: 8px; min-width: 0; } +.sp-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; } +.sp-name { font: 700 18px "DejaVu Web", sans-serif; display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.sp-name small { font-weight: 400; font-size: 12.5px; color: var(--dim); text-transform: capitalize; } +.sp-now { display: flex; align-items: baseline; gap: 10px; white-space: nowrap; } +.sp-now b { font: 700 30px "DejaVu Web", sans-serif; } +.sp-now span { color: var(--cool); font-size: 18px; } +.sp-range { color: var(--muted); font-size: 13.5px; } +.sp-range b { color: var(--fg); font-weight: 400; } +.sp-chart { width: 100%; height: 220px; display: block; overflow: visible; } +.sp-chart .grid { stroke: #222837; stroke-width: 1; vector-effect: non-scaling-stroke; } +.sp-chart .base { stroke: #2e3647; stroke-width: 1; vector-effect: non-scaling-stroke; } +.sp-chart .temp { fill: none; stroke: var(--warm); stroke-width: 2; vector-effect: non-scaling-stroke; stroke-linejoin: round; } +.sp-chart .band { fill: var(--warm); opacity: .16; } +.sp-chart .hum { fill: none; stroke: var(--cool); stroke-width: 1.5; stroke-dasharray: 5 4; vector-effect: non-scaling-stroke; opacity: .8; } +.sp-chart .hit { fill: transparent; } +.sp-chart .hit:hover { fill: rgba(255, 255, 255, .06); } +.sp-chart text { fill: var(--muted); font: 12px "DejaVu Web", sans-serif; } +.sp-chart .xl { text-anchor: middle; } +.sp-legend { display: flex; gap: 14px; color: var(--muted); font-size: 12.5px; } +.sp-legend span { display: inline-flex; align-items: center; gap: 6px; } +.sp-legend i { width: 16px; height: 0; border-top: 2px solid var(--warm); } +.sp-legend i.band { height: 8px; border: 0; background: var(--warm); opacity: .3; } +.sp-legend i.hum { border-top: 2px dashed var(--cool); } +.sp-none { margin: 4px 0; color: var(--dim); } +@media (max-width: 499px) { .sp { grid-template-columns: minmax(0, 1fr); } .sp-chart { height: 180px; } } diff --git a/dashboard/plugins/stations/templates/stations/_home_main.html b/dashboard/plugins/stations/templates/stations/_home_main.html new file mode 100644 index 0000000..d310341 --- /dev/null +++ b/dashboard/plugins/stations/templates/stations/_home_main.html @@ -0,0 +1,9 @@ +{# The Home's main temperature (region "main"): m = views._main_temp — the first sensor. #} +<section class="main-temp"> + <div class="mt" style="color:{{ m.colour if m.temp else THEME.dim }}">{{ m.temp or "—" }}</div> + <div class="mt-sub"> + <svg class="house" viewBox="-12 -12 24 24"><polygon points="-12,-2 0,-12 12,-2" fill="{{ THEME.accent if m.temp else THEME.dim }}"/> + <rect x="-8" y="-2" width="16" height="12" fill="{{ THEME.accent if m.temp else THEME.dim }}"/></svg> + <span class="nm">{{ m.name }}</span>{% if m.hum %}<span class="hm">{{ m.hum }}</span>{% endif %} + </div> +</section> diff --git a/dashboard/plugins/stations/templates/stations/_home_row.html b/dashboard/plugins/stations/templates/stations/_home_row.html new file mode 100644 index 0000000..d9bd091 --- /dev/null +++ b/dashboard/plugins/stations/templates/stations/_home_row.html @@ -0,0 +1,7 @@ +{# The Home's stations row (region "stations"): rows = views._stations — the other sensors. #} +{% from "_reading.html" import reading %} +<section class="stations{% if not rows %} empty{% endif %}"> + {% for row in rows %} + <div class="srow">{% for r in row %}{{ reading(r) }}{% endfor %}</div> + {% endfor %} +</section> diff --git a/dashboard/plugins/stations/templates/stations/page.html b/dashboard/plugins/stations/templates/stations/page.html new file mode 100644 index 0000000..92b9519 --- /dev/null +++ b/dashboard/plugins/stations/templates/stations/page.html @@ -0,0 +1,46 @@ +{% extends "base.html" %} +{% from "_header.html" import nav_btns, settings_btn, title_block, subline, section_tabs %} +{% block title %}Stations · Dashboard{% endblock %} +{% block head %}<link rel="stylesheet" href="{{ url_for('stations.static', filename='stations.css') }}?v={{ build_id() }}">{% endblock %} +{# The stations page: a card per sensor — now (temperature in its band colour, humidity), + lowest / highest in the range, the graph (temperature line, from 7 days on a lowest–highest + band, humidity dashed on its own 0–100 % scale, gaps where nothing was measured; hover a + strip for the values). views.page / views.chart. #} +{% block page %} +<header class="head"> + {{ nav_btns() }} + {{ title_block("Stations", "/stations") }} + {{ settings_btn("sensors") }} +</header> +<div class="sp-sub">{# like the weather page: on wide windows the tab row sits beside the sub-heading #} +{{ subline(v.status) }} +{% if plugin_host("stations") %}{{ section_tabs(plugin_host("stations"), "/stations") }}{% endif %}{# inside Weather: its tab row #} +</div> +<nav class="sp-ranges" aria-label="Range">{% for k, l in v.ranges.items() %}<a href="?r={{ k }}"{% if k == v.range %} class="on" aria-current="page"{% endif %}>{{ l }}</a>{% endfor %}</nav> +<div class="sp"> + {% for c in v.cards %} + <section class="sp-card"> + <div class="sp-head"> + <div class="sp-name">{{ c.name }}<small>{{ c.kind }}{% if c.age is not none and c.age > 900 %} · last reading {{ (c.age // 60) | int }} min ago{% endif %}</small></div> + <div class="sp-now"><b style="color:{{ c.colour or 'var(--dim)' }}">{{ c.temp or "—" }}</b>{% if c.hum %}<span>{{ c.hum }}</span>{% endif %}</div> + </div> + {% if c.lo %}<div class="sp-range">lowest <b>{{ c.lo }}</b> · highest <b>{{ c.hi }}</b></div>{% endif %} + {% set g = c.chart %} + {% if g %} + <svg class="sp-chart" viewBox="0 0 {{ g.w }} {{ g.h }}" preserveAspectRatio="none" role="img" aria-label="{{ c.name }}: temperature and humidity"> + {% for t in g.yticks %}<line x1="0" x2="{{ g.w }}" y1="{{ t.y }}" y2="{{ t.y }}" class="grid"/><text x="4" y="{{ t.y - 4 }}" class="yl">{{ t.v }}</text>{% endfor %} + <line x1="0" x2="{{ g.w }}" y1="{{ g.base }}" y2="{{ g.base }}" class="base"/> + {% for t in g.xticks %}<line x1="{{ t.x }}" x2="{{ t.x }}" y1="12" y2="{{ g.base }}" class="grid"/><text x="{{ t.x }}" y="{{ g.h - 8 }}" class="xl">{{ t.t }}</text>{% endfor %} + {% for b in g.band %}<polygon points="{{ b }}" class="band"/>{% endfor %} + {% for p in g.hum %}<polyline points="{{ p }}" class="hum"/>{% endfor %} + {% for p in g.temp %}<polyline points="{{ p }}" class="temp"/>{% endfor %} + {% for s in g.strips %}<rect x="{{ s.x }}" y="0" width="{{ s.w }}" height="{{ g.base }}" class="hit"><title>{{ s.tip }}{% endfor %} + +
    temperature{% if v.range != "1d" %}lowest – highest{% endif %}humidity
    + {% else %} +

    No readings kept for this sensor in this range yet — they're kept from now on.

    + {% endif %} + + {% endfor %} + +{% endblock %} diff --git a/dashboard/plugins/stations/views.py b/dashboard/plugins/stations/views.py new file mode 100644 index 0000000..b10d974 --- /dev/null +++ b/dashboard/plugins/stations/views.py @@ -0,0 +1,146 @@ +"""View models of the stations plugin for the web Home: the readings, the stations row, +the main temperature (moved here from the core's webview.py).""" +from panel import disp_temp, temp_colour + +STATION_ROWS = {1: (1,), 2: (1, 1), 3: (2, 1), 4: (2, 2), 5: (3, 2), 6: (3, 3)} + + +def _temp(s, units, decimals=1): + return f"{disp_temp(s.t, units)[0]:.{decimals}f}°" if s is not None and s.t is not None else None + + +def _reading(s, units): + return {"name": (s.name or "—") if s else "—", "temp": _temp(s, units), + "hum": f"{s.h:.0f}%" if s is not None and s.h is not None else None} + + +def _stations(store): + srcs = [s for s in store.sources if s is not store.main and s.device_id is not None][:6] + rows, it = [], iter(srcs) + for n in STATION_ROWS.get(len(srcs), ()): + rows.append([_reading(next(it), store.units) for _ in range(n)]) + return rows + + +def _main_temp(store): + house = store.main + if house.t is None: + return {"name": house.name or "—", "temp": None, "hum": None} + t, u = disp_temp(house.t, store.units) + return {"name": house.name or "—", "temp": f"{t:.1f}{u}", "colour": temp_colour(house.t), + "hum": f"{house.h:.0f}%" if house.h is not None else None} + + +# ---- the stations page: each sensor's graph -------------------------------------------- + +CHART_W, CHART_H = 1000, 240 +RANGE_LABELS = {"1d": "24 hours", "7d": "7 days", "30d": "30 days", "1y": "1 year"} + + +def _ticks(rng, t0, t1): + """x labels: hours (24 h), days (7 days), every 5th day (30 days), months (1 year).""" + from datetime import datetime, timedelta + a, z = datetime.fromtimestamp(t0), datetime.fromtimestamp(t1) + out = [] + if rng == "1d": + t = a.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1) + while t < z: + if t.hour % 3 == 0: + out.append((t.timestamp(), f"{t:%H}:00")) + t += timedelta(hours=1) + elif rng in ("7d", "30d"): + t = a.replace(hour=0, minute=0, second=0, microsecond=0) + timedelta(days=1) + while t < z: + if rng == "7d" or t.day % 5 == 1: + out.append((t.timestamp(), f"{t:%a %-d}" if rng == "7d" else f"{t:%-d %b}")) + t += timedelta(days=1) + else: + t = a.replace(day=1, hour=0, minute=0, second=0, microsecond=0) + while t < z: + if t > a: + out.append((t.timestamp(), f"{t:%b}" if t.month != 1 else f"{t:%b %Y}")) + t = (t + timedelta(days=32)).replace(day=1) + return out + + +def chart(points, rng, span, step, now, units): + """One sensor's graph in a CHART_W × CHART_H box: the temperature (line; from 7 days on, + a lowest–highest band behind it), the humidity on its own 0–100 % scale (dashed), gaps + where nothing was measured, hover strips with the values. None without points.""" + if not points: + return None + t0, t1 = now - span, now + x = lambda t: round((t - t0) / span * CHART_W, 1) + temps = [disp_temp(p[1], units)[0] for p in points if p[1] is not None] + lows = [disp_temp(p[2], units)[0] for p in points if p[2] is not None] + highs = [disp_temp(p[3], units)[0] for p in points if p[3] is not None] + band = rng != "1d" + lo = min(lows if band and lows else temps or [0]) - 0.5 + hi = max(highs if band and highs else temps or [1]) + 0.5 + if hi - lo < 3: + mid = (hi + lo) / 2 + lo, hi = mid - 1.5, mid + 1.5 + y = lambda v: round(12 + (hi - v) / (hi - lo) * (CHART_H - 40), 1) + yh = lambda h: round(12 + (100 - h) / 100 * (CHART_H - 40), 1) + runs, cur, prev = [], [], None # split where readings are missing + for p in points: + if prev is not None and p[0] - prev > step * 2.5: + runs.append(cur) + cur = [] + cur.append(p) + prev = p[0] + runs.append(cur) + temp_paths, hum_paths, bands = [], [], [] + for r in runs: + tp = [(x(p[0] + step / 2), y(disp_temp(p[1], units)[0])) for p in r if p[1] is not None] + hp = [(x(p[0] + step / 2), yh(p[4])) for p in r if p[4] is not None] + if tp: + temp_paths.append(" ".join(f"{a},{b}" for a, b in tp)) + if hp: + hum_paths.append(" ".join(f"{a},{b}" for a, b in hp)) + if band: + top = [(x(p[0] + step / 2), y(disp_temp(p[3], units)[0])) for p in r if p[3] is not None] + bot = [(x(p[0] + step / 2), y(disp_temp(p[2], units)[0])) for p in reversed(r) if p[2] is not None] + if top and bot: + bands.append(" ".join(f"{a},{b}" for a, b in top + bot)) + from datetime import datetime + u = disp_temp(0, units)[1] + fmt_t = "%H:%M" if rng == "1d" else "%a %-d %b %H:%M" if rng in ("7d", "30d") else "%a %-d %b %Y" + strips = [] + w = max(1.0, step / span * CHART_W) + for p in points: + parts = [datetime.fromtimestamp(p[0]).strftime(fmt_t)] + if p[1] is not None: + parts.append(f"{disp_temp(p[1], units)[0]:.1f}{u}" + ( + f" ({disp_temp(p[2], units)[0]:.1f} – {disp_temp(p[3], units)[0]:.1f})" if band and p[2] is not None else "")) + if p[4] is not None: + parts.append(f"{p[4]:.0f}%") + strips.append({"x": x(p[0]), "w": round(w, 1), "tip": " · ".join(parts)}) + import math + gap = next(g for g in (1, 2, 5, 10, 20) if (hi - lo) / g <= 5) # round steps, at most 5 lines + yt = [v * gap for v in range(math.ceil(lo / gap), math.floor(hi / gap) + 1)] + return {"w": CHART_W, "h": CHART_H, "temp": temp_paths, "hum": hum_paths, "band": bands, "strips": strips, + "yticks": [{"y": y(v), "v": f"{v:.0f}{u}"} for v in yt], + "xticks": [{"x": x(t), "t": l} for t, l in _ticks(rng, t0, t1)], + "base": CHART_H - 28} + + +def page(store, devs, series_of, rng, now, live): + """The stations page: a card per sensor (live values + its graph). devs = db.devices(); + live = {device_id: TempSource}; series_of(device_id) → db.series rows.""" + from .db import RANGES + span, step = RANGES[rng] + cards = [] + known = {d["id"] for d in devs} + for d in devs + [{"id": i, "name": s.name, "kind": "indoor"} for i, s in live.items() if i not in known]: + s = live.get(d["id"]) + r = _reading(s, store.units) if s else {"name": d["name"] or f"#{d['id']}", "temp": None, "hum": None} + pts = series_of(d["id"]) + temps = [p[2] for p in pts if p[2] is not None] + [p[3] for p in pts if p[3] is not None] + cards.append({"id": d["id"], "name": (s.name if s else None) or d["name"] or f"#{d['id']}", "kind": d["kind"], + "temp": r["temp"], "hum": r["hum"], "colour": temp_colour(s.t) if s and s.t is not None else None, + "age": s.age_s if s else None, + "lo": f"{disp_temp(min(temps), store.units)[0]:.1f}°" if temps else None, + "hi": f"{disp_temp(max(temps), store.units)[0]:.1f}°" if temps else None, + "chart": chart(pts, rng, span, step, now, store.units)}) + return {"range": rng, "ranges": RANGE_LABELS, "cards": cards, "status": store.sensors_status} diff --git a/dashboard/plugins/weather/__init__.py b/dashboard/plugins/weather/__init__.py new file mode 100644 index 0000000..0a0474f --- /dev/null +++ b/dashboard/plugins/weather/__init__.py @@ -0,0 +1,96 @@ +"""Weather (built in): Open-Meteo for the main place + the extra places of Settings ▸ Weather. + + /weather the weather page (now + its values, the sun's arc | air quality, 48 h chart, + 14 days; ?loc=N another place) + /icon/.png a weather icon (Meteocons, icons/.png) with its margin trimmed (cached) + +Also the Home's weather box (region "weather"; the stations plugin's outdoor readings sit in +it when that's on), the 3.5" Weather screen and the weather in the 3.5" Home's top-right +corner, and for the core: provide("sun") → today's (sunrise, sunset) for the backlight. +Off: no weather anywhere, the backlight falls back to fixed day / night times. Settings ▸ +Weather (location, places) is one of the Settings page's own panes (settings_tab). +""" +import io + +from flask import abort, render_template, request, send_file + +import time + +from . import places, screens, views, weather + +META = { + "title": "Weather", + "glyph": "☁", + "glyph_color": "#cfd6e4", + "glyph_svg": {"viewBox": "-12 -12 24 24", # a cloud, like the 3.5" screen's button + "d": "M-6.5 7 A4.5 4.5 0 0 1 -7 -2 A6 6 0 0 1 4 -4.5 A5.5 5.5 0 0 1 6.5 7 Z"}, + "description": "Open-Meteo forecast for your place (and more places): the Home box, the weather page, the 3.5\" " + "screen, sunrise / sunset for the screen's brightness.", + "default_on": True, + "settings_tab": "weather", + "links": [{"label": "Open", "href": "/weather"}], + "sync": {"places.db": places.SYNC}, # the phone app's places — written here only (places.py) +} +_ICONS = {} # code -> PNG bytes (trimmed) + + +def register(ctx): + store = ctx.store + weather.load_cache(store) # the last good weather, in case there's no internet now + ctx.worker(lambda c: weather.openmeteo_worker(store)) + places_db = ctx.data_path("places.db") + places.create(places_db) + + def places_worker(_ctx): # the primary writes them; the others get them synced + while True: + if ctx.primary(): + try: + places.refresh(places_db, store.cfg) + except Exception as e: + print(f"weather: places for the app: {e}", flush=True) + time.sleep(places.EVERY) + ctx.worker(places_worker) + bp = ctx.blueprint("") + ctx.warm("/weather") + ctx.nav("Weather", "/weather") + ctx.section_tabs([("/weather", "Forecast")]) # + Stations (inside, while it's on) + + def sun(): + cur = store.wx_current + s = (cur or {}).get("sys") or {} + from datetime import datetime + return (datetime.fromtimestamp(s["sunrise"]) if s.get("sunrise") else None, + datetime.fromtimestamp(s["sunset"]) if s.get("sunset") else None) + ctx.provide("sun", sun) + ctx.provide("status", lambda: store.wx_status) + + def home_box(): + with store.lock: + cur, fc = store.wx_current, list(store.wx_forecast) + outdoor = ctx.ask("stations", "outdoor") or [] # readings shown in the box, if any + return render_template("weather/_home.html", w=views.home_box(store, cur, fc), outdoor=outdoor) + ctx.home("weather", home_box) + + ctx.screen("Weather", screens.icon, screens.screen, order=20) + ctx.home_screen("corner", screens.home_corner) + + @bp.route("/weather") + def page(): + try: + loc = int(request.args.get("loc", 0)) + except ValueError: + loc = 0 + return render_template("weather/page.html", v=views.weather_page(store, loc), page="weather") + + @bp.route("/icon/.png") + def icon(code): + if not code.isalnum() or len(code) > 4: + abort(404) + if code not in _ICONS: + im = weather.trimmed_icon(code, 220) + if im is None: + abort(404) + buf = io.BytesIO() + im.save(buf, "PNG") + _ICONS[code] = buf.getvalue() + return send_file(io.BytesIO(_ICONS[code]), mimetype="image/png", max_age=86400) diff --git a/dashboard/plugins/weather/icons/01d.png b/dashboard/plugins/weather/icons/01d.png new file mode 100644 index 0000000..8753306 Binary files /dev/null and b/dashboard/plugins/weather/icons/01d.png differ diff --git a/dashboard/plugins/weather/icons/01n.png b/dashboard/plugins/weather/icons/01n.png new file mode 100644 index 0000000..cd5df5f Binary files /dev/null and b/dashboard/plugins/weather/icons/01n.png differ diff --git a/dashboard/plugins/weather/icons/02d.png b/dashboard/plugins/weather/icons/02d.png new file mode 100644 index 0000000..90fb73a Binary files /dev/null and b/dashboard/plugins/weather/icons/02d.png differ diff --git a/dashboard/plugins/weather/icons/02n.png b/dashboard/plugins/weather/icons/02n.png new file mode 100644 index 0000000..5f9f762 Binary files /dev/null and b/dashboard/plugins/weather/icons/02n.png differ diff --git a/dashboard/plugins/weather/icons/03d.png b/dashboard/plugins/weather/icons/03d.png new file mode 100644 index 0000000..108f8c6 Binary files /dev/null and b/dashboard/plugins/weather/icons/03d.png differ diff --git a/dashboard/plugins/weather/icons/03n.png b/dashboard/plugins/weather/icons/03n.png new file mode 100644 index 0000000..824ec7e Binary files /dev/null and b/dashboard/plugins/weather/icons/03n.png differ diff --git a/dashboard/plugins/weather/icons/04d.png b/dashboard/plugins/weather/icons/04d.png new file mode 100644 index 0000000..9190826 Binary files /dev/null and b/dashboard/plugins/weather/icons/04d.png differ diff --git a/dashboard/plugins/weather/icons/04n.png b/dashboard/plugins/weather/icons/04n.png new file mode 100644 index 0000000..9190826 Binary files /dev/null and b/dashboard/plugins/weather/icons/04n.png differ diff --git a/dashboard/plugins/weather/icons/09d.png b/dashboard/plugins/weather/icons/09d.png new file mode 100644 index 0000000..0b34fd5 Binary files /dev/null and b/dashboard/plugins/weather/icons/09d.png differ diff --git a/dashboard/plugins/weather/icons/09n.png b/dashboard/plugins/weather/icons/09n.png new file mode 100644 index 0000000..0b34fd5 Binary files /dev/null and b/dashboard/plugins/weather/icons/09n.png differ diff --git a/dashboard/plugins/weather/icons/10d.png b/dashboard/plugins/weather/icons/10d.png new file mode 100644 index 0000000..7c72e41 Binary files /dev/null and b/dashboard/plugins/weather/icons/10d.png differ diff --git a/dashboard/plugins/weather/icons/10n.png b/dashboard/plugins/weather/icons/10n.png new file mode 100644 index 0000000..7c72e41 Binary files /dev/null and b/dashboard/plugins/weather/icons/10n.png differ diff --git a/dashboard/plugins/weather/icons/11d.png b/dashboard/plugins/weather/icons/11d.png new file mode 100644 index 0000000..da34a4d Binary files /dev/null and b/dashboard/plugins/weather/icons/11d.png differ diff --git a/dashboard/plugins/weather/icons/11n.png b/dashboard/plugins/weather/icons/11n.png new file mode 100644 index 0000000..da34a4d Binary files /dev/null and b/dashboard/plugins/weather/icons/11n.png differ diff --git a/dashboard/plugins/weather/icons/13d.png b/dashboard/plugins/weather/icons/13d.png new file mode 100644 index 0000000..463c769 Binary files /dev/null and b/dashboard/plugins/weather/icons/13d.png differ diff --git a/dashboard/plugins/weather/icons/13n.png b/dashboard/plugins/weather/icons/13n.png new file mode 100644 index 0000000..463c769 Binary files /dev/null and b/dashboard/plugins/weather/icons/13n.png differ diff --git a/dashboard/plugins/weather/icons/50d.png b/dashboard/plugins/weather/icons/50d.png new file mode 100644 index 0000000..7d83580 Binary files /dev/null and b/dashboard/plugins/weather/icons/50d.png differ diff --git a/dashboard/plugins/weather/icons/50n.png b/dashboard/plugins/weather/icons/50n.png new file mode 100644 index 0000000..7d83580 Binary files /dev/null and b/dashboard/plugins/weather/icons/50n.png differ diff --git a/dashboard/plugins/weather/icons/LICENSE-meteocons.txt b/dashboard/plugins/weather/icons/LICENSE-meteocons.txt new file mode 100644 index 0000000..1588fe9 --- /dev/null +++ b/dashboard/plugins/weather/icons/LICENSE-meteocons.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2020-present Bas Milius + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dashboard/plugins/weather/places.py b/dashboard/plugins/weather/places.py new file mode 100644 index 0000000..feef8d3 --- /dev/null +++ b/dashboard/plugins/weather/places.py @@ -0,0 +1,57 @@ +"""The places for the phone app's Weather: home (Settings ▸ Weather ▸ Home location) + the weather +page's places, written by the primary dashboard into dash_data/weather/places.db and synced one way +(META "sync") — so the app starts with them, nothing typed there. Gone ones are deleted (→ delete markers). + + place (k = the name, name, lat, lon, ord: 0 = home) +""" +import os +import sqlite3 +from contextlib import closing + +SCHEMA = "CREATE TABLE IF NOT EXISTS place (k TEXT PRIMARY KEY, name TEXT NOT NULL, lat REAL NOT NULL, lon REAL NOT NULL, ord INTEGER NOT NULL);" +SYNC = {"place": {"key": "'place:' || NEW.k"}} # META["sync"]["places.db"] +EVERY = 60 # s between looks at the settings + + +def create(path): + os.makedirs(os.path.dirname(path), exist_ok=True) + with closing(sqlite3.connect(path)) as c: + c.executescript(SCHEMA) + os.chmod(path, 0o600) + + +def wanted(cfg): + out = [] + if cfg.get("lat") or cfg.get("lon"): + out.append((cfg.get("location_name") or "Home", float(cfg["lat"]), float(cfg["lon"]))) + for p in cfg.get("weather_locations") or []: + try: + out.append((str(p["name"]), float(p["lat"]), float(p["lon"]))) + except (KeyError, TypeError, ValueError): + continue + seen, rows = set(), [] + for name, lat, lon in out: + if name not in seen: + seen.add(name) + rows.append({"k": name, "name": name, "lat": round(lat, 5), "lon": round(lon, 5), "ord": len(rows)}) + return rows + + +def refresh(path, cfg): + """Make the table = the settings' places → changed rows (0 = nothing to do).""" + new = {r["k"]: r for r in wanted(cfg)} + changed = 0 + with closing(sqlite3.connect(path, timeout=10)) as con: + con.row_factory = sqlite3.Row + old = {r["k"]: dict(r) for r in con.execute("SELECT k, name, lat, lon, ord FROM place")} + for k, r in new.items(): + if old.get(k) != r: + con.execute("INSERT INTO place (k, name, lat, lon, ord) VALUES (:k, :name, :lat, :lon, :ord) " + "ON CONFLICT(k) DO UPDATE SET name = excluded.name, lat = excluded.lat, lon = excluded.lon, " + "ord = excluded.ord", r) + changed += 1 + for k in old.keys() - new.keys(): + con.execute("DELETE FROM place WHERE k = ?", (k,)) + changed += 1 + con.commit() + return changed diff --git a/dashboard/plugins/weather/screens.py b/dashboard/plugins/weather/screens.py new file mode 100644 index 0000000..bd52ec5 --- /dev/null +++ b/dashboard/plugins/weather/screens.py @@ -0,0 +1,69 @@ +"""The weather on the 3.5" panel: its screen (now + 5 days) and the 3.5" Home's top-right +corner (icon, temperature, condition, H / L, humidity) — moved from the core's screens.py.""" +from config import THEME +from panel import disp_temp, fit_text, ic_cloud, text_c, text_r + +from .weather import daily_forecast, load_icon, today_weather + +icon = ic_cloud +COLUMN_X = 316 # the 3.5" Home's right column starts here (the agenda's right edge) + + +def home_corner(img, d, panel, store): + with store.lock: + cur, fc = store.wx_current, list(store.wx_forecast) + rx = panel.w - 16 + if cur: + ci = load_icon(cur["weather"][0]["icon"], 80) + if ci: + img.paste(ci, (panel.w - 88, -6), ci) + t, u = disp_temp(cur["main"]["temp"], store.units) + text_r(d, rx, 66, f"{t:.0f}{u}", panel.f["lg"], THEME["fg"]) + text_r(d, rx, 104, fit_text(d, cur["weather"][0]["description"].title(), panel.f["xs"], + rx - COLUMN_X - 12), panel.f["xs"], THEME["muted"]) + hum = f"{cur['main']['humidity']}%" + text_r(d, rx, 124, hum, panel.f["sm"], THEME["cool"]) + tw_ = today_weather(fc, store.units) + if tw_: + _, _, lo, hi = tw_ + hx = rx - d.textlength(hum, font=panel.f["sm"]) - 12 + text_r(d, hx, 124, f"H {hi:.0f}° L {lo:.0f}°", panel.f["sm"], THEME["dim"]) + else: + text_r(d, rx, 66, "—", panel.f["lg"], THEME["dim"]) + text_r(d, rx, 102, store.wx_status, panel.f["xs"], THEME["dim"]) + + +def screen(img, d, panel, store): + with store.lock: + cur, fc = store.wx_current, list(store.wx_forecast) + d.text((16, 10), store.cfg.get("location_name", "—"), font=panel.f["sm"], fill=THEME["accent"]) + if not cur: + d.text((16, 70), "Weather unavailable", font=panel.f["lg"], fill=THEME["dim"]) + d.text((16, 112), f"status: {store.wx_status}", font=panel.f["sm"], fill=THEME["muted"]) + return + ic = load_icon(cur["weather"][0]["icon"], 96) + if ic: + img.paste(ic, (10, 28), ic) + t, u = disp_temp(cur["main"]["temp"], store.units) + d.text((114, 34), f"{t:.0f}{u}", font=panel.f["xl"], fill=THEME["fg"]) + d.text((114, 96), cur["weather"][0]["description"].title(), font=panel.f["sm"], fill=THEME["muted"]) + fl = disp_temp(cur["main"]["feels_like"], store.units)[0] + d.text((300, 36), f"Feels {fl:.0f}{u}", font=panel.f["sm"], fill=THEME["muted"]) + d.text((300, 60), f"Humidity {cur['main']['humidity']}%", font=panel.f["sm"], fill=THEME["cool"]) + wind = cur.get("wind", {}).get("speed") + if wind is not None: + d.text((300, 84), f"Wind {wind:.0f} m/s", font=panel.f["sm"], fill=THEME["muted"]) + + y = 140 + d.line([(16, y), (panel.w - 16, y)], fill=THEME["card"], width=1) + days = daily_forecast(fc, store.units, 5) + if days: + cw = (panel.w - 32) / len(days) + for i, dd in enumerate(days): + cx = 16 + cw * i + cw / 2 + text_c(d, cx, y + 8, dd["label"], panel.f["xs"], THEME["muted"]) + ici = load_icon(dd["icon"], 48) + if ici: + img.paste(ici, (int(cx - 24), y + 24), ici) + text_c(d, cx, y + 74, f"{dd['hi']:.0f}°", panel.f["sm"], THEME["fg"]) + text_c(d, cx, y + 92, f"{dd['lo']:.0f}°", panel.f["xs"], THEME["dim"]) diff --git a/dashboard/plugins/weather/templates/weather/_home.html b/dashboard/plugins/weather/templates/weather/_home.html new file mode 100644 index 0000000..381d72a --- /dev/null +++ b/dashboard/plugins/weather/templates/weather/_home.html @@ -0,0 +1,28 @@ +{# The Home's weather box (region "weather"): w = views.home_box, outdoor = the stations + plugin's outdoor readings (ctx.ask("stations", "outdoor"), may be empty). #} +{% from "_reading.html" import reading %} + + {% if w.status %} +
    Weather: {{ w.status }}
    + {% else %} +
    +
    +
    +
    {{ w.temp }}
    +
    {{ w.desc }}{% if w.hl %}{{ w.hl }}{% endif %}
    +
    + {% for x in w.extras %}{% if x.arrow is defined and x.arrow is not none %} {% elif x.svg %} {% elif x.glyph %}{{ x.glyph }} {% endif %}{{ x.text }}{% endfor %} +
    +
    + {% if outdoor %} +
    {% for r in outdoor %}{{ reading(r) }}{% endfor %}
    + {% endif %} +
    +
    + {% for dd in w.days %} +
    {{ dd.label }}
    +
    {{ dd.hi }}{{ dd.lo }}
    + {% endfor %} +
    + {% endif %} +
    diff --git a/dashboard/plugins/weather/templates/weather/page.html b/dashboard/plugins/weather/templates/weather/page.html new file mode 100644 index 0000000..70a289f --- /dev/null +++ b/dashboard/plugins/weather/templates/weather/page.html @@ -0,0 +1,116 @@ +{% extends "base.html" %} +{% from "_header.html" import nav_btns, settings_btn, title_block, section_tabs %} +{% block title %}Weather · Dashboard{% endblock %} +{% block page %} +
    {# the grid's "head" area: the bar + the sub-heading under it #} +
    + {{ nav_btns() }} + {% set cur = v.tabs | selectattr("on") | first %} + {{ title_block("Weather", "/weather" ~ (("?loc=" ~ cur.idx) if cur and cur.idx else "")) }} + {{ settings_btn("weather") }} +
    +
    + {% if v.tabs|length > 1 %}{# the place: click → the other places (no browser dialogs) #} +
    {{ v.location }} ▾ +
    {% for t in v.tabs %}{{ t.name }}{% endfor %}
    +
    {% else %}{{ v.location }}{% endif %}{% if v.updated %} · {{ v.updated }}{% endif %} · Open-Meteo +
    +{% if plugin_section("weather").tabs | length > 1 %}{{ section_tabs("weather", "/weather") }}{% endif %}{# Forecast | Stations #} +
    + +{% if v.status %} +
    Weather for {{ v.location }} could not be loaded ({{ v.status }}). Reload the page to try again.
    +{% else %} +{% set n = v.now %} +{# ---- left: now + its values, then the sun's arc | air quality (as the phone app) ---- #} +
    +
    +
    +
    +
    +
    {{ n.temp }}
    +
    {{ n.desc }}
    +
    feels {{ n.feels }} · {{ n.hl }}
    +
    +
    +
    + {% for g, value, tip, deg in n.stats %} +
    {% if g == "wind" %}{% else %}{{ g }}{% endif %}{{ value }}
    + {% endfor %} +
    +
    +
    + {% set s = n.sun %} +
    + + + {% if s.day %}{% endif %} + + {% if s.day %}{% endif %} + + +
    {{ s.daylight }}
    +
    ↑ {{ s.rise }}↓ {{ s.set }}
    +
    + {% if v.aq %}{% set a = v.aq %} +
    +
    Air quality
    +
    {{ a.aqi }}{{ a.label }}
    +
    +
    {% for name, val in a.parts[:2] %}{{ name }} {{ "%.0f" | format(val) }}{% if not loop.last %} · {% endif %}{% endfor %}
    +
    + {% endif %} +
    +
    + +{# ---- right top: next 48 hours ---- #} +{% set h = v.hourly %} +
    +
    Next 48 hours
    +
    TemperatureFeels likeRain chanceWind / gusts {{ v.spd_u }}
    +
    +
    + {% for t in h.ticks %}
    +
    {{ t.hour }}
    {% endfor %} +
    + + {% for d in h.days %} + {{ d.label }}{% endfor %} + + + {% for b in h.bars %}{% endfor %} + + + + {% for t in h.ticks %} + {{ t.temp }} + {% if t.rain >= 10 %}{{ t.rain }}%{% endif %}{% endfor %} + +
    + {% for w in h.wind %}
    + +
    {{ w.speed }}/{{ w.gust }}
    {% endfor %} +
    +
    +
    + +{# ---- right bottom: 14 days ---- #} +
    +
    14 days
    +
    + {% for d in v.days %} +
    +
    {{ d.label }}
    {{ d.date }}
    + +
    {{ d.hi }}
    +
    +
    {{ d.lo }}
    +
    {{ d.rain_p }}{{ d.rain_mm }} mm
    +
    {{ d.wind }}
    +
    UV {{ d.uv }}
    +
    + {% endfor %} +
    +
    +{% endif %} +{% endblock %} diff --git a/dashboard/plugins/weather/views.py b/dashboard/plugins/weather/views.py new file mode 100644 index 0000000..c726a24 --- /dev/null +++ b/dashboard/plugins/weather/views.py @@ -0,0 +1,203 @@ +"""View models of the weather plugin: the Home box (`home_box`) and the weather page +(`weather_page`) — plain dicts for the templates (moved here from the core's webview.py).""" +import math +from datetime import date, datetime + +from config import THEME +from panel import _day_label, _ordinal, disp_temp, temp_colour + +from .weather import daily_forecast, location_weather, today_weather, weather_locations, wmo_icon, wmo_text + +# the round droplet (cycle tracker's too) — humidity on the web pages; the font's 💧 is too tall +DROP = {"viewBox": "2 5 20 24", "d": "M12 5.6L18.72 12.28A9.5 9.5 0 1 1 5.28 12.28Z"} +COMPASS = ("N", "NE", "E", "SE", "S", "SW", "W", "NW") + + +# ---- Home ----------------------------------------------------------------------- + +def home_box(store, cur, fc): + """The Home's weather box (now, H / L, humidity, pressure, wind, the next 4 days).""" + if not cur: + return {"status": store.wx_status} + t, u = disp_temp(cur["main"]["temp"], store.units) + tw = today_weather(fc, store.units) + extras = [{"glyph": "💧", "svg": DROP, "text": f"{cur['main']['humidity']}%", "cls": "cool"}] + if cur["main"].get("pressure"): + extras.append({"glyph": "", "text": f"{cur['main']['pressure']} hPa", "cls": "muted"}) + wind = cur.get("wind") or {} + if wind.get("speed") is not None: + imperial = store.units == "imperial" + v = wind["speed"] * 2.237 if imperial else wind["speed"] + dirn = COMPASS[round((wind.get("deg") or 0) / 45) % 8] if "deg" in wind else "" + extras.append({"glyph": "🌬" if "deg" not in wind else "", "arrow": wind.get("deg"), # points where it blows + "text": f"{v:.0f} {'mph' if imperial else 'm/s'} {dirn}".rstrip(), "cls": "muted"}) + days = [dd for dd in daily_forecast(fc, store.units, days=6) if dd["label"] != "Today"][:4] + return { + "icon": cur["weather"][0]["icon"], "temp": f"{t:.0f}{u}", + "desc": cur["weather"][0]["description"].capitalize(), + "hl": f"H {tw[3]:.0f}° L {tw[2]:.0f}°" if tw else "", + "extras": extras, + "days": [{"label": _day_label(dd["date"], ordinal=True), "hi": f"{dd['hi']:.0f}°", + "lo": f"{dd['lo']:.0f}°", "icon": dd["icon"]} for dd in days], + } + + +# ---- weather page (/weather, Open-Meteo) ------------------------------------------------ + +AQI_BANDS = ((20, "Good", "#50f0e6"), (40, "Fair", "#50ccaa"), (60, "Moderate", "#f0e641"), + (80, "Poor", "#ff5050"), (100, "Very poor", "#c0305a"), (10**9, "Extremely poor", "#9b3ea0")) +UV_BANDS = ((3, "low"), (6, "moderate"), (8, "high"), (11, "very high"), (99, "extreme")) +HOURS = 48 +CHART_W, CHART_H = 1232, 300 # hourly chart viewBox + + +def _level(value, bands): + """First (limit, …) band whose limit is above value.""" + return next(b for b in bands if value < b[0]) + + +SUN_W, SUN_H = 300, 92 # the sun card's arc (viewBox) + + +def _sun(rise, set_, now, daylight): + """Sunrise → sunset as an arc over the horizon: the dashed path, the part gone (solid) and the sun + where it is now; f < 0 / > 1 = before sunrise / after sunset (no sun).""" + a, z = datetime.fromisoformat(rise), datetime.fromisoformat(set_) + t = datetime.fromisoformat(now) if now else datetime.now() + f = (t - a).total_seconds() / max(1, (z - a).total_seconds()) + cx, cy, rx, ry = SUN_W / 2, SUN_H - 4, SUN_W / 2 - 8, SUN_H - 22 + out = {"rise": rise[11:16], "set": set_[11:16], "w": SUN_W, "h": SUN_H, + "daylight": f"{int(daylight // 3600)} h {int(daylight % 3600 // 60):02d} min", + "path": f"M{cx - rx},{cy} A{rx},{ry} 0 0 1 {cx + rx},{cy}", "x0": cx - rx, "x1": cx + rx, "y": cy, "day": 0 < f < 1} + if 0 < f < 1: + ang = math.pi + math.pi * f + sx, sy = cx + rx * math.cos(ang), cy + ry * math.sin(ang) + left = z - t + out.update(sx=round(sx, 1), sy=round(sy, 1), gone=f"M{cx - rx},{cy} A{rx},{ry} 0 0 1 {sx:.1f},{sy:.1f}", + glow=f"M{cx - rx},{cy} A{rx},{ry} 0 0 1 {sx:.1f},{sy:.1f} L{sx:.1f},{cy} Z", + left=f"{int(left.total_seconds() // 3600)} h {int(left.total_seconds() % 3600 // 60):02d} min of daylight left") + else: + out["left"] = "The sun has set" if f >= 1 else "Before sunrise" + return out + + +def _hm(iso): + return iso[11:16] if iso and len(iso) >= 16 else "—" + + +def weather_page(store, loc=0): + locs = weather_locations(store.cfg) + loc = loc if 0 <= loc < len(locs) else 0 + om, air, status = location_weather(store, loc) + tabs = [{"label": l["name"].split(",")[0], "name": l["name"], "idx": i, "on": i == loc} for i, l in enumerate(locs)] + if not om: + return {"status": status, "tabs": tabs, "location": locs[loc]["name"]} + units = store.units + T = lambda c: disp_temp(c, units)[0] if c is not None else None # °C -> display + unit = disp_temp(0, units)[1] + imperial = units == "imperial" + spd = lambda ms: (ms * 2.237 if imperial else ms) if ms is not None else None + spd_u = "mph" if imperial else "m/s" + cur, h, dly = om.get("current", {}), om["hourly"], om["daily"] + + # ---- now + details + today = dly + rain_today = today["precipitation_sum"][0] + uv = cur.get("uv_index") or 0 + deg = cur.get("wind_direction_10m") or 0 + vis = cur.get("visibility") + dl = today["daylight_duration"][0] or 0 + now = { + "icon": wmo_icon(cur.get("weather_code"), cur.get("is_day", 1)), + "temp": f"{T(cur['temperature_2m']):.0f}{unit}", + "feels": f"{T(cur['apparent_temperature']):.0f}°", + "desc": wmo_text(cur.get("weather_code")), + "hl": f"H {T(today['temperature_2m_max'][0]):.0f}° · L {T(today['temperature_2m_min'][0]):.0f}°", + "stats": [ # (glyph, value, hover) — the phone app's "now" card, details on hover + ("wind", f"{spd(cur.get('wind_speed_10m')):.0f} {spd_u}", + f"Wind {COMPASS[round(deg / 45) % 8]}, gusts {spd(cur.get('wind_gusts_10m')):.0f} {spd_u} — the arrow points where it blows", deg), + ("💧", f"{cur.get('relative_humidity_2m', 0):.0f}%", "Humidity", None), + ("⏲", f"{cur.get('pressure_msl', 0):.0f}", "Pressure, hPa", None), + ("☀", f"UV {uv:.0f}", f"UV index {uv:.0f} — {_level(uv, UV_BANDS)[1]} (today's top {today['uv_index_max'][0] or 0:.0f})", None), + ("☁", f"{cur.get('cloud_cover', 0):.0f}%", "Cloud cover", None), + ("👁", f"{vis / 1000:.0f} km" if vis is not None else "—", "Visibility", None), + ("☂", f"{rain_today:.1f} mm", f"Rain today · chance {today['precipitation_probability_max'][0] or 0:.0f}%", None), + ("🌡", f"{T(cur.get('dew_point_2m')):.0f}°", "Dew point", None), + ], + "temp_colour": temp_colour(cur["temperature_2m"]), + } + + # ---- the sun's arc (the place's own time) + air quality on its scale (pollen dropped 2026-10-21) + now["sun"] = _sun(today["sunrise"][0], today["sunset"][0], cur.get("time"), dl) + aq = None + if air and air.get("current"): + a = air["current"] + eaqi = a.get("european_aqi") or 0 + _, label, colour = _level(eaqi, AQI_BANDS) + aq = {"aqi": f"{eaqi:.0f}", "label": label, "colour": colour, "pct": round(min(eaqi, 100), 1), + "stops": ", ".join(c for _, _, c in AQI_BANDS[:5]), + "parts": [(n, a.get(k)) for k, n in (("pm2_5", "PM2.5"), ("pm10", "PM10"), + ("ozone", "O₃"), ("nitrogen_dioxide", "NO₂")) + if a.get(k) is not None]} + + # ---- next 48 hours (from the current hour — in the place's own time zone) + stamp = (cur.get("time") or datetime.now().strftime("%Y-%m-%dT%H:%M"))[:13] + ":00" + i0 = next((i for i, t in enumerate(h["time"]) if t >= stamp), 0) + idx = list(range(i0, min(i0 + HOURS, len(h["time"])))) + temps = [h["temperature_2m"][i] for i in idx] + feels = [h["apparent_temperature"][i] for i in idx] + lo, hi = min(temps + feels) - 1, max(temps + feels) + 1 + xs = lambda k: round(24 + k * (CHART_W - 48) / max(1, len(idx) - 1), 1) + ty = lambda c: round(34 + (hi - c) / (hi - lo) * 150, 1) # temp band: y 34..184 + bar_top, bar_h = 206, 84 # rain band: y 206..290 + hourly = {"temp": " ".join(f"{xs(k)},{ty(c)}" for k, c in enumerate(temps)), + "feels": " ".join(f"{xs(k)},{ty(c)}" for k, c in enumerate(feels)), + "area": f"{xs(0)},184 " + " ".join(f"{xs(k)},{ty(c)}" for k, c in enumerate(temps)) + f" {xs(len(idx) - 1)},184", + "bars": [], "ticks": [], "days": [], "wind": []} + bw = (CHART_W - 48) / max(1, len(idx) - 1) * 0.7 + for k, i in enumerate(idx): + p = h["precipitation_probability"][i] or 0 + mm = h["precipitation"][i] or 0 + hgt = round(p / 100 * bar_h, 1) + hourly["bars"].append({"x": round(xs(k) - bw / 2, 1), "w": round(bw, 1), "y": round(bar_top + bar_h - hgt, 1), + "h": hgt, "mm": mm}) + hh = int(h["time"][i][11:13]) + if hh == 0 and k: + d = datetime.fromisoformat(h["time"][i]) + hourly["days"].append({"x": xs(k), "label": f"{d:%a}"[:2] + " " + _ordinal(d.day)}) + if k % 3 == 0: + hourly["ticks"].append({"x": xs(k), "y": ty(temps[k]), "hour": f"{hh:02d}", + "temp": f"{T(temps[k]):.0f}°", "rain": p, + "icon": wmo_icon(h["weather_code"][i], h["is_day"][i])}) + hourly["wind"].append({"x": xs(k), "deg": h["wind_direction_10m"][i] or 0, + "speed": f"{spd(h['wind_speed_10m'][i]):.0f}", + "gust": f"{spd(h['wind_gusts_10m'][i]):.0f}"}) + + # ---- 14 days + n = min(14, len(dly["time"])) + dmin = min(dly["temperature_2m_min"][:n]) - 1 + dmax = max(dly["temperature_2m_max"][:n]) + 1 + days = [] + for i in range(n): + d = date.fromisoformat(dly["time"][i]) + tmin, tmax = dly["temperature_2m_min"][i], dly["temperature_2m_max"][i] + days.append({ + "label": "Today" if i == 0 else f"{d:%a}"[:2], "date": _ordinal(d.day) if i else "", + "weekend": d.weekday() >= 5, "icon": wmo_icon(dly["weather_code"][i], True), + "desc": wmo_text(dly["weather_code"][i]), + "hi": f"{T(tmax):.0f}°", "lo": f"{T(tmin):.0f}°", + # vertical range bar: % from the top of the bar track, coloured by temperature band + "top": round((dmax - tmax) / (dmax - dmin) * 100, 1), + "bottom": round((dmax - tmin) / (dmax - dmin) * 100, 1), + "c_hi": temp_colour(tmax), "c_lo": temp_colour(tmin), + "rain_p": f"{dly['precipitation_probability_max'][i] or 0:.0f}%", + "rain_mm": f"{dly['precipitation_sum'][i] or 0:.1f}", + "wind": f"{spd(dly['wind_speed_10m_max'][i]):.0f}", + "deg": dly["wind_direction_10m_dominant"][i] or 0, + "uv": f"{dly['uv_index_max'][i] or 0:.0f}", + }) + st = status or "" + return {"location": locs[loc]["name"], "tabs": tabs, + "updated": "updated " + st[5:] if st.startswith("ok · ") else st, + "now": now, "aq": aq, "hourly": hourly, "days": days, "unit": unit, + "spd_u": spd_u, "chart_w": CHART_W, "chart_h": CHART_H} diff --git a/dashboard/plugins/weather/weather.py b/dashboard/plugins/weather/weather.py new file mode 100644 index 0000000..75d6452 --- /dev/null +++ b/dashboard/plugins/weather/weather.py @@ -0,0 +1,321 @@ +"""Weather: Open-Meteo for everything (`openmeteo_worker`, every 15 min, metric — the °C/°F +toggle is display-only), converted for Home / the 3.5" screen / backlight by `owm_shape`; +the last good data saved to disk (`load_cache`). The icons are Meteocons (MIT) in icons/, one PNG per +OpenWeatherMap-style code that the WMO codes map onto (tools/weather-icons.py makes them; the app has the same). +""" +import json +import os +import threading +import time +import urllib.parse +import urllib.request +from datetime import date, datetime + +from PIL import Image + +from config import WEATHER_CACHE +from panel import disp_temp + + +_ICON_MEM = {} + + +ICONS = os.path.join(os.path.dirname(os.path.abspath(__file__)), "icons") + + +def load_icon(code, size): + if not code: + return None + key = (code, size) + if key in _ICON_MEM: + return _ICON_MEM[key] + path = os.path.join(ICONS, f"{code}.png") + if not os.path.exists(path): + return None + try: + im = Image.open(path).convert("RGBA").resize((size, size), Image.LANCZOS) + _ICON_MEM[key] = im + return im + except Exception: + return None + + +_TRIMMED = {} + + +def trimmed_icon(code, height): + """An icon with any transparent margin cut off, scaled to `height` (the web pages' /icon/.png).""" + if (code, height) not in _TRIMMED: + im = load_icon(code, 200) + if im is None: + return None + bbox = im.getchannel("A").point(lambda a: 255 if a > 24 else 0).getbbox() + if bbox: + im = im.crop(bbox) + k = height / im.height + _TRIMMED[(code, height)] = im.resize((round(im.width * k), round(im.height * k)), Image.LANCZOS) + return _TRIMMED[(code, height)] + + +def today_weather(fc, units): + """(icon, description, lo, hi) over the next ~24h, or None. + + Uses a rolling 24h window (next 8 three-hourly slots) rather than only the + slots dated 'today' — otherwise, late in the day few slots remain and the + high/low collapse to the same value. This way L is the upcoming night. + """ + if not fc: + return None + window = fc[:8] + temps = [i["main"]["temp"] for i in window] + rep = min(window, key=lambda i: abs(datetime.fromtimestamp(i["dt"]).hour - 13)) + return (rep["weather"][0]["icon"], rep["weather"][0]["description"], + disp_temp(min(temps), units)[0], disp_temp(max(temps), units)[0]) + + +def daily_forecast(fc, units, days=5): + """Aggregate the 3-hourly forecast into per-day {label, lo, hi, icon}.""" + by_day = {} + for it in fc: + by_day.setdefault(datetime.fromtimestamp(it["dt"]).date(), []).append(it) + out, today = [], date.today() + for dday, items in by_day.items(): + pool = fc[:8] if dday == today else items # 24h window for today -> real hi/lo + temps = [i["main"]["temp"] for i in pool] + rep = min(pool, key=lambda i: abs(datetime.fromtimestamp(i["dt"]).hour - 13)) + out.append({ + "label": "Today" if dday == today else dday.strftime("%a"), + "date": dday, + "lo": disp_temp(min(temps), units)[0], + "hi": disp_temp(max(temps), units)[0], + "icon": rep["weather"][0]["icon"], + }) + if len(out) >= days: + break + return out + + +# ---- the last good weather on disk ------------------------------------------------------- +# +# Every successful fetch (Open-Meteo, main place + extra places) is saved to +# dash_weather.json; at start-up load_cache() puts it back, so after a restart without +# internet the pages show the last weather (status "saved · HH:MM") instead of nothing. + +_cache_lock = threading.Lock() + + +def _save_cache(part, value): + """Store one part ({"t": time, …}) of the cache file, atomically.""" + with _cache_lock: + try: + with open(WEATHER_CACHE) as f: + data = json.load(f) + except Exception: + data = {} + data[part] = value + tmp = WEATHER_CACHE + ".tmp" + try: + with open(tmp, "w") as f: + json.dump(data, f) + os.replace(tmp, WEATHER_CACHE) + except OSError as e: + print(f"weather: cache not saved: {e}", flush=True) + + +def load_cache(store): + """Put the saved weather back (before the workers start).""" + try: + with open(WEATHER_CACHE) as f: + data = json.load(f) + except Exception: + return + at = lambda t: "saved · " + datetime.fromtimestamp(t).strftime("%d %b %H:%M") + if data.get("om"): + o = data["om"] + store.om, store.om_air, store.om_status = o["fc"], o.get("air"), at(o["t"]) + store.wx_current, store.wx_forecast = owm_shape(o["fc"]) + store.wx_status = store.om_status + names = [p.get("name") for p in weather_locations(store.cfg)] + for name, o in (data.get("extra") or {}).items(): + if name in names[1:]: + _OM_EXTRA[names.index(name)] = (o["t"], o["fc"], o.get("air")) + + +# ---- Open-Meteo: all the weather ----------------------------------------------------- +# +# Free, no key: hourly data for 16 days + daily summaries, and (separate endpoint) +# air quality for Europe. The web weather page uses it as is; Home, the 3.5" +# screen and the screen brightness get it converted to OpenWeatherMap's old shapes +# (owm_shape → store.wx_current / wx_forecast). (OpenWeatherMap itself was dropped +# 2026-10-18; its icon PNGs are still used, downloaded from its image server, no key.) + +OM_FORECAST = "https://api.open-meteo.com/v1/forecast" +OM_AIR = "https://air-quality-api.open-meteo.com/v1/air-quality" +OM_HOURLY = ("temperature_2m,apparent_temperature,relative_humidity_2m,dew_point_2m," + "precipitation_probability,precipitation,snowfall,weather_code,cloud_cover,visibility," + "wind_speed_10m,wind_gusts_10m,wind_direction_10m,uv_index,is_day,pressure_msl") +OM_DAILY = ("weather_code,temperature_2m_max,temperature_2m_min,apparent_temperature_max," + "apparent_temperature_min,sunrise,sunset,daylight_duration,uv_index_max,precipitation_sum," + "precipitation_probability_max,precipitation_hours,wind_speed_10m_max,wind_gusts_10m_max," + "wind_direction_10m_dominant") +OM_CURRENT = ("temperature_2m,apparent_temperature,relative_humidity_2m,dew_point_2m,weather_code," + "is_day,cloud_cover,pressure_msl,wind_speed_10m,wind_gusts_10m,wind_direction_10m," + "precipitation,visibility,uv_index") +OM_AIR_CURRENT = "european_aqi,pm10,pm2_5,ozone,nitrogen_dioxide" # (pollen dropped 2026-10-21) +OM_REFRESH, OM_RETRY = 900, 600 # seconds (Home's "now" comes from here too) + +# WMO weather code -> (icon code: icons/d|n.png, the app's assets/weather/ too; description) +WMO = { + 0: ("01", "Clear sky"), 1: ("02", "Mainly clear"), 2: ("03", "Partly cloudy"), 3: ("04", "Overcast"), + 45: ("50", "Fog"), 48: ("50", "Rime fog"), + 51: ("09", "Light drizzle"), 53: ("09", "Drizzle"), 55: ("09", "Dense drizzle"), + 56: ("09", "Freezing drizzle"), 57: ("09", "Freezing drizzle"), + 61: ("10", "Light rain"), 63: ("10", "Rain"), 65: ("10", "Heavy rain"), + 66: ("10", "Freezing rain"), 67: ("10", "Freezing rain"), + 71: ("13", "Light snow"), 73: ("13", "Snow"), 75: ("13", "Heavy snow"), 77: ("13", "Snow grains"), + 80: ("09", "Light showers"), 81: ("09", "Showers"), 82: ("09", "Violent showers"), + 85: ("13", "Snow showers"), 86: ("13", "Heavy snow showers"), + 95: ("11", "Thunderstorm"), 96: ("11", "Thunderstorm, hail"), 99: ("11", "Thunderstorm, heavy hail"), +} + + +def wmo_icon(code, is_day=True): + """WMO code -> icon code ('10d'): icons/10d.png, /icon/10d.png.""" + return WMO.get(int(code or 0), ("03", ""))[0] + ("d" if is_day else "n") + + +def wmo_text(code): + return WMO.get(int(code or 0), ("", "—"))[1] + + +def _om_get(base, params): + with urllib.request.urlopen(f"{base}?{urllib.parse.urlencode(params)}", timeout=20) as r: + return json.load(r) + + +def owm_shape(fc): + """Open-Meteo forecast → the shapes Home, the 3.5" screen and backlight.py were built on + (OpenWeatherMap's): (current {main, weather, wind, sys}, [3-hourly {dt, main, weather}]).""" + cur, h, d = fc.get("current") or {}, fc.get("hourly") or {}, fc.get("daily") or {} + ts = lambda iso: datetime.fromisoformat(iso).timestamp() if iso else None + now = { + "dt": ts(cur.get("time")) or time.time(), + "main": {"temp": cur.get("temperature_2m"), "feels_like": cur.get("apparent_temperature"), + "humidity": round(cur.get("relative_humidity_2m") or 0), + "pressure": round(cur["pressure_msl"]) if cur.get("pressure_msl") else None}, + "weather": [{"icon": wmo_icon(cur.get("weather_code"), cur.get("is_day", 1)), + "description": wmo_text(cur.get("weather_code")).lower()}], + "wind": {"speed": cur.get("wind_speed_10m"), "deg": cur.get("wind_direction_10m")}, + "sys": {"sunrise": ts((d.get("sunrise") or [None])[0]), "sunset": ts((d.get("sunset") or [None])[0])}, + } + if now["wind"]["deg"] is None: + del now["wind"]["deg"] + out, start = [], time.time() - 3600 + times = h.get("time") or [] + for i, t in enumerate(times): + dt = ts(t) + if dt < start or datetime.fromtimestamp(dt).hour % 3: + continue + code = h["weather_code"][i] + out.append({"dt": dt, "main": {"temp": h["temperature_2m"][i]}, + "weather": [{"icon": wmo_icon(code, h.get("is_day", [1] * len(times))[i]), + "description": wmo_text(code).lower()}]}) + if len(out) >= 44: # 5.5 days of 3-hourly slots, like OWM's forecast + break + return now, out + + +def openmeteo_fetch(lat, lon): + """(forecast, air quality or None) for one place, metric, wind in m/s, local time.""" + fc = _om_get(OM_FORECAST, {"latitude": lat, "longitude": lon, "hourly": OM_HOURLY, + "daily": OM_DAILY, "current": OM_CURRENT, "timezone": "auto", + "forecast_days": 16, "wind_speed_unit": "ms"}) + try: + air = _om_get(OM_AIR, {"latitude": lat, "longitude": lon, "current": OM_AIR_CURRENT, + "timezone": "auto"}) + except Exception: + air = None # optional: the page just leaves the block out + return fc, air + + +def weather_locations(cfg): + """[{name, lat, lon}] — the main location (location_name / lat / lon, the one Home + shows) first, then `weather_locations` from the config (web weather page only).""" + main = {"name": cfg.get("location_name") or "Home", "lat": cfg.get("lat"), "lon": cfg.get("lon")} + return [main] + [l for l in cfg.get("weather_locations") or [] if "lat" in l and "lon" in l] + + +_OM_EXTRA = {} # location index -> (fetched at, forecast, air) +_OM_EXTRA_LOCK = None + + +def forget_places(): + """Settings changed the extra places: drop what was fetched for the old list.""" + _OM_EXTRA.clear() + + +def location_weather(store, idx): + """(forecast, air, status) for location idx: 0 = the main one (kept fresh by + openmeteo_worker), others fetched on demand and cached for OM_REFRESH.""" + global _OM_EXTRA_LOCK + locs = weather_locations(store.cfg) + if idx <= 0 or idx >= len(locs): + with store.lock: + return store.om, store.om_air, store.om_status + if _OM_EXTRA_LOCK is None: + import threading + _OM_EXTRA_LOCK = threading.Lock() + with _OM_EXTRA_LOCK: + hit = _OM_EXTRA.get(idx) + if hit is None or time.time() - hit[0] > OM_REFRESH: + err = None + for attempt in (1, 2): # one quick retry: a dropped connection is common + try: + fc, air = openmeteo_fetch(locs[idx]["lat"], locs[idx]["lon"]) + hit = _OM_EXTRA[idx] = (time.time(), fc, air) + _save_extra(store) + err = None + break + except Exception as e: + err = e + if err is not None: + print(f"open-meteo: {locs[idx].get('name')}: {type(err).__name__}: {err}", flush=True) + if hit is None: + return None, None, f"{type(err).__name__}: {err}"[:120] + return hit[1], hit[2], "ok · " + datetime.fromtimestamp(hit[0]).strftime("%H:%M") + + +def _save_extra(store): + names = [p.get("name") for p in weather_locations(store.cfg)] + _save_cache("extra", {names[i]: {"t": t, "fc": fc, "air": air} + for i, (t, fc, air) in list(_OM_EXTRA.items()) if 0 < i < len(names)}) + + +def openmeteo_worker(store): + """Main location's forecast + air quality every 15 min into store.om / store.om_air, and + (converted) store.wx_current / wx_forecast for Home.""" + cfg = store.cfg + while True: + lat, lon = cfg.get("lat"), cfg.get("lon") # settings may change + ok = False + try: + fc, air = openmeteo_fetch(lat, lon) + cur, three_hourly = owm_shape(fc) + with store.lock: + store.om, store.om_air = fc, air or store.om_air + store.wx_current, store.wx_forecast = cur, three_hourly + store.om_status = store.wx_status = "ok · " + datetime.now().strftime("%H:%M") + _save_cache("om", {"t": time.time(), "fc": fc, "air": store.om_air}) + ok = True + except Exception as e: + store.om_status = f"{type(e).__name__}: {e}"[:120] + if store.wx_current: # Home keeps the last good weather + store.wx_status = "offline · last " + (store.wx_status.split("· ")[-1] if "·" in store.wx_status else "") + else: + store.wx_status = "offline" + print(f"open-meteo: main location: {store.om_status}", flush=True) + # the other places too, so their tabs always have recent values (no fetch on click) + for idx in range(1, len(weather_locations(cfg))): + location_weather(store, idx) + store.om_wake.wait(timeout=OM_REFRESH if ok else OM_RETRY) + store.om_wake.clear() diff --git a/dashboard/plugins/workload/__init__.py b/dashboard/plugins/workload/__init__.py new file mode 100644 index 0000000..d53c095 --- /dev/null +++ b/dashboard/plugins/workload/__init__.py @@ -0,0 +1,243 @@ +"""Workload tracker: time per customer, booked like calendar events. + + /work week view: drag on a day to book time, click a block to edit, + drag it to move, its bottom edge to resize (?w=N other weeks) + /work/customers -> Settings ▸ Work (/settings#work), where the customers live: + sub-customers, projects, tasks, rates (with history), billable + default, currency, colour, notes, archive (_settings.html) + /work/report hours + money for a range, as a tree + the entries; .csv export + /work/api/… JSON writes (same-origin only, like the core's) + +Data: dash_data/workload/workload.db (SQLite, see db.py). Talks to the dashboard only +through `ctx` (pluginhost.Context): its settings, its data path, the calendar events +shown faintly behind the week (click one to book it), and — while the Activity plugin is on +and the week's "Activity" box is ticked (cookie work_act, per browser) — Activity's sorted +blocks in a lane beside the bookings (ask "activity" "blocks"; click one to book it). +""" +import csv +import io +import os +import time +from contextlib import closing +from datetime import date, timedelta + +from flask import Response, abort, jsonify, redirect, render_template, request + +from . import db, phone, views + +META = { + "title": "Workload tracker", + "glyph": "⏱", + "glyph_color": "#c08a5a", + "glyph_svg": {"viewBox": "-12 -12 24 24", "d": "M-8 -5 H8 A2 2 0 0 1 10 -3 V7 A2 2 0 0 1 8 9 H-8 A2 2 0 0 1 -10 7 V-3 A2 2 0 0 1 -8 -5 Z M-4.5 -5 V-8 A1.5 1.5 0 0 1 -3 -9.5 H3 A1.5 1.5 0 0 1 4.5 -8 V-5 H2.5 V-7.5 H-2.5 V-5 Z"}, # a briefcase + "description": "Book time per customer, project and task in a week view, billable or not, " + "with hourly rates that sub-customers, projects and tasks can override.", + "links": [{"label": "Open the tracker", "href": "/work"}, {"label": "Report", "href": "/work/report"}], + "settings": [ + {"key": "currency", "label": "Default currency", "type": "text", "default": "EUR", "max": 3, + "pattern": "[A-Za-z]{3}", "pattern_help": "A 3-letter code like EUR or RON.", + "help": "Customers can set their own; sub-customers, projects and tasks inherit it."}, + {"key": "default_rate", "label": "Default hourly rate (when no customer sets one)", "type": "number", + "default": 0, "min": 0, "max": 100000}, + {"key": "day_start", "label": "Focus hours: from", "type": "select", "default": 7, + "options": [[h, f"{h:02d}:00"] for h in range(0, 13)]}, + {"key": "day_end", "label": "… to", "type": "select", "default": 19, + "options": [[h, f"{h:02d}:00"] for h in range(12, 25)], + "help": "The week shows all 24 hours and opens scrolled to these. On a screen at least " + "1080 px tall they fill the window; the rest is a scroll away."}, + {"key": "default_minutes", "label": "A click books", "type": "select", "default": 60, + "options": [[15, "15 minutes"], [30, "30 minutes"], [45, "45 minutes"], [60, "1 hour"], + [90, "1½ hours"], [120, "2 hours"]]}, + {"key": "week_target", "label": "Hours per week (progress bar; 0 = off)", "type": "number", + "default": 40, "min": 0, "max": 168, "integer": True}, + {"key": "show_calendar", "label": "Show calendar events behind the week (click one to book it)", + "type": "bool", "default": True}, + ], + # what syncs between devices (sync.py / syncdb.py): the customer tree (parents first), its rates + # (by node + date: they're rewritten on every save), the entries + "sync": {"workload.db": { + "node": {"refs": {"parent_id": "node"}}, + "rate": {"key": "(SELECT _uid FROM node WHERE id = NEW.node_id) || ':' || NEW.since", "refs": {"node_id": "node"}}, + "entry": {"refs": {"node_id": "node"}}, + }, "phone.db": phone.SYNC}, # for the app's week: calendar events + Activity's blocks (phone.py) +} + + +def validate_settings(sec): + if int(sec.get("day_end", 19)) <= int(sec.get("day_start", 8)): + return "day_end", "The day must end after it starts." + sec["currency"] = (sec.get("currency") or "EUR").upper() + return None + + +def register(ctx): + bp = ctx.blueprint("/work") + ctx.warm("/work", "/work/report") # kept built / templates compiled in the background (pluginhost) + ctx.nav("Work", "/work") + here = os.path.dirname(os.path.abspath(__file__)) + + @bp.context_processor + def asset_version(): # cache-buster for workload.css / .js + st = os.path.join(here, "static") + return {"asset_v": "%x" % int(max(os.path.getmtime(os.path.join(st, f)) for f in os.listdir(st)))} + + # the app's week can't make these itself: the primary dashboard keeps them fresh in phone.db (synced) + phone_db = ctx.data_path("phone.db") + phone.create(phone_db) + + def phone_watch(_ctx): + time.sleep(90) # after the calendar's first sync + while True: + if ctx.enabled and ctx.primary(): + try: + with ctx.as_owner(): # every calendar (it's the owner's phone), not the household's + res = phone.refresh(phone_db, ctx.events_between, + lambda d0, d1: ctx.ask("activity", "blocks", d0, d1)) + if any(sum(v) for v in res.values()): + print(f"workload: phone rows {res}", flush=True) + except Exception as e: + print(f"workload: phone rows failed: {e}", flush=True) + time.sleep(phone.EVERY) + ctx.worker(phone_watch) + + def con(): # one connection per request, closed after + return closing(db.connect(ctx.data_path("workload.db"))) + + def tree(c): + s = ctx.settings + return db.Tree(c, s["default_rate"], s["currency"]) + + def body(): + if not ctx.same_origin(): + abort(403) + return request.get_json(silent=True) or {} + + def fail(e): + return jsonify(error=str(e), field=e.field), 400 + + # ---- pages + @bp.route("/", strict_slashes=False) # /work too, no redirect + def week(): + try: + offset = max(-520, min(520, int(request.args.get("w", 0)))) + except ValueError: + offset = 0 + s = ctx.settings + ws = views.week_start(offset) + events = ctx.events_between(ws, ws + timedelta(days=7)) if s["show_calendar"] else [] + act_on = any(h == "/activity" for h, _ in ctx.section()["tabs"]) + show_act = act_on and request.cookies.get("work_act") == "1" + acts = (ctx.ask("activity", "blocks", ws.date(), ws.date() + timedelta(days=6)) or {}) if show_act else None + with con() as c: + t = tree(c) + v = views.week(c, t, s, offset, events, ctx.day_bands, acts) + data = {"entries": v["entries"], "nodes": views.node_list(t, date.today()), + "recent": db.recent(c, t), "h0": v["h0"], "h1": v["h1"], "focus": v["focus"], + "minutes": int(s["default_minutes"]), "currency": s["currency"], + "default_rate": float(s["default_rate"] or 0)} + return render_template("workload/week.html", v=v, data=data, page="work", tab="week", act_on=act_on, show_act=show_act) + + def customers_panel(): # Settings ▸ Work, under the plugin's fields + st = os.path.join(here, "static") + with con() as c: + t = tree(c) + v = views.customers(c, t, bool(request.args.get("archived"))) + return {"v": v, "palette": db.PALETTE, "default_currency": ctx.settings["currency"], + "asset_v": "%x" % int(max(os.path.getmtime(os.path.join(st, f)) for f in os.listdir(st)))} + ctx.settings_panel("workload/_settings.html", customers_panel) + + @bp.route("/customers") + def customers(): # old address (bookmarks): the editor is in Settings + return redirect("/settings#work") + + def _range(): + p = request.args.get("p") or ("custom" if request.args.get("from") else "month") + rng = views.preset_range(p) + if not rng: + try: + rng = (date.fromisoformat(request.args.get("from", "")), date.fromisoformat(request.args.get("to", ""))) + except ValueError: + p, rng = "month", views.preset_range("month") + frm, to = rng + if to < frm: + frm, to = to, frm + try: + client = int(request.args.get("c") or 0) or None + except ValueError: + client = None + return p, frm, to, client + + @bp.route("/report") + @ctx.cached_page("workload.db") + def report(): + p, frm, to, client = _range() + with con() as c: + t = tree(c) + v = views.report(c, t, frm, to, client) + clients = [{"id": n["id"], "label": " " * d + n["name"]} for n, d in t.walk(include_archived=True) + if n["kind"] == "client"] + return render_template("workload/report.html", v=v, page="work", tab="report", preset=p, + presets=views.PRESETS, frm=frm, to=to, client=client, clients=clients, + qs=request.query_string.decode()) + + @bp.route("/report.csv") + def report_csv(): + p, frm, to, client = _range() + with con() as c: + v = views.report(c, tree(c), frm, to, client) + buf = io.StringIO() + w = csv.writer(buf) + w.writerow(["date", "start", "end", "hours", "customer / project / task", "billable", "rate", + "amount", "currency", "note"]) + for i in v["entries"]: + w.writerow([i["iso"], i["start"][11:], i["end"][11:], f"{i['minutes'] / 60:.2f}", i["path"], + "yes" if i["billable"] else "no", i["rate"], f"{i['amount_raw']:.2f}" if i["billable"] else "", + i["currency"], i["note"]]) + return Response("" + buf.getvalue(), mimetype="text/csv", # BOM: Excel / LibreOffice read UTF-8 + headers={"Content-Disposition": f'attachment; filename="work-{frm}-{to}.csv"'}) + + # ---- writes + @bp.route("/api/entry", methods=["POST"]) + def api_entry(): + d = body() + with con() as c: + try: + return jsonify(id=db.save_entry(c, tree(c), d)) + except db.Invalid as e: + return fail(e) + + @bp.route("/api/entry/move", methods=["POST"]) + def api_move(): + d = body() + with con() as c: + try: + return jsonify(ok=db.move_entry(c, int(d.get("id") or 0), str(d.get("start")), str(d.get("end")))) + except (db.Invalid, ValueError) as e: + return jsonify(error=str(e)), 400 + + @bp.route("/api/entry/delete", methods=["POST"]) + def api_entry_delete(): + d = body() + with con() as c: + return jsonify(ok=db.delete_entry(c, int(d.get("id") or 0))) + + @bp.route("/api/node", methods=["POST"]) + def api_node(): + d = body() + with con() as c: + try: + return jsonify(id=db.save_node(c, tree(c), d)) + except db.Invalid as e: + return fail(e) + + @bp.route("/api/node/delete", methods=["POST"]) + def api_node_delete(): + d = body() + with con() as c: + t = tree(c) + nid = int(d.get("id") or 0) + if nid not in t.nodes: + return jsonify(ok=True) + if not db.delete_node(c, t, nid): + return jsonify(ok=False, error="Time is booked on it — archive it instead."), 409 + return jsonify(ok=True) diff --git a/dashboard/plugins/workload/db.py b/dashboard/plugins/workload/db.py new file mode 100644 index 0000000..ea5ff07 --- /dev/null +++ b/dashboard/plugins/workload/db.py @@ -0,0 +1,355 @@ +"""Workload tracker storage: one SQLite file (dash_data/workload/workload.db). + +Everything you can book time on is a **node** in one tree: + + client a customer (parent NULL) or a sub-customer (parent = a client) + project under a client or sub-customer + task under a client / sub-customer, or under a project + +A time **entry** points at the most specific node it was done for. The settings +that can differ per level — hourly rate, billable or not, currency, colour — are +stored only where they are set (NULL = inherit) and resolved by walking up the +tree, so an "exception" (a sub-customer, project or task with its own rate) is +simply a node that sets one. + +Rates have a history (`rate` rows with a `since` day): the rate for a piece of +work is the one in force on the day it was done, so raising a rate in January +doesn't rewrite last year's invoices, while correcting a typo (editing the row) +does fix everything it covers. +""" +import os +import sqlite3 +import threading +from datetime import datetime, timedelta + +KINDS = ("client", "project", "task") +PARENTS = {"client": (None, "client"), "project": ("client",), "task": ("client", "project")} +PALETTE = ("#ffb33a", "#5cc8ff", "#7fd6a3", "#ff6b7a", "#c792ea", "#ff9d5c", "#82aaff", "#f78c6c", + "#c3e88d", "#89ddff") +EPOCH = "0000-01-01" # a rate "since" this applies to all work, any date + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS node ( + id INTEGER PRIMARY KEY, + kind TEXT NOT NULL CHECK (kind IN ('client', 'project', 'task')), + parent_id INTEGER REFERENCES node(id), + name TEXT NOT NULL, + colour TEXT, -- NULL = inherit (top-level clients always have one) + billable INTEGER, -- NULL = inherit, 0 / 1 + currency TEXT, -- NULL = inherit + notes TEXT NOT NULL DEFAULT '', + archived INTEGER NOT NULL DEFAULT 0, + created TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS node_parent ON node(parent_id); +CREATE TABLE IF NOT EXISTS rate ( + id INTEGER PRIMARY KEY, + node_id INTEGER NOT NULL REFERENCES node(id) ON DELETE CASCADE, + since TEXT NOT NULL, -- YYYY-MM-DD, EPOCH = always + rate REAL NOT NULL, -- per hour + UNIQUE (node_id, since) +); +CREATE TABLE IF NOT EXISTS entry ( + id INTEGER PRIMARY KEY, + node_id INTEGER NOT NULL REFERENCES node(id), + start TEXT NOT NULL, -- local time, 'YYYY-MM-DD HH:MM' + end TEXT NOT NULL, + billable INTEGER NOT NULL, + note TEXT NOT NULL DEFAULT '', + created TEXT NOT NULL, + updated TEXT NOT NULL +); +CREATE INDEX IF NOT EXISTS entry_start ON entry(start); +CREATE INDEX IF NOT EXISTS entry_node ON entry(node_id); +""" +FMT = "%Y-%m-%d %H:%M" +_init_lock = threading.Lock() +_ready = set() + + +class Invalid(ValueError): + def __init__(self, field, msg): + super().__init__(msg) + self.field = field + + +def connect(path): + """A connection for one request (sqlite3 connections don't cross threads).""" + con = sqlite3.connect(path, timeout=10) + con.row_factory = sqlite3.Row + con.execute("PRAGMA foreign_keys = ON") + if path not in _ready: + with _init_lock: + con.executescript(SCHEMA) + _ready.add(path) + os.chmod(path, 0o600) + return con + + +def now(): + return datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + +# ---- the tree ---------------------------------------------------------------------- + +class Tree: + """All nodes + rates in memory (a few hundred rows at most): inheritance, paths, + and the picker lists are computed here instead of in SQL.""" + + def __init__(self, con, default_rate=0.0, default_currency="EUR"): + self.nodes = {r["id"]: dict(r) for r in con.execute("SELECT * FROM node ORDER BY name COLLATE NOCASE")} + self.rates = {} + for r in con.execute("SELECT * FROM rate ORDER BY since"): + self.rates.setdefault(r["node_id"], []).append(dict(r)) + self.children = {} + for n in self.nodes.values(): + self.children.setdefault(n["parent_id"], []).append(n["id"]) + self.default_rate, self.default_currency = float(default_rate or 0), default_currency or "EUR" + + def chain(self, nid): + """The node and its ancestors, nearest first.""" + out, seen = [], set() + while nid is not None and nid in self.nodes and nid not in seen: + seen.add(nid) + out.append(self.nodes[nid]) + nid = self.nodes[nid]["parent_id"] + return out + + def path(self, nid, sep=" › "): + return sep.join(n["name"] for n in reversed(self.chain(nid))) + + def client_of(self, nid): + """The top-level customer a node belongs to.""" + c = self.chain(nid) + return c[-1] if c else None + + def _inherit(self, nid, key, default): + for n in self.chain(nid): + if n[key] is not None: + return n[key], n + return default, None + + def colour(self, nid): + return self._inherit(nid, "colour", PALETTE[0])[0] + + def currency(self, nid): + return self._inherit(nid, "currency", self.default_currency)[0] + + def billable(self, nid): + """(default billable for new entries, the node it comes from or None).""" + v, src = self._inherit(nid, "billable", 1) + return bool(v), src + + def rate(self, nid, day): + """(hourly rate on `day` 'YYYY-MM-DD', the node it comes from or None = default). + The nearest node with a rate in force that day wins.""" + for n in self.chain(nid): + best = None + for r in self.rates.get(n["id"], ()): + if r["since"] <= day: + best = r + if best: + return best["rate"], n + return self.default_rate, None + + def archived(self, nid): + return any(n["archived"] for n in self.chain(nid)) + + def walk(self, parent=None, depth=0, include_archived=False): + """Depth-first [(node, depth)]: clients, then under each its sub-customers, + projects and tasks (sub-customers first, then projects, then tasks).""" + order = {"client": 0, "project": 1, "task": 2} + kids = sorted(self.children.get(parent, ()), key=lambda i: (order[self.nodes[i]["kind"]], + self.nodes[i]["name"].lower())) + for i in kids: + n = self.nodes[i] + if n["archived"] and not include_archived: + continue + yield n, depth + yield from self.walk(i, depth + 1, include_archived) + + def subtree(self, nid): + out, todo = set(), [nid] + while todo: + i = todo.pop() + out.add(i) + todo += self.children.get(i, []) + return out + + +# ---- nodes ------------------------------------------------------------------------------ + +def _clean_node(d, tree, nid=None): + name = str(d.get("name") or "").strip() + if not name: + raise Invalid("name", "Give it a name.") + if len(name) > 80: + raise Invalid("name", "At most 80 characters.") + kind = d.get("kind") if nid is None else tree.nodes[nid]["kind"] + if kind not in KINDS: + raise Invalid("kind", "Unknown kind.") + parent = d.get("parent_id") + parent = int(parent) if parent not in (None, "", 0, "0") else None + pkind = tree.nodes[parent]["kind"] if parent in tree.nodes else None + if parent is not None and parent not in tree.nodes: + raise Invalid("parent_id", "That parent no longer exists.") + if pkind not in PARENTS[kind]: + what = {"client": "A sub-customer goes under a customer.", "project": "A project goes under a customer.", + "task": "A task goes under a customer or a project."}[kind] + raise Invalid("parent_id", what) + if nid is not None and parent is not None and parent in tree.subtree(nid): + raise Invalid("parent_id", "It can't go under itself.") + colour = d.get("colour") or None + if colour is not None and not (isinstance(colour, str) and len(colour) == 7 and colour[0] == "#"): + raise Invalid("colour", "A colour like #ffb33a.") + if kind == "client" and parent is None and colour is None: # customers always have one + used = {n["colour"] for n in tree.nodes.values() if n["parent_id"] is None} + colour = next((c for c in PALETTE if c not in used), PALETTE[len(used) % len(PALETTE)]) + billable = d.get("billable") + billable = None if billable in (None, "", "inherit") else int(billable in (True, 1, "1", "yes")) + currency = str(d.get("currency") or "").strip().upper() or None + if currency and not (currency.isalpha() and len(currency) == 3): + raise Invalid("currency", "A 3-letter code like EUR or RON.") + notes = str(d.get("notes") or "")[:4000] + return {"kind": kind, "parent_id": parent, "name": name, "colour": colour, "billable": billable, + "currency": currency, "notes": notes, "archived": int(bool(d.get("archived")))} + + +def save_node(con, tree, d): + """Create (no id) or update a node; returns its id.""" + nid = int(d["id"]) if d.get("id") else None + if nid is not None and nid not in tree.nodes: + raise Invalid("name", "It was deleted meanwhile.") + v = _clean_node(d, tree, nid) + if nid is None: + cur = con.execute("INSERT INTO node (kind, parent_id, name, colour, billable, currency, notes, archived, created)" + " VALUES (:kind, :parent_id, :name, :colour, :billable, :currency, :notes, :archived, :created)", + dict(v, created=now())) + nid = cur.lastrowid + else: + con.execute("UPDATE node SET parent_id=:parent_id, name=:name, colour=:colour, billable=:billable," + " currency=:currency, notes=:notes, archived=:archived WHERE id=:id", dict(v, id=nid)) + if "rates" in d: + _save_rates(con, nid, d["rates"]) + con.commit() + return nid + + +def _save_rates(con, nid, rates): + """Replace a node's rate history with the submitted rows [{since, rate}].""" + rows = {} + for i, r in enumerate(rates or []): + raw = str(r.get("rate") if r.get("rate") is not None else "").strip().replace(",", ".") + if raw == "": + continue + try: + rate = float(raw) + except ValueError: + raise Invalid(f"rates.{i}.rate", "The rate must be a number.") + if not 0 <= rate <= 100000: + raise Invalid(f"rates.{i}.rate", "Between 0 and 100000.") + since = str(r.get("since") or "").strip() or EPOCH + if since != EPOCH: + try: + datetime.strptime(since, "%Y-%m-%d") + except ValueError: + raise Invalid(f"rates.{i}.since", "A date, or empty for always.") + if since in rows: + raise Invalid(f"rates.{i}.since", "Two rates from the same day.") + rows[since] = rate + con.execute("DELETE FROM rate WHERE node_id = ?", (nid,)) + con.executemany("INSERT INTO rate (node_id, since, rate) VALUES (?, ?, ?)", + [(nid, s, r) for s, r in rows.items()]) + + +def delete_node(con, tree, nid): + """Delete a node and everything under it — only if no time was booked there + (booked work is history: archive it instead). Returns False if refused.""" + ids = tree.subtree(nid) + q = ",".join("?" * len(ids)) + if con.execute(f"SELECT 1 FROM entry WHERE node_id IN ({q}) LIMIT 1", tuple(ids)).fetchone(): + return False + for i in sorted(ids, key=lambda i: -len(tree.chain(i))): # leaves first (parent FK) + con.execute("DELETE FROM node WHERE id = ?", (i,)) + con.commit() + return True + + +# ---- entries --------------------------------------------------------------------------- + +def clean_entry(d, tree): + try: + nid = int(d.get("node_id") or 0) + except (TypeError, ValueError): + nid = 0 + if nid not in tree.nodes: + raise Invalid("node_id", "Choose what you worked on.") + try: + start = datetime.strptime(f"{d['date']} {d['start']}", FMT) + end = datetime.strptime(f"{d.get('end_date') or d['date']} {d['end']}", FMT) + except (KeyError, ValueError): + raise Invalid("start", "Check the date and times.") + if end <= start and not d.get("end_date"): # 23:00 – 01:00: ends the next day + end += timedelta(days=1) + if end <= start: + raise Invalid("end", "The end must be after the start.") + if (end - start).total_seconds() > 24 * 3600: + raise Invalid("end", "At most 24 hours in one entry.") + return {"node_id": nid, "start": start.strftime(FMT), "end": end.strftime(FMT), + "billable": int(bool(d.get("billable"))), "note": str(d.get("note") or "").strip()[:2000]} + + +def save_entry(con, tree, d): + v = clean_entry(d, tree) + eid = int(d["id"]) if d.get("id") else None + if eid is None: + eid = con.execute("INSERT INTO entry (node_id, start, end, billable, note, created, updated)" + " VALUES (:node_id, :start, :end, :billable, :note, :t, :t)", dict(v, t=now())).lastrowid + elif not con.execute("UPDATE entry SET node_id=:node_id, start=:start, end=:end, billable=:billable," + " note=:note, updated=:t WHERE id=:id", dict(v, t=now(), id=eid)).rowcount: + raise Invalid("node_id", "This entry was deleted meanwhile.") + con.commit() + return eid + + +def move_entry(con, eid, start, end): + """Drag / resize in the week view: new times only.""" + s, e = datetime.strptime(start, FMT), datetime.strptime(end, FMT) + if e <= s or (e - s).total_seconds() > 24 * 3600: + raise Invalid("end", "Not a valid span.") + n = con.execute("UPDATE entry SET start=?, end=?, updated=? WHERE id=?", + (s.strftime(FMT), e.strftime(FMT), now(), eid)).rowcount + con.commit() + return bool(n) + + +def delete_entry(con, eid): + n = con.execute("DELETE FROM entry WHERE id = ?", (eid,)).rowcount + con.commit() + return bool(n) + + +def entries_between(con, start, end, nodes=None): + """Entries overlapping [start, end) (datetimes); `nodes` = a set of node ids to keep.""" + rows = [dict(r) for r in con.execute("SELECT * FROM entry WHERE start < ? AND end > ? ORDER BY start", + (end.strftime(FMT), start.strftime(FMT)))] + for r in rows: + r["s"], r["e"] = datetime.strptime(r["start"], FMT), datetime.strptime(r["end"], FMT) + return [r for r in rows if nodes is None or r["node_id"] in nodes] + + +def recent(con, tree, n=5): + """The last few distinct nodes worked on (form chips), live ones only.""" + out = [] + for r in con.execute("SELECT node_id, MAX(updated) AS t FROM entry GROUP BY node_id ORDER BY t DESC LIMIT 30"): + if r["node_id"] in tree.nodes and not tree.archived(r["node_id"]): + out.append(r["node_id"]) + if len(out) == n: + break + return out + + +def booked_minutes(con): + """node id -> minutes ever booked directly on it (Customers page).""" + return {r["node_id"]: r["m"] for r in con.execute( + "SELECT node_id, SUM((julianday(end) - julianday(start)) * 1440) AS m FROM entry GROUP BY node_id")} diff --git a/dashboard/plugins/workload/phone.py b/dashboard/plugins/workload/phone.py new file mode 100644 index 0000000..e793a5c --- /dev/null +++ b/dashboard/plugins/workload/phone.py @@ -0,0 +1,99 @@ +"""What the phone app's Work week shows besides the bookings — the calendar events behind it and +Activity's blocks beside it — which the phone can't make itself (no Nextcloud, no ActivityWatch). +The primary dashboard writes them for a window around today into dash_data/workload/phone.db, synced +one way (META "sync"); only rows that changed are written, gone ones deleted (→ delete markers). + + cal (k 'cal::', start, end 'YYYY-MM-DD HH:MM', title, colour, calendar) + act (k 'act::', day, start, end 'HH:MM', a, b minutes, colour, path, name, what, names JSON, dur) +""" +import hashlib +import json +import os +import sqlite3 +from contextlib import closing +from datetime import date, datetime, time, timedelta + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS cal (k TEXT PRIMARY KEY, start TEXT NOT NULL, end TEXT NOT NULL, title TEXT NOT NULL, + colour TEXT, calendar TEXT); +CREATE TABLE IF NOT EXISTS act (k TEXT PRIMARY KEY, day TEXT NOT NULL, start TEXT NOT NULL, end TEXT NOT NULL, + a REAL, b REAL, colour TEXT, path TEXT, name TEXT, what TEXT, names TEXT, dur TEXT); +""" +SYNC = {"cal": {"key": "NEW.k"}, "act": {"key": "NEW.k"}} # META["sync"]["phone.db"] +BACK, AHEAD = 8 * 7, 12 * 7 # days of calendar events around today (Activity: only the past) +EVERY = 300 # s between refreshes +FMT = "%Y-%m-%d %H:%M" + + +def create(path): + with closing(sqlite3.connect(path)) as c: + c.executescript(SCHEMA) + os.chmod(path, 0o600) + + +def cal_rows(events): + """events_between's timed events → {k: row} (all-day ones aren't drawn in the week).""" + out = {} + for ev in events: + if ev["all_day"]: + continue + h = hashlib.sha1(f"{ev['title']}\0{ev.get('calendar', '')}".encode()).hexdigest()[:10] + k = f"cal:{ev['start']:%Y-%m-%d %H:%M}:{h}" + out[k] = {"k": k, "start": ev["start"].strftime(FMT), "end": ev["end"].strftime(FMT), "title": ev["title"][:200], + "colour": ev.get("colour") or "#8b929e", "calendar": ev.get("calendar") or ""} + return out + + +def act_rows(blocks): + """Activity's {iso: [block]} → {k: row}.""" + out = {} + for day, bs in (blocks or {}).items(): + for b in bs: + k = f"act:{day}:{b['start']}" + out[k] = {"k": k, "day": day, "start": b["start"], "end": b["end"], "a": round(b["a"], 2), "b": round(b["b"], 2), + "colour": b["color"], "path": b["path"], "name": b["name"], "what": " · ".join(b["top"]), + "names": json.dumps(b["names"], ensure_ascii=False), "dur": b["dur"]} + return out + + +def _write(con, table, new, keep=lambda r: True): + """Make `table` = new (for the rows `keep` says are in the window) → (written, deleted).""" + cols = None + old = {} + for r in con.execute(f"SELECT * FROM {table}"): + r = dict(r) + if keep(r): + old[r["k"]] = r + written = deleted = 0 + for k, row in new.items(): + if cols is None: + cols = list(row) + o = old.get(k) + if o and all(o.get(c) == row[c] for c in cols): + continue + con.execute(f"INSERT INTO {table} ({', '.join(cols)}) VALUES ({', '.join('?' * len(cols))}) " + f"ON CONFLICT(k) DO UPDATE SET {', '.join(f'{c} = excluded.{c}' for c in cols if c != 'k')}", + [row[c] for c in cols]) + written += 1 + for k in old.keys() - new.keys(): + con.execute(f"DELETE FROM {table} WHERE k = ?", (k,)) + deleted += 1 + return written, deleted + + +def refresh(path, events_between, blocks, today=None): + """events_between(start, end) / blocks(d0, d1) = the calendar's and Activity's answers (None = off).""" + today = today or date.today() + d0, d1 = today - timedelta(days=BACK), today + timedelta(days=AHEAD) + evs = events_between(datetime.combine(d0, time()), datetime.combine(d1, time())) + acts = blocks(d0, today) + lo, hi = d0.isoformat(), d1.isoformat() + out = {} + with closing(sqlite3.connect(path, timeout=10)) as con, con: + con.row_factory = sqlite3.Row + # outside the window rows stay (history); a source that's off (None) is left alone + if evs: # [] = the calendar is off or hasn't synced yet: keep what's there + out["cal"] = _write(con, "cal", cal_rows(evs), lambda r: lo <= r["start"][:10] < hi) + if acts is not None: + out["act"] = _write(con, "act", act_rows(acts), lambda r: lo <= r["day"] <= today.isoformat()) + return out diff --git a/dashboard/plugins/workload/static/workload.css b/dashboard/plugins/workload/static/workload.css new file mode 100644 index 0000000..bd7068f --- /dev/null +++ b/dashboard/plugins/workload/static/workload.css @@ -0,0 +1,226 @@ +/* Workload tracker — on top of dash.css (its tokens, header, .ec-box dialogs). Real px. */ +.page-work { display: flex; flex-direction: column; gap: 14px; font-size: 15px; } +/* Week ↔ Report (+ Activity): right end of the totals row (week) / the filter row (report), same spot */ +.wl-switch { margin-left: auto; align-self: center; border-radius: 10px; padding: 9px 20px; background: #262d3b; + color: var(--fg); font: 700 15px "DejaVu Web", sans-serif; text-decoration: none; } +.wl-switch:hover { background: #1d222d; } +.wl-switch:active { background: #12161e; } +.wl-switches { margin-left: auto; align-self: center; display: flex; gap: 8px; } /* + Activity (inside Work) */ +.wl-switches .wl-switch { margin-left: 0; } +/* Settings ▸ Work: the customer editor fills the tab's width */ +.wl-in-settings .wl-cust { margin-top: 6px; } +.wl-note { margin: 0; color: var(--dim); font-size: 13.5px; line-height: 1.45; } +.wl-note b { color: var(--muted); font-weight: 400; } +.wl-empty { padding: 18px 20px; border-radius: 14px; background: var(--card); color: var(--muted); } +.wl-empty a { color: var(--accent); } +.wl-btn { border: 0; border-radius: 10px; padding: 9px 16px; background: var(--accent); color: var(--bg); + font: 700 15px "DejaVu Web", sans-serif; cursor: pointer; } +.wl-mini { border: 0; border-radius: 8px; padding: 6px 12px; background: #262d3b; color: var(--fg); cursor: pointer; + font: 400 14px "DejaVu Web", sans-serif; } +.wl-mini:hover { color: var(--accent); } +.wl-b { color: #7fd6a3; } .wl-u { color: var(--muted); } +.wl-dot { display: inline-block; width: 10px; height: 10px; border-radius: 50%; margin-right: 8px; flex: none; } +.bad { outline: 2px solid #ff6b6b !important; outline-offset: -1px; } + +/* ---- week summary ------------------------------------------------------------------ */ +.wl-sum { display: flex; flex-wrap: wrap; align-items: baseline; gap: 6px 22px; padding: 2px 4px; } +.wl-tot { font-size: 18px; color: var(--muted); } .wl-tot b { font-size: 28px; color: var(--fg); } +.wl-split { color: var(--muted); } +.wl-money { color: var(--accent); font-weight: 700; } +.wl-prog { flex: 1 1 160px; max-width: 360px; height: 8px; border-radius: 4px; background: #262d3b; overflow: hidden; align-self: center; } +.wl-prog div { height: 100%; background: var(--accent); border-radius: 4px; } +.wl-help { margin: 0; color: var(--dim); font-size: 13px; text-align: center; } + +/* customers strip: chips -> /work/customers#n=ID */ +.wl-custs { display: flex; flex-wrap: wrap; gap: 6px; } +.wl-cchip { display: inline-flex; align-items: baseline; gap: 8px; padding: 6px 12px; border-radius: 8px; + background: var(--card); border-left: 4px solid var(--c); font-size: 14px; white-space: nowrap; } +.wl-cchip span { color: var(--muted); font-size: 13px; } +.wl-cchip .wl-camt { color: var(--accent); } +.wl-cchip.idle b { font-weight: 400; color: var(--muted); } +.wl-cchip:hover { background: #222837; } .wl-cchip:hover b { color: var(--fg); } +.wl-cadd { border-left-color: transparent; color: var(--accent); } +.wl-flh { display: flex; justify-content: space-between; color: var(--muted); font-size: 13.5px; } +.wl-nedit { color: var(--cool); } .wl-nedit[hidden] { display: none; } + +/* ---- week grid: hour gutter + 7 day columns (weekends narrower) ---------------------- */ +.wl-week { overflow: auto; height: 70vh; overscroll-behavior: contain; scrollbar-width: thin; scrollbar-color: #2c3343 transparent; } +.wl-in { --cols: 44px repeat(5, minmax(0, 1fr)) repeat(2, minmax(0, .7fr)); min-width: 760px; } +.wl-heads { display: grid; grid-template-columns: var(--cols); gap: 0 4px; padding-bottom: 6px; + position: sticky; top: 0; z-index: 6; background: var(--bg); } +.wl-dh { display: flex; justify-content: space-between; align-items: baseline; gap: 6px; padding: 6px 8px; + border-radius: 8px; background: var(--card); white-space: nowrap; overflow: hidden; } +.wl-dh b { font-size: 15px; } .wl-dt { color: var(--dim); font-size: 13px; } +.wl-dt .wl-u { color: var(--muted); } +.wl-dh.today { background: #2a2416; } .wl-dh.today b { color: var(--accent); } +.wl-dh.weekend b { color: var(--muted); } +.wl-body { display: grid; grid-template-columns: var(--cols); gap: 0 4px; height: calc(24 * var(--hh, 44px)); } +.wl-hours { position: relative; } +.wl-hours span { position: absolute; right: 6px; transform: translateY(-50%); font-size: 12px; color: var(--dim); } +.wl-col { position: relative; border-radius: 8px; background: var(--card); cursor: cell; user-select: none; -webkit-user-select: none; } +.wl-col.weekend { background: #12161e; } +.wl-col.today { box-shadow: inset 0 0 0 1px rgba(255, 179, 58, .35); } +.wl-band { position: absolute; left: 0; right: 0; background: #23272f; pointer-events: none; } /* sleep / lunch: greyer */ +.wl-band span { position: absolute; right: 6px; top: 3px; font-size: 11px; color: var(--dim); text-transform: uppercase; } +.wl-band + .wl-band { border-top: 0; } +.wl-hl { position: absolute; left: 0; right: 0; border-top: 1px solid #222837; pointer-events: none; } + +.wl-ghost { position: absolute; left: 3px; right: 3px; box-sizing: border-box; border-radius: 6px; padding: 2px 6px; + border: 1px dashed color-mix(in srgb, var(--gc) 70%, transparent); + background: color-mix(in srgb, var(--gc) 9%, transparent); color: color-mix(in srgb, var(--gc) 75%, var(--muted)); + font-size: 11.5px; line-height: 1.3; overflow: hidden; cursor: copy; } +.wl-ghost:hover { background: color-mix(in srgb, var(--gc) 18%, transparent); } + +.wl-blk { position: absolute; z-index: 2; box-sizing: border-box; padding: 0 2px; cursor: grab; touch-action: auto; } +.wl-blk::before { content: ""; position: absolute; inset: 1px 1px 2px; border-radius: 6px; + background: color-mix(in srgb, var(--c) 32%, #161a23); border-left: 4px solid var(--c); } +.wl-blk.unbill::before { background: repeating-linear-gradient(135deg, color-mix(in srgb, var(--c) 18%, #161a23) 0 6px, + color-mix(in srgb, var(--c) 8%, #161a23) 6px 12px); border-left-style: dashed; } +.wl-blk.cb::before { border-top-left-radius: 0; border-top-right-radius: 0; } +.wl-blk.ca::before { border-bottom-left-radius: 0; border-bottom-right-radius: 0; } +.wl-blk > div { position: relative; padding: 0 6px 0 10px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; } +.wl-bt { padding-top: 3px !important; font-size: 13px; line-height: 1.3; } +.wl-bt span { color: var(--muted); font-size: 12px; } +.wl-bm { font-size: 11.5px; color: var(--muted); line-height: 1.3; } +.wl-bn { font-size: 12px; color: var(--fg); opacity: .8; line-height: 1.3; white-space: normal !important; } +.wl-blk.dragging { z-index: 4; cursor: grabbing; opacity: .9; } +.wl-blk.dragging::before { box-shadow: 0 6px 18px rgba(0, 0, 0, .5); } +.wl-blk:hover::before { filter: brightness(1.15); } +.wl-rs { position: absolute !important; left: 0; right: 0; bottom: 0; height: 8px; padding: 0 !important; cursor: ns-resize; } +.wl-rs::after { content: ""; position: absolute; left: 50%; bottom: 4px; width: 22px; margin-left: -11px; height: 2px; + border-radius: 1px; background: var(--muted); opacity: 0; } +.wl-blk:hover .wl-rs::after { opacity: .7; } +.wl-new { position: absolute; left: 3px; right: 3px; z-index: 3; box-sizing: border-box; border-radius: 6px; + border: 2px solid var(--accent); background: rgba(255, 179, 58, .22); padding: 2px 6px; + font-size: 12px; color: var(--fg); pointer-events: none; overflow: hidden; white-space: nowrap; } +.wl-now { position: absolute; left: -2px; right: 0; z-index: 3; border-top: 2px solid var(--accent); pointer-events: none; } +.wl-now::before { content: ""; position: absolute; left: -3px; top: -5px; width: 8px; height: 8px; border-radius: 50%; background: var(--accent); } + +/* ---- entry dialog (looks like the new-event form) ---------------------------------- */ +.wl-modal[hidden] { display: none !important; } +.wl-modal { position: fixed; inset: 0; z-index: 10; display: flex; align-items: center; justify-content: center; } +.wl-box { display: flex; flex-direction: column; gap: 12px; } +.wl-ftitle { font: 700 22px "DejaVu Web", sans-serif; color: var(--ec, var(--fg)); margin-right: 34px; } +.wl-box input, .wl-box select, .wl-box textarea, .wl-edit input, .wl-edit select, .wl-edit textarea, .wl-filter input, .wl-filter select { + font: 16px "DejaVu Web", sans-serif; color: var(--fg); background: #1d222d; border: 1px solid #2c3343; + border-radius: 8px; padding: 7px 10px; box-sizing: border-box; min-width: 0; color-scheme: dark; } +.wl-box textarea, .wl-edit textarea { resize: vertical; line-height: 1.4; } +.wl-box :focus, .wl-edit :focus, .wl-filter :focus { outline: 2px solid var(--accent); outline-offset: -1px; } +.wl-fl { display: flex; flex-direction: column; gap: 5px; min-width: 0; } +.wl-fl > span { color: var(--muted); font-size: 13.5px; } +.wl-frow { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; color: var(--muted); } +.wl-dur { color: var(--fg); font-weight: 700; } +.wl-check { display: flex; align-items: center; gap: 9px; cursor: pointer; flex-wrap: wrap; } +.wl-check input { accent-color: var(--accent); width: 18px; height: 18px; margin: 0; } +.wl-bhint { color: var(--dim); font-size: 13.5px; } +.wl-path { color: var(--dim); font-size: 13px; } +.wl-path:empty { display: none; } +.wl-rate { color: var(--muted); font-size: 14px; margin-top: -4px; } +.wl-recent { display: flex; flex-wrap: wrap; gap: 6px; } +.wl-recent:empty { display: none; } +.wl-recent button { border: 0; border-left: 4px solid var(--c); border-radius: 6px; padding: 5px 10px; background: #262d3b; + color: var(--fg); font: 13px "DejaVu Web", sans-serif; cursor: pointer; max-width: 100%; + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.wl-recent button:hover { background: #2e3647; } +.wl-actions { display: flex; align-items: center; justify-content: flex-end; gap: 14px; flex-wrap: wrap; } +.wl-err { flex: 1; color: #ff7a7a; font-size: 15px; min-width: 120px; } +.wl-save, .wl-del { padding: 9px 18px; border: 0; border-radius: 10px; cursor: pointer; font: 700 16px "DejaVu Web", sans-serif; } +.wl-save { background: var(--accent); color: var(--bg); } .wl-save:disabled { opacity: .5; cursor: wait; } +.wl-del { background: #262d3b; color: #ff9a9a; } .wl-del.armed { background: #8a2b2b; color: #fff; } +.wl-del:disabled { opacity: .35; cursor: not-allowed; } .wl-del[hidden] { display: none; } + +/* ---- customers ---------------------------------------------------------------------- */ +.wl-cust { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px; align-items: start; } +.wl-tree, .wl-edit, .wl-card { background: var(--card); border-radius: 14px; padding: 16px 18px; } +.wl-edit { position: sticky; top: 20px; } +.wl-edit[hidden] { display: none; } +.wl-edit form { display: flex; flex-direction: column; gap: 14px; } +.wl-tbar { display: flex; align-items: center; gap: 12px; justify-content: space-between; margin-bottom: 10px; } +.wl-nodes { list-style: none; margin: 0; padding: 0; } +.wl-node { display: flex; align-items: center; gap: 8px; padding: 8px 10px 8px calc(10px + var(--d) * 22px); + border-radius: 8px; cursor: pointer; border-left: 3px solid transparent; } +.wl-node:hover { background: #1d222d; } +.wl-node.sel { background: #222837; border-left-color: var(--c); } +.wl-node.arch { opacity: .45; } +.wl-node.k-client:not(.sub) { margin-top: 6px; } +.wl-ico { color: var(--c); width: 14px; text-align: center; flex: none; font-family: "Symbola Web", "DejaVu Web"; } +.wl-nm { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.k-client:not(.sub) .wl-nm { font-weight: 700; } +.wl-nm small { margin-left: 8px; color: var(--dim); font-size: 12px; font-weight: 400; } +.wl-tag { flex: none; padding: 2px 8px; border-radius: 6px; font-size: 12px; color: var(--dim); background: #1b1f29; white-space: nowrap; } +.wl-tag.own { color: var(--accent); background: #2a2416; } +.wl-tag.nb { color: var(--muted); background: repeating-linear-gradient(135deg, #222837 0 4px, #1b1f29 4px 8px); } +.wl-legend { margin-left: auto; color: var(--dim); font-size: 12px; } +.wl-mo { flex: none; width: 44px; text-align: right; color: var(--muted); font-size: 13px; } +.wl-ehead { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; } +.wl-ekind { font: 700 20px "DejaVu Web", sans-serif; } +.wl-epath { color: var(--dim); font-size: 13.5px; } +.wl-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 12px; } +.wl-crow { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; } +.wl-edit input[type=color] { width: 54px; height: 38px; padding: 2px; flex: none; } +.wl-edit input[type=color]:disabled { opacity: .35; } +.wl-cinh { font-size: 13.5px; color: var(--muted); } +.wl-cinh[hidden], .wl-parent[hidden], .wl-kids[hidden], .wl-kids [hidden] { display: none; } +.wl-rates { display: flex; flex-direction: column; gap: 6px; } +.wl-rrow { display: flex; align-items: center; gap: 8px; color: var(--muted); flex-wrap: wrap; } +.wl-rrow [name=rate] { width: 90px; } +.wl-x { border: 0; background: none; color: var(--dim); cursor: pointer; font-size: 16px; padding: 4px 6px; } +.wl-x:hover { color: #ff9a9a; } +.wl-rinh { color: var(--dim); font-size: 14px; } +.wl-rinh:empty { display: none; } +.wl-radd { align-self: flex-start; } +.wl-kids { display: flex; gap: 8px; flex-wrap: wrap; padding-top: 4px; border-top: 1px solid #262c39; padding-top: 14px; } +.wl-booked { color: var(--dim); font-size: 13.5px; } + +/* ---- report ------------------------------------------------------------------------- */ +.wl-filter { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; } +.wl-presets { display: flex; flex-wrap: wrap; gap: 4px; } +.wl-presets a { padding: 7px 12px; border-radius: 8px; background: var(--card); color: var(--muted); font-size: 14px; } +.wl-presets a.on { background: #2a2416; color: var(--accent); } +.wl-custom { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); } +.wl-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(170px, 1fr)); gap: 12px; } +.wl-tiles > div { background: var(--card); border-radius: 14px; padding: 14px 18px; display: flex; flex-direction: column; gap: 4px; } +.wl-tiles span { color: var(--dim); font-size: 13px; text-transform: uppercase; } +.wl-tiles b { font-size: 24px; } .wl-tiles small { color: var(--muted); } +.wl-card { overflow-x: auto; } +.wl-card h2 { margin: 0 0 8px; font: 700 18px "DejaVu Web", sans-serif; } +.wl-card h2 small { color: var(--dim); font-weight: 400; font-size: 14px; } +.wl-table { width: 100%; border-collapse: collapse; font-size: 14.5px; } +.wl-table th { text-align: left; font-weight: 400; font-size: 13px; color: var(--dim); padding: 6px 10px; border-bottom: 1px solid #262c39; } +.wl-table td { padding: 7px 10px; border-bottom: 1px solid #1f2430; vertical-align: top; white-space: nowrap; } +.wl-table th:not(:first-child), .wl-rtree td:not(:first-child) { text-align: right; } +.wl-items th:nth-child(4), .wl-items td:nth-child(4), .wl-items th:nth-child(3), .wl-items td:nth-child(3) { text-align: left; } +.wl-rtree td:first-child { padding-left: calc(10px + var(--d) * 22px); } +.wl-rtree tr.d0 td { font-weight: 700; border-top: 1px solid #262c39; } +.wl-items a { color: var(--cool); } +.wl-inote { white-space: pre-wrap !important; min-width: 200px; color: var(--muted); } +.wl-items tr.nb td { color: var(--muted); } + +/* ---- narrow --------------------------------------------------------------------------- */ +@media (max-width: 799px) { + .wl-cust { grid-template-columns: minmax(0, 1fr); } + .wl-edit { position: static; } +} +@media (max-width: 599px) { + .wl-mo { display: none; } +} + +/* the entry form beside its slot (dash.js place → .wl-modal.anchored; the box styles are in dash.css) */ +.wl-modal.anchored .wl-box { gap: 10px; } +.wl-modal.anchored .wl-box { width: 440px; } +.wl-modal.anchored .wl-box input, .wl-modal.anchored .wl-box select, .wl-modal.anchored .wl-box textarea { font-size: 15px; padding: 6px 9px; } +.wl-modal.anchored .wl-box textarea { min-height: 0; } +.wl-modal.anchored .wl-frow { flex-wrap: wrap; } +.wl-modal.anchored .wl-frow input[type="date"] { flex: 0 0 100%; } +.wl-modal.anchored .wl-ftitle { font-size: 17px; } + +/* the Activity lane (the "Activity" box): bookings keep the left --bw, activity the right 28 % */ +.wl-col { --bw: 100%; } +.wl-week.act .wl-col { --bw: 72%; } +.wl-week.act .wl-ghost { right: 28%; } +.wl-act { position: absolute; right: 2px; width: calc(28% - 4px); z-index: 1; box-sizing: border-box; border-radius: 4px; cursor: pointer; + background: color-mix(in srgb, var(--ac) 55%, #161a23); border-left: 3px solid var(--ac); overflow: hidden; } +.wl-act:hover { filter: brightness(1.25); z-index: 3; } +.wl-act span { display: block; padding: 1px 3px; font-size: 11px; line-height: 1.2; color: var(--fg); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.wl-actbox { align-self: center; margin-left: auto; display: inline-flex; gap: 6px; align-items: center; color: var(--muted); font-size: 14px; cursor: pointer; white-space: nowrap; } +.wl-actbox + .wl-switches { margin-left: 12px; } diff --git a/dashboard/plugins/workload/static/workload.js b/dashboard/plugins/workload/static/workload.js new file mode 100644 index 0000000..fdacab2 --- /dev/null +++ b/dashboard/plugins/workload/static/workload.js @@ -0,0 +1,499 @@ +// Workload tracker pages. Week (/work): book time like calendar events — mouse: drag on a +// day (a click books the default length), click a block to edit it, drag it to move (also +// to another day), drag its bottom edge to resize; touch: taps only, so the page scrolls. +// The "Activity" box (cookie work_act) shows Activity's lane; a click on one of its blocks +// books it, with the customer it guessed. +// Customers (Settings ▸ Work, /settings#work): the tree's editor. No browser dialogs anywhere. +(function () { + const page = document.getElementById("page"); + const SNAP = 15; // minutes + const post = async (url, data) => { + const r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(data) }); + const j = await r.json().catch(() => ({})); + if (!r.ok) throw Object.assign(new Error(j.error || `Error ${r.status}`), { field: j.field }); + return j; + }; + const pad = (n) => String(n).padStart(2, "0"); + const hhmm = (m) => `${pad(Math.floor(m / 60) % 24)}:${pad(m % 60)}`; + const mins = (t) => { const [h, m] = t.split(":").map(Number); return h * 60 + m; }; + const dur = (m) => `${Math.floor(m / 60)}:${pad(m % 60)}`; + const modal = (on) => document.body.classList.toggle("modal", on); // dash.js: keys off + + // =================================================================================== + // week view + // =================================================================================== + const formBox = document.getElementById("wl-form"); + if (formBox) { + let D = JSON.parse(document.getElementById("wl-data").textContent); + let N = Object.fromEntries(D.nodes.map((n) => [n.id, n])); + const form = formBox.querySelector("form"), F = form.elements; + let editing = null, billTouched = false; + + // ---- size: all 24 h are drawn inside .wl-week (scrolls both ways, fills the window). + // On a screen at least 1080 px tall the focus hours (settings, 07–19) fill it exactly; + // smaller screens keep readable 44 px hours. Opens scrolled to the focus start. + function fit(scrollTo = true) { + const wk = page.querySelector(".wl-week"); + if (!wk) return; + const avail = Math.max(420, innerHeight - wk.getBoundingClientRect().top - 34); + wk.style.height = avail + "px"; + const [f0, f1] = D.focus, heads = wk.querySelector(".wl-heads").offsetHeight; + const hh = screen.height >= 1080 ? Math.max(28, (avail - heads) / (f1 - f0)) : 44; + wk.style.setProperty("--hh", hh + "px"); + if (scrollTo) wk.scrollTop = f0 * hh; + const t = wk.querySelector(".wl-dh.today"); // narrow screens: today's column in sight + if (scrollTo && t && wk.scrollWidth > wk.clientWidth) wk.scrollLeft = t.offsetLeft - (wk.clientWidth - t.offsetWidth) / 2; + } + addEventListener("resize", () => { + const wk = page.querySelector(".wl-week"), hh = parseFloat(wk?.style.getPropertyValue("--hh")) || 44; + const at = wk ? wk.scrollTop / hh : 0; // keep the same hour at the top + fit(false); + if (wk) wk.scrollTop = at * (parseFloat(wk.style.getPropertyValue("--hh")) || 44); + }); + + // ---- swap in a fresh copy of the page after a save (keeps both scroll positions) + async function reload() { + const old = page.querySelector(".wl-week"), top = old?.scrollTop || 0, left = old?.scrollLeft || 0; + try { + const r = await fetch(location.href, { cache: "no-store" }); + const doc = new DOMParser().parseFromString(await r.text(), "text/html"); + page.innerHTML = doc.getElementById("page").innerHTML; + D = JSON.parse(document.getElementById("wl-data").textContent); + N = Object.fromEntries(D.nodes.map((n) => [n.id, n])); + fit(false); + const wk = page.querySelector(".wl-week"); + if (wk) { wk.scrollTop = top; wk.scrollLeft = left; } + } catch (e) { location.reload(); } + } + setInterval(() => { if (formBox.hidden && !drag && document.visibilityState === "visible") reload(); }, 5 * 60000); + document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible" && formBox.hidden) reload(); }); + + // ---- geometry: a pointer's y in a day column -> minutes since midnight (snapped) + function minuteAt(col, clientY, snap = true) { + const r = col.getBoundingClientRect(); + const f = Math.max(0, Math.min(1, (clientY - r.top) / r.height)); + const m = D.h0 * 60 + f * (D.h1 - D.h0) * 60; + return snap ? Math.round(m / SNAP) * SNAP : m; + } + const pct = (m) => ((m - D.h0 * 60) / ((D.h1 - D.h0) * 60)) * 100; + function colAt(x) { + return [...page.querySelectorAll(".wl-col")].find((c) => { const r = c.getBoundingClientRect(); return x >= r.left && x < r.right; }); + } + + // ---- pointer: create / move / resize (mouse + pen); touch only taps (see click below) + let drag = null; + page.addEventListener("pointerdown", (e) => { + if (e.pointerType === "touch" || e.button !== 0 || !formBox.hidden) return; + const col = e.target.closest(".wl-col"); + if (!col) return; + const blk = e.target.closest(".wl-blk"); + const m = minuteAt(col, e.clientY); + if (blk) { + const en = D.entries[blk.dataset.id]; + if (!en) return; + const s = mins(en.start.slice(11)), len = (new Date(en.end.replace(" ", "T")) - new Date(en.start.replace(" ", "T"))) / 60000; + drag = { kind: e.target.closest(".wl-rs") ? "resize" : "move", blk, en, col, x0: e.clientX, y0: e.clientY, + grab: minuteAt(col, e.clientY, false) - s, s, len, day: en.start.slice(0, 10), moved: false }; + } else { + drag = { kind: "new", col, a: m, b: m, x0: e.clientX, y0: e.clientY, moved: false, + ghost: e.target.closest(".wl-ghost, .wl-act") }; + } + e.preventDefault(); + }); + addEventListener("pointermove", (e) => { + if (!drag) return; + if (!drag.moved && Math.hypot(e.clientX - drag.x0, e.clientY - drag.y0) < 5) return; + drag.moved = true; + if (drag.kind === "new") { + drag.b = minuteAt(drag.col, e.clientY); + let el = drag.col.querySelector(".wl-new"); + if (!el) { el = document.createElement("div"); el.className = "wl-new"; drag.col.append(el); } + const a = Math.min(drag.a, drag.b), b = Math.max(drag.a, drag.b, a + SNAP); + el.style.top = pct(a) + "%"; el.style.height = (pct(b) - pct(a)) + "%"; + el.textContent = `${hhmm(a)} – ${hhmm(b)} · ${dur(b - a)}`; + } else if (drag.kind === "move") { + const col = colAt(e.clientX) || drag.col; + let s = Math.round((minuteAt(col, e.clientY, false) - drag.grab) / SNAP) * SNAP; + s = Math.max(0, Math.min(24 * 60 - SNAP, s)); + drag.ns = s; drag.nday = col.dataset.day; + if (drag.blk.parentElement !== col) col.append(drag.blk); + Object.assign(drag.blk.style, { top: pct(s) + "%", left: "0", width: "100%" }); + drag.blk.classList.add("dragging"); + drag.blk.querySelector(".wl-bm").textContent = `${hhmm(s)}–${hhmm(s + drag.len)} · ${dur(drag.len)}`; + } else { + const end = Math.max(drag.s + SNAP, minuteAt(drag.col, e.clientY)); + drag.nlen = end - drag.s; + drag.blk.style.height = (pct(end) - pct(drag.s)) + "%"; + drag.blk.classList.add("dragging"); + drag.blk.querySelector(".wl-bm").textContent = `${hhmm(drag.s)}–${hhmm(end)} · ${dur(drag.nlen)}`; + } + }); + addEventListener("pointerup", async () => { + const d = drag; + drag = null; + if (!d) return; + if (!d.moved) { // a click + if (d.kind === "new") clickEmpty(d.col, d.a, d.ghost); + else openForm(d.en, null, d.blk); + return; + } + if (d.kind === "new") { + const a = Math.min(d.a, d.b), b = Math.max(d.a, d.b, a + SNAP); + openForm(null, { date: d.col.dataset.day, start: a, end: b }); + return; + } + const day = d.kind === "move" ? d.nday : d.day; + const s = d.kind === "move" ? d.ns : d.s, len = d.kind === "move" ? d.len : d.nlen; + if (s === undefined || len === undefined) return reload(); + const start = new Date(`${day}T${hhmm(s)}`), end = new Date(start.getTime() + len * 60000); + const fmt = (t) => `${t.getFullYear()}-${pad(t.getMonth() + 1)}-${pad(t.getDate())} ${pad(t.getHours())}:${pad(t.getMinutes())}`; + try { await post("/work/api/entry/move", { id: d.en.id, start: fmt(start), end: fmt(end) }); } + catch (err) { /* the reload shows where it really is */ } + reload(); + }); + addEventListener("pointercancel", () => { if (drag) { drag = null; reload(); } }); + + // touch: a tap on a block edits it, on a faint calendar event books it, elsewhere books + // the default length from that spot + page.addEventListener("click", (e) => { + if (e.pointerType && e.pointerType !== "touch") return; + if (!(e.pointerType === "touch" || matchMedia("(pointer: coarse)").matches)) return; + const col = e.target.closest(".wl-col"); + if (!col || !formBox.hidden) return; + const blk = e.target.closest(".wl-blk"); + if (blk) return openForm(D.entries[blk.dataset.id], null, blk); + clickEmpty(col, minuteAt(col, e.clientY), e.target.closest(".wl-ghost, .wl-act")); + }); + + // the Activity lane on / off (per browser) + page.addEventListener("change", (e) => { + if (e.target.id !== "wl-act") return; + document.cookie = `work_act=${e.target.checked ? 1 : 0}; path=/work; max-age=31536000; SameSite=Lax`; + reload(); + }); + + function clickEmpty(col, m, ghost) { + if (ghost?.classList.contains("wl-act")) { // an activity block: book it, on 5-minute marks + const a = Math.floor(mins(ghost.dataset.start) / 5) * 5; + const b = ghost.dataset.end === "24:00" ? 1440 : Math.min(1440, Math.ceil(mins(ghost.dataset.end) / 5) * 5); + return openForm(null, { date: col.dataset.day, start: a, end: Math.max(b, a + 5), note: ghost.dataset.note, node: ghost.dataset.node }); + } + if (ghost) { // a calendar event: book it as it was + const a = mins(ghost.dataset.start), b = ghost.dataset.end === "24:00" ? 1440 : mins(ghost.dataset.end); + return openForm(null, { date: col.dataset.day, start: a, end: b, note: ghost.dataset.title }); + } + const a = Math.floor(m / SNAP) * SNAP; + openForm(null, { date: col.dataset.day, start: a, end: Math.min(1440, a + D.minutes) }); + } + + // ---- the form + function fillPicker(current) { + const sel = F.node_id; + sel.replaceChildren(); + sel.append(new Option("Choose…", "")); + let group = null; + for (const n of D.nodes) { + if (n.archived && n.id !== current) continue; + if (n.depth === 0) { + group = document.createElement("optgroup"); + group.label = n.label; + sel.append(group); + } + const o = new Option(" ".repeat(n.depth) + (n.depth === 0 ? n.label + " (customer)" : n.label) + + (n.kind === "project" ? " ▣" : "") + (n.archived ? " (archived)" : ""), n.id); + (group || sel).append(o); + } + sel.value = current || ""; + } + function fillRecent() { + const box = formBox.querySelector(".wl-recent"); + box.replaceChildren(...D.recent.filter((id) => N[id]).map((id) => { + const b = document.createElement("button"); + b.type = "button"; b.dataset.node = id; b.style.setProperty("--c", N[id].colour); + b.textContent = N[id].path; + return b; + })); + } + function rateOn(n, day) { + for (const lvl of n.rchain) { + let best = null; + for (const [since, rate] of lvl.rates) if (since <= day) best = rate; + if (best !== null) return [best, lvl.src]; + } + return [D.default_rate, ""]; + } + function length() { + let a = mins(F.start.value || "00:00"), b = mins(F.end.value || "00:00"); + if (b <= a) b += 1440; + return b - a; + } + function sync() { + const n = N[F.node_id.value]; + formBox.querySelector(".ec-box").style.setProperty("--ec", n ? n.colour : "var(--accent)"); + formBox.querySelector(".wl-path").textContent = n && n.depth ? n.path : ""; + const ed = formBox.querySelector(".wl-nedit"); // jump to its settings (rate, notes, …) + ed.hidden = !n; + if (n) ed.href = "/settings#work&n=" + n.id; + if (n && !billTouched) F.billable.checked = n.billable; + formBox.querySelector(".wl-bhint").textContent = n + ? `(default: ${n.billable ? "billable" : "not billable"}${n.bsrc ? " — " + n.bsrc : ""})` : ""; + const len = F.start.value && F.end.value ? length() : 0; + formBox.querySelector(".wl-dur").textContent = len ? dur(len) + " h" + (mins(F.end.value) <= mins(F.start.value) ? " (ends next day)" : "") : ""; + const r = formBox.querySelector(".wl-rate"); + if (!n) { r.textContent = ""; return; } + if (!F.billable.checked) { r.textContent = "Not billable — counted in hours only."; return; } + const [rate, src] = rateOn(n, F.date.value || "9999"); + r.textContent = `${rate} ${n.currency}/h${src ? " · rate from " + src : " · default rate"}` + + (len ? ` = ${(rate * len / 60).toFixed(2)} ${n.currency}` : ""); + } + // the selection being booked: an orange block in its day column (.wl-new), kept while the + // form is open and following the times typed; the form sits beside it (or beside the block + // being edited) — dash.js place() + let anchorEl = null; + function showNew() { + page.querySelectorAll(".wl-new").forEach((el) => el.remove()); + if (editing) return; + const col = page.querySelector(`.wl-col[data-day="${F.date.value}"]`); + if (!col || !F.start.value || !F.end.value) return; + const a = mins(F.start.value), b = mins(F.end.value) || 1440; + if (b <= a) return; + const el = document.createElement("div"); + el.className = "wl-new"; + el.style.top = pct(a) + "%"; el.style.height = (pct(b) - pct(a)) + "%"; + el.textContent = `${hhmm(a)} – ${F.end.value} · ${dur(b - a)}`; + col.append(el); + anchorEl = el; + } + const placeForm = () => window.dashPlace?.(formBox, form, anchorEl?.isConnected ? anchorEl.getBoundingClientRect() : null); + function openForm(en, pre, blk) { + editing = en || null; + billTouched = false; + fillPicker(en ? en.node_id : null); + fillRecent(); + formBox.querySelector(".wl-ftitle").textContent = en ? "Edit entry" : "New entry"; + if (en) { + F.date.value = en.start.slice(0, 10); F.start.value = en.start.slice(11); F.end.value = en.end.slice(11); + F.billable.checked = en.billable; F.note.value = en.note; + billTouched = true; // keep what was saved + } else { + F.date.value = pre.date; F.start.value = hhmm(pre.start); F.end.value = hhmm(pre.end % 1440); + F.note.value = pre.note || ""; + let last = 0; // the last thing booked + try { last = Number(localStorage.getItem("work.last") || 0); } catch (x) { /* private mode */ } + if (N[last] && !N[last].archived) F.node_id.value = last; + if (N[pre.node] && !N[pre.node].archived) F.node_id.value = pre.node; // an activity block's guess + } + const del = formBox.querySelector(".wl-del"); + del.hidden = !en; del.textContent = "Delete"; del.classList.remove("armed"); + err(""); + anchorEl = blk || null; + sync(); + showNew(); + formBox.hidden = false; + placeForm(); + modal(true); + (F.node_id.value ? F.note : F.node_id).focus(); + } + function closeForm() { + formBox.hidden = true; modal(false); + page.querySelectorAll(".wl-new").forEach((el) => el.remove()); + } + const err = (m) => { formBox.querySelector(".wl-err").textContent = m || ""; }; + + form.addEventListener("change", (e) => { if (e.target === F.billable) billTouched = true; sync(); }); + form.addEventListener("input", sync); + form.addEventListener("input", (e) => { if ([F.date, F.start, F.end].includes(e.target)) showNew(); }); + addEventListener("resize", () => { if (!formBox.hidden) placeForm(); }); + formBox.addEventListener("click", (e) => { + if (e.target.closest(".ec-x") || e.target.classList.contains("ec-back")) return closeForm(); + const chip = e.target.closest(".wl-recent button"); + if (chip) { F.node_id.value = chip.dataset.node; if (!editing) billTouched = false; sync(); F.note.focus(); } + }); + addEventListener("keydown", (e) => { + if (formBox.hidden) return; + if (e.key === "Escape") closeForm(); + if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) form.requestSubmit(); + }); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + if (!F.node_id.value) { err("Choose what you worked on."); return F.node_id.focus(); } + const save = form.querySelector(".wl-save"); + save.disabled = true; + try { + await post("/work/api/entry", { id: editing?.id, node_id: Number(F.node_id.value), date: F.date.value, + start: F.start.value, end: F.end.value, billable: F.billable.checked, note: F.note.value }); + try { localStorage.setItem("work.last", F.node_id.value); } catch (x) { /* private mode */ } + closeForm(); + reload(); + } catch (x) { err(x.message); } finally { save.disabled = false; } + }); + formBox.querySelector(".wl-del").addEventListener("click", async (e) => { + const b = e.target; + if (!b.classList.contains("armed")) { b.classList.add("armed"); b.textContent = "Click again to delete"; return; } + try { await post("/work/api/entry/delete", { id: editing.id }); closeForm(); reload(); } + catch (x) { err(x.message); } + }); + + fit(); + } + + // =================================================================================== + // customers + // =================================================================================== + const edit = document.getElementById("wl-edit"); + if (edit) { + const C = JSON.parse(document.getElementById("wl-cust").textContent); + const form = edit.querySelector("form"), F = form.elements; + const rates = edit.querySelector(".wl-rates"), rowTpl = document.getElementById("wl-rate-row"); + const KIND = { client: "Customer", sub: "Sub-customer", project: "Project", task: "Task" }; + let cur = null, dirty = false; + // in Settings the tab name leads the hash: #work&n=ID (dash.js reads the part before "&") + const H = page.dataset.page === "settings" ? "#work&" : "#"; + + function parentsFor(kind, self) { + const ok = { client: ["client"], project: ["client"], task: ["client", "project"] }[kind]; + const bad = new Set(); // itself + its subtree can't be its parent + if (self) { + bad.add(self); + let grew = true; + while (grew) { + grew = false; + for (const [id, d] of Object.entries(C.detail)) if (!bad.has(+id) && bad.has(d.parent_id)) { bad.add(+id); grew = true; } + } + } + return C.parents.filter((p) => ok.includes(p.kind) && !bad.has(p.id)); + } + function rateRow(r) { + const row = rowTpl.content.firstElementChild.cloneNode(true); + row.querySelector("[name=rate]").value = r ? r.rate : ""; + row.querySelector("[name=since]").value = r ? r.since : ""; + row.querySelector(".wl-cur").textContent = F.currency.value.toUpperCase() || cur?.inherit.currency || C.currency; + rates.append(row); + return row; + } + function show(d) { + cur = d; dirty = false; + const sub = d.kind === "client" && d.parent_id; + edit.querySelector(".wl-ekind").textContent = d.id ? KIND[sub ? "sub" : d.kind] : "New " + KIND[sub ? "sub" : d.kind].toLowerCase(); + edit.querySelector(".wl-epath").textContent = d.path || ""; + F.name.value = d.name || ""; + const ps = parentsFor(d.kind, d.id); + F.parent_id.replaceChildren(...(d.kind === "client" ? [new Option("— nothing (a top-level customer)", "")] : []), + ...ps.map((p) => new Option(p.label + (p.kind === "project" ? " ▣" : ""), p.id))); + F.parent_id.value = d.parent_id || ""; + edit.querySelector(".wl-parent").hidden = !ps.length && d.kind === "client"; + F.billable.options[0].text = d.parent_id || d.kind !== "client" ? `Inherit: ${d.inherit.billable}` : "Billable (default)"; + F.billable.value = d.billable === null || d.billable === undefined ? "inherit" : String(d.billable); + F.currency.value = d.currency || ""; + F.currency.placeholder = d.inherit.currency; + const top = d.kind === "client" && !d.parent_id; + F.colour.value = d.colour || d.inherit.colour || C.palette[0]; + F.colour_inherit.checked = !top && !d.colour; + edit.querySelector(".wl-cinh").hidden = top; + F.colour.disabled = F.colour_inherit.checked; + rates.replaceChildren(); + (d.rates || []).forEach(rateRow); + edit.querySelector(".wl-rinh").textContent = (d.rates || []).length ? "" : `Inherits ${d.inherit.rate}.`; + F.notes.value = d.notes || ""; + F.archived.checked = !!d.archived; + edit.querySelector(".wl-kids").hidden = !d.id || d.kind === "task"; + edit.querySelectorAll(".wl-kids [data-kind]").forEach((b) => { b.hidden = d.kind === "project" && b.dataset.kind !== "task"; }); + const del = edit.querySelector(".wl-del"); + del.hidden = !d.id; del.classList.remove("armed"); + del.textContent = "Delete"; + del.disabled = !!d.has_time; + del.title = d.has_time ? "Time is booked on it — archive it instead" : "Delete it and everything under it"; + edit.querySelector(".wl-booked").textContent = d.id ? `${d.booked} h booked` : ""; + err(""); + edit.hidden = false; + page.querySelectorAll(".wl-node").forEach((li) => li.classList.toggle("sel", +li.dataset.id === d.id)); + if (d.id) history.replaceState(null, "", H + "n=" + d.id); + if (matchMedia("(max-width: 799px)").matches) edit.scrollIntoView({ behavior: "smooth", block: "start" }); + F.name.focus(); + } + const err = (m, field) => { + edit.querySelector(".wl-err").textContent = m || ""; + form.querySelectorAll(".bad").forEach((el) => el.classList.remove("bad")); + if (field) { + const m2 = /^rates\.(\d+)\.(\w+)$/.exec(field); + const el = m2 ? rates.children[+m2[1]]?.querySelector(`[name=${m2[2]}]`) : F[field]; + el?.classList?.add("bad"); el?.focus?.(); + } + }; + function blank(kind, parent) { + const p = parent ? C.detail[parent] : null; + const pb = p && (p.billable === null ? (p.parent_id ? p.inherit.billable : "billable (default)") + : (p.billable ? "billable" : "not billable") + " from " + p.name); + const inh = p ? { rate: "the rate of " + p.name, billable: pb, + currency: p.currency || p.inherit.currency, colour: p.colour || p.inherit.colour } + : { rate: `the default rate`, billable: "billable", currency: C.currency, colour: "" }; + const used = new Set(Object.values(C.detail).filter((d) => !d.parent_id).map((d) => d.colour)); + const colour = p ? "" : C.palette.find((c) => !used.has(c)) || C.palette[used.size % C.palette.length]; + return { id: null, kind, parent_id: parent || null, name: "", colour, billable: null, currency: "", + notes: "", archived: false, rates: [], inherit: inh, path: p ? p.path + " ›" : "" }; + } + + page.addEventListener("click", (e) => { + const add = e.target.closest(".wl-add"); + if (add) return show(blank(add.dataset.kind, add.hasAttribute("data-under") ? cur?.id : null)); + const li = e.target.closest(".wl-node"); + if (li) show(C.detail[li.dataset.id]); + }); + page.addEventListener("keydown", (e) => { + const li = e.target.closest?.(".wl-node"); + if (li && e.key === "Enter") show(C.detail[li.dataset.id]); + }); + form.addEventListener("input", () => { dirty = true; }); + F.colour_inherit.addEventListener("change", () => { F.colour.disabled = F.colour_inherit.checked; }); + F.currency.addEventListener("input", () => rates.querySelectorAll(".wl-cur").forEach((s) => { s.textContent = F.currency.value.toUpperCase() || F.currency.placeholder; })); + edit.querySelector(".wl-radd").addEventListener("click", () => { + const r = rateRow(); + if (rates.children.length > 1) r.querySelector("[name=since]").value = new Date().toISOString().slice(0, 10); + edit.querySelector(".wl-rinh").textContent = ""; + r.querySelector("[name=rate]").focus(); + dirty = true; + }); + rates.addEventListener("click", (e) => { + if (!e.target.closest(".wl-x")) return; + e.target.closest(".wl-rrow").remove(); + dirty = true; + if (!rates.children.length) edit.querySelector(".wl-rinh").textContent = `Inherits ${cur.inherit.rate}.`; + }); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + const save = form.querySelector(".wl-save"); + save.disabled = true; + const top = cur.kind === "client" && !F.parent_id.value; + try { + const r = await post("/work/api/node", { + id: cur.id, kind: cur.kind, name: F.name.value, parent_id: F.parent_id.value || null, + billable: F.billable.value, currency: F.currency.value, + colour: top || !F.colour_inherit.checked ? F.colour.value : null, + notes: F.notes.value, archived: F.archived.checked, + rates: [...rates.children].map((row) => ({ rate: row.querySelector("[name=rate]").value, since: row.querySelector("[name=since]").value })), + }); + dirty = false; + history.replaceState(null, "", H + "n=" + r.id); + location.reload(); + } catch (x) { err(x.message, x.field); } finally { save.disabled = false; } + }); + edit.querySelector(".wl-del").addEventListener("click", async (e) => { + const b = e.target; + if (!b.classList.contains("armed")) { b.classList.add("armed"); b.textContent = "Click again — deletes everything under it too"; return; } + try { await post("/work/api/node/delete", { id: cur.id }); history.replaceState(null, "", location.pathname + location.search + H.slice(0, -1)); location.reload(); } + catch (x) { err(x.message); } + }); + addEventListener("beforeunload", (e) => { if (dirty) e.preventDefault(); }); + + function fromHash() { // /settings#work&n=ID opens it, #work&new a new customer + const m = /(?:^#|&)n=(\d+)$/.exec(location.hash); + if (m && C.detail[m[1]]) show(C.detail[m[1]]); + else if (/(?:^#|&)new$/.test(location.hash)) { + history.replaceState(null, "", location.pathname + location.search + H.slice(0, -1)); + show(blank("client", null)); + } + } + addEventListener("hashchange", fromHash); + fromHash(); + } +})(); diff --git a/dashboard/plugins/workload/templates/workload/_head.html b/dashboard/plugins/workload/templates/workload/_head.html new file mode 100644 index 0000000..2fe9af7 --- /dev/null +++ b/dashboard/plugins/workload/templates/workload/_head.html @@ -0,0 +1,24 @@ +{# Header of the workload pages: the core's look (⌂ 📅 … ··· ‹ title › ··· ⚙). Week ↔ Report (+ Activity, + a plugin living inside Work, while it's on) are buttons at the right end of the totals row (switch); + customers live in Settings ▸ Work. #} +{% from "_header.html" import nav_btns, settings_btn, title_block, subline %} +{% macro head(title, sub, current=True, center_href="/work", prev_href=None, next_href=None) %} +
    + {{ nav_btns() }} + {{ title_block(title, center_href, current, prev_href, next_href, prev_title="Previous week (←)", next_title="Next week (→)") }} + {{ settings_btn("work") }} +
    +{{ subline(sub) }} +{% endmacro %} + +{# Week ↔ Report + the plugins living inside Work (Activity), in the same spot on every page #} +{% macro switch() %} + + {% if tab == "report" %}Week{% else %}Report{% endif %} + {% for href, label in plugin_section("workload").tabs %}{{ label }}{% endfor %} + +{% endmacro %} + +{% macro assets() %} + +{% endmacro %} diff --git a/dashboard/plugins/workload/templates/workload/_settings.html b/dashboard/plugins/workload/templates/workload/_settings.html new file mode 100644 index 0000000..75735b7 --- /dev/null +++ b/dashboard/plugins/workload/templates/workload/_settings.html @@ -0,0 +1,79 @@ +{# Settings ▸ Work: the customer tree (views.customers) on the left, the editor of the selected + node on the right. Rendered by pluginhost for the Settings page (outside its form: it saves + on its own through /work/api/node); workload.js fills the editor from #wl-cust JSON. + Links: /settings#work&n=ID opens a node, #work&new a new customer. #} + +
    +

    Customers

    +

    Customers, sub-customers, projects and tasks: rates, billable default, notes. Each one is + saved with the editor's own Save; the plugin's settings below use the Save at the bottom.

    +
    +
    +
    + + {% if v.archived_count %} + {{ 'Hide' if v.show_archived else 'Show' }} archived ({{ v.archived_count }}) + {% endif %} + {% if v.rows %}rate · this month{% endif %} +
    + {% if not v.rows %} +

    Nothing here yet. A customer can have sub-customers, projects and tasks + (tasks also under projects). Each level can set its own hourly rate, billable default and currency — + or inherit them from above.

    + {% endif %} +
      + {% for r in v.rows %} +
    • + {{ {"client": "◆", "project": "▣", "task": "•"}[r.kind] if not r.sub else "◇" }} + {{ r.name }}{{ "sub-customer" if r.sub else ("" if r.kind == "client" else r.kind) }} + {% if not r.billable %}not billable{% endif %} + {{ r.rate }}/h + {{ r.month }} +
    • + {% endfor %} +
    +
    + + +
    + +
    + + diff --git a/dashboard/plugins/workload/templates/workload/report.html b/dashboard/plugins/workload/templates/workload/report.html new file mode 100644 index 0000000..ab3e1e1 --- /dev/null +++ b/dashboard/plugins/workload/templates/workload/report.html @@ -0,0 +1,65 @@ +{% extends "base.html" %} +{% import "workload/_head.html" as wl with context %} +{% block title %}Report · Work{% endblock %} +{% block head %}{{ wl.assets() }}{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{% block page %} +{{ wl.head("Report", frm.strftime("%-d. %b %Y") ~ " – " ~ to.strftime("%-d. %b %Y"), True, "/work/report") }} + +
    + + + – + + + + + ⇩ CSV + {{ wl.switch() }} +
    + +
    +
    Total{{ v.total }}{{ v.decimal }} h
    +
    Billable{{ v.billable }}
    +
    Not billable{{ v.unbillable }}
    +
    Amount{{ v.amounts | join(" · ") or "—" }}
    +
    + +{% if not v.rows %} +

    No time booked in this range.

    +{% else %} +
    + + + + {% for r in v.rows %} + + + + {% endfor %} + +
    Customer / project / taskHoursBillableNot billableAmount
    {{ r.name }}{{ r.hours }}{{ r.billable }}{{ r.unbillable if r.unbillable != "0:00" else "" }}{{ r.amounts | join(" · ") }}
    +
    + +
    +

    Entries {{ v.entries | length }}

    + + + + {% for i in v.entries %} + + + + + + {% endfor %} + +
    DayTimeWhatNoteHoursAmount
    {{ i.date }}{{ i.time }}{{ i.path }}{{ i.note }}{{ i.hours }}{{ i.amount if i.billable else "not billable" }}
    +
    +{% endif %} +{% endblock %} diff --git a/dashboard/plugins/workload/templates/workload/week.html b/dashboard/plugins/workload/templates/workload/week.html new file mode 100644 index 0000000..f8c4337 --- /dev/null +++ b/dashboard/plugins/workload/templates/workload/week.html @@ -0,0 +1,113 @@ +{% extends "base.html" %} +{% import "workload/_head.html" as wl with context %} +{% block title %}Work · CW {{ v.cw }}{% endblock %} +{% block head %}{{ wl.assets() }}{% endblock %} +{% block main_attrs %} data-norefresh{% endblock %} +{# Week of time entries. Geometry in % of the day's visible hours (views.week); workload.js + does the interaction: drag on a day = new entry, click a block = edit, drag a block = + move, drag its bottom edge = resize, click a faint calendar event = book it. "Activity" + (while the Activity plugin is on) adds a lane on each day's right: what ActivityWatch saw, + sorted — click a block to book it (customer guessed from its category). #} +{% block page %} +{{ wl.head("CW " ~ v.cw, v.range, v.offset == 0, "/work", "/work?w=" ~ (v.offset - 1), "/work?w=" ~ (v.offset + 1)) }} + +
    +
    {{ v.total }} h
    +
    {{ v.billable }} billable{% if v.unbillable != "0:00" %} · {{ v.unbillable }} not billable{% endif %}
    + {% if v.amounts %}
    {{ v.amounts | join(" · ") }}
    {% endif %} + {% if v.progress is not none %} +
    + {% endif %} + {% if act_on %}{% endif %} + {{ wl.switch() }} +
    + +{# customers: this week's hours per customer; click = its settings (rates, notes, projects) #} +{% if v.customers %} + +{% endif %} + +{% if v.empty_tree %} +
    No customers yet. Add your first customer (Settings ▸ Work), then drag on a day here to book time.
    +{% endif %} + +{# scrolls both ways inside the window: all 24 h, opened at the focus hours (workload.js fit()) #} +
    +
    +
    +
    + {% for c in v.cols %} +
    + {{ c.label }} + {% if c.billable %}{{ c.billable }}{% endif %}{% if c.billable and c.unbillable %} + {% endif %}{% if c.unbillable %}{{ c.unbillable }}{% endif %} +
    + {% endfor %} +
    +
    +
    {% for l in v.lines %}{{ l.label }}{% endfor %}
    + {% for c in v.cols %} +
    + {% for b in c.bands %}
    {{ b.label }}
    {% endfor %} + {% for l in v.lines %}
    {% endfor %} + {% for g in c.ghosts %} +
    {{ g.title }}
    + {% endfor %} + {% for b in c.blocks %} +
    +
    {{ b.name }}{% if b.client %} {{ b.client }}{% endif %}
    +
    {{ b.time }} · {{ b.dur }}{% if not b.billable %} · not billable{% endif %}
    + {% if b.note %}
    {{ b.note }}
    {% endif %} + {% if not b.cont_after %}
    {% endif %} +
    + {% endfor %} + {% for a in c.act %} +
    {% if a.height > 2.2 %}{{ a.name }}{% endif %}
    + {% endfor %} + {% if c.now is not none and 0 <= c.now <= 100 %}
    {% endif %} +
    + {% endfor %} +
    +
    +
    +

    Drag on a day to book time · click a block to edit · drag it to move, its bottom edge to resize{% if v.cols | selectattr("ghosts") | list %} · click a faint calendar event to book it{% endif %}{% if show_act %} · click an activity block (right lane) to book it{% endif %}

    + +{% endblock %} + +{% block scripts %} +{# entry form (no browser dialogs) #} + + +{% endblock %} diff --git a/dashboard/plugins/workload/views.py b/dashboard/plugins/workload/views.py new file mode 100644 index 0000000..8b48e34 --- /dev/null +++ b/dashboard/plugins/workload/views.py @@ -0,0 +1,303 @@ +"""View models for the workload pages: plain dicts, geometry in % (like webview.py).""" +from datetime import date, datetime, time, timedelta + +from . import db + +WEEKDAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun") + + +def hm(minutes): + """90 -> '1:30'.""" + m = int(round(minutes or 0)) + return f"{m // 60}:{m % 60:02d}" + + +def money(amount, currency): + return f"{amount:,.2f} {currency}".replace(",", " ") + + +def _amount(tree, e): + """(minutes, amount, currency) of one entry; unbillable work is worth 0.""" + minutes = (e["e"] - e["s"]).total_seconds() / 60 + cur = tree.currency(e["node_id"]) + if not e["billable"]: + return minutes, 0.0, cur + rate, _ = tree.rate(e["node_id"], e["start"][:10]) + return minutes, minutes / 60 * rate, cur + + +def node_list(tree, today): + """Everything the entry form can pick, in tree order, with what it inherits: + [{id, label, path, depth, kind, colour, billable, bsrc, currency, rchain}]. + rchain = the rate histories up the tree (nearest first) so the form can show the + rate in force on the entry's date: [{src, rates: [[since, rate], …]}].""" + out = [] + for n, depth in tree.walk(include_archived=True): + nid = n["id"] + billable, bsrc = tree.billable(nid) + out.append({"id": nid, "label": n["name"], "path": tree.path(nid), "depth": depth, "kind": n["kind"], + "colour": tree.colour(nid), "billable": billable, "bsrc": bsrc["name"] if bsrc else "", + "currency": tree.currency(nid), "archived": tree.archived(nid), + "rchain": [{"src": c["name"], "rates": [[r["since"], r["rate"]] for r in tree.rates[c["id"]]]} + for c in tree.chain(nid) if tree.rates.get(c["id"])]}) + return out + + +def _lanes(items): + """Overlap layout: sets it['lane'], it['lanes'] per cluster of overlapping items.""" + cluster, end = [], None + + def flush(): + n = max((i["lane"] for i in cluster), default=0) + 1 + for i in cluster: + i["lanes"] = n + + for it in sorted(items, key=lambda i: (i["a"], -i["b"])): + if cluster and it["a"] >= end: + flush() + cluster, end = [], None + used = {c["lane"] for c in cluster if c["b"] > it["a"]} + it["lane"] = next(i for i in range(len(cluster) + 1) if i not in used) + cluster.append(it) + end = it["b"] if end is None else max(end, it["b"]) + if cluster: + flush() + return items + + +def week_start(offset): + """Monday 00:00 of the week `offset` weeks from this one.""" + today = date.today() + return datetime.combine(today - timedelta(days=today.weekday()) + timedelta(weeks=offset), time()) + + +def _guess(tree, names): + """The customer / project an activity block is probably for: the first of its category names + (nearest first: "Rocket", "Acme", "Customer", "Work") that's a live node's name, or None.""" + by_name = {} + for n, _ in tree.walk(): + by_name.setdefault(n["name"].strip().lower(), n["id"]) + return next((by_name[x.strip().lower()] for x in names if x.strip().lower() in by_name), None) + + +def week(con, tree, s, offset, cal_events, bands=lambda day: [], acts=None): + """acts = Activity's blocks {iso: [...]} for the lane beside the bookings, or None (off).""" + today = date.today() + ws = week_start(offset) + monday = ws.date() + we = ws + timedelta(days=7) + entries = db.entries_between(con, ws, we) + + # all 24 hours are drawn; the focus hours (settings) are what the page scrolls to / fits + h0, h1 = 0, 24 + span = (h1 - h0) * 60 + + def y(minutes): + return round((minutes - h0 * 60) / span * 100, 3) + + cols, tot_m, tot_bm, amounts = [], 0, 0, {} + for d in range(7): + day = monday + timedelta(days=d) + d0 = datetime.combine(day, time()) + d1 = d0 + timedelta(days=1) + blocks, day_m, day_bm = [], 0, 0 + for e in entries: + a, b = max(e["s"], d0), min(e["e"], d1) + if a >= b: + continue + am, bm = (a - d0).total_seconds() / 60, (b - d0).total_seconds() / 60 + dur = bm - am + day_m += dur + day_bm += dur if e["billable"] else 0 + n = tree.nodes.get(e["node_id"]) + top = tree.client_of(e["node_id"]) + blocks.append({"id": e["id"], "a": am, "b": bm, "top": y(am), "height": y(bm) - y(am), + "colour": tree.colour(e["node_id"]), "billable": bool(e["billable"]), + "name": n["name"] if n else "?", + "client": top["name"] if top and n and top["id"] != n["id"] else "", + "time": f"{e['s']:%H:%M}–{e['e']:%H:%M}", "dur": hm((e["e"] - e["s"]).total_seconds() / 60), + "note": e["note"].split("\n", 1)[0][:120], + "cont_before": e["s"] < d0, "cont_after": e["e"] > d1}) + _lanes(blocks) + ghosts = [] + for ev in cal_events: + if ev["all_day"]: + continue + a, b = max(ev["start"], d0), min(ev["end"], d1) + if a >= b: + continue + am, bm = (a - d0).total_seconds() / 60, (b - d0).total_seconds() / 60 + ghosts.append({"top": y(am), "height": y(bm) - y(am), "title": ev["title"][:80], + "colour": ev.get("colour") or "#8b929e", "calendar": ev.get("calendar", ""), + "start": f"{a:%H:%M}", "end": "24:00" if b == d1 else f"{b:%H:%M}"}) + act = [] + for b in (acts or {}).get(day.isoformat(), []): + act.append({"top": y(b["a"]), "height": max(0.3, y(b["b"]) - y(b["a"])), "start": b["start"], "end": b["end"], + "colour": b["color"], "path": b["path"], "name": b["name"], "what": " · ".join(b["top"]), + "dur": b["dur"], "node": _guess(tree, b["names"]) or ""}) + now_y = None + if day == today: + n = datetime.now() + now_y = y(n.hour * 60 + n.minute) + cols.append({"iso": day.isoformat(), "label": f"{WEEKDAYS[d]} {day.day}", "today": day == today, + "weekend": d >= 5, "blocks": blocks, "ghosts": ghosts, "now": now_y, "act": act, + "bands": [{"top": y(b["start"] * 60), "height": y(b["end"] * 60) - y(b["start"] * 60), + "label": b["label"]} for b in bands(day)], + "billable": hm(day_bm) if day_bm else "", + "unbillable": hm(day_m - day_bm) if day_m - day_bm else ""}) + tot_m += day_m + tot_bm += day_bm + per = {} # top-level customer -> [minutes, {currency: amount}] + for e in entries: # money by the entry's own date + rate + minutes, amt, cur = _amount(tree, e) + if e["billable"]: + amounts[cur] = amounts.get(cur, 0) + amt + top = tree.client_of(e["node_id"]) + if top: + p = per.setdefault(top["id"], [0, {}]) + p[0] += minutes + if e["billable"]: + p[1][cur] = p[1].get(cur, 0) + amt + # every live customer (the strip under the totals: a way into its settings), busiest first + customers = [] + for n, _ in tree.walk(): + if n["parent_id"] is None: + m, amt = per.get(n["id"], [0, {}]) + rate, _ = tree.rate(n["id"], today.isoformat()) + customers.append({"id": n["id"], "name": n["name"], "colour": tree.colour(n["id"]), + "hours": hm(m) if m else "", "m": m, + "amount": " · ".join(money(v, c) for c, v in sorted(amt.items()) if v), + "rate": f"{rate:g} {tree.currency(n['id'])}/h", + "notes": n["notes"].strip().split("\n", 1)[0][:80]}) + customers.sort(key=lambda c: -c["m"]) + + iso = monday.isocalendar() + sunday = monday + timedelta(days=6) + rng = (f"{monday.day}. – {sunday.day}. {sunday:%B %Y}" if monday.month == sunday.month + else f"{monday.day}. {monday:%b} – {sunday.day}. {sunday:%b %Y}") + target = float(s.get("week_target") or 0) + return { + "offset": offset, "cw": iso[1], "range": rng, "cols": cols, + "lines": [{"top": y(h * 60), "label": f"{h:02d}"} for h in range(h0, h1 + 1)], + "h0": h0, "h1": h1, "focus": [int(s["day_start"]), int(s["day_end"])], + "total": hm(tot_m), "billable": hm(tot_bm), "unbillable": hm(tot_m - tot_bm), + "amounts": [money(a, c) for c, a in sorted(amounts.items())], + "target": target, "progress": min(100, round(tot_m / 60 / target * 100)) if target else None, + "entries": {e["id"]: {"id": e["id"], "node_id": e["node_id"], "start": e["start"], "end": e["end"], + "billable": bool(e["billable"]), "note": e["note"]} for e in entries}, + "empty_tree": not tree.nodes, "customers": customers, + } + + +# ---- report ---------------------------------------------------------------------------- + +PRESETS = (("week", "This week"), ("lastweek", "Last week"), ("month", "This month"), + ("lastmonth", "Last month"), ("year", "This year"), ("lastyear", "Last year")) + + +def preset_range(name, today=None): + t = today or date.today() + mon = t - timedelta(days=t.weekday()) + if name == "week": + return mon, mon + timedelta(days=6) + if name == "lastweek": + return mon - timedelta(days=7), mon - timedelta(days=1) + first = t.replace(day=1) + nxt = (first + timedelta(days=32)).replace(day=1) + if name == "month": + return first, nxt - timedelta(days=1) + if name == "lastmonth": + prev = (first - timedelta(days=1)).replace(day=1) + return prev, first - timedelta(days=1) + if name == "year": + return t.replace(month=1, day=1), t.replace(month=12, day=31) + if name == "lastyear": + return date(t.year - 1, 1, 1), date(t.year - 1, 12, 31) + return None + + +def report(con, tree, frm, to, client=None): + """Hours + money in [frm, to] (dates, inclusive), as a tree; `client` limits it to + one node's subtree. Entries are counted on the day they start.""" + keep = tree.subtree(client) if client in tree.nodes else None + start, end = datetime.combine(frm, time()), datetime.combine(to + timedelta(days=1), time()) + rows = [e for e in db.entries_between(con, start - timedelta(days=1), end, keep) if start <= e["s"] < end] + agg, items, totals = {}, [], {"m": 0, "bm": 0, "amounts": {}} + for e in rows: + minutes, amt, cur = _amount(tree, e) + rate, _ = tree.rate(e["node_id"], e["start"][:10]) + for n in tree.chain(e["node_id"]): + a = agg.setdefault(n["id"], {"m": 0, "bm": 0, "amounts": {}}) + a["m"] += minutes + if e["billable"]: + a["bm"] += minutes + a["amounts"][cur] = a["amounts"].get(cur, 0) + amt + totals["m"] += minutes + if e["billable"]: + totals["bm"] += minutes + totals["amounts"][cur] = totals["amounts"].get(cur, 0) + amt + items.append({"id": e["id"], "date": f"{e['s']:%a %d.%m.}", "iso": e["start"][:10], + "w": (e["s"].date() - week_start(0).date()).days // 7, + "time": f"{e['s']:%H:%M}–{e['e']:%H:%M}", "path": tree.path(e["node_id"]), + "colour": tree.colour(e["node_id"]), "note": e["note"], "minutes": minutes, + "hours": hm(minutes), "billable": bool(e["billable"]), + "rate": f"{rate:g}" if e["billable"] else "", + "amount": money(amt, cur) if e["billable"] else "", "currency": cur, "amount_raw": amt, + "start": e["start"], "end": e["end"]}) + out = [] + for n, depth in tree.walk(include_archived=True): + a = agg.get(n["id"]) + if not a: + continue + out.append({"id": n["id"], "name": n["name"], "kind": n["kind"], "depth": depth, + "colour": tree.colour(n["id"]), "hours": hm(a["m"]), "billable": hm(a["bm"]), + "unbillable": hm(a["m"] - a["bm"]), "decimal": f"{a['m'] / 60:.2f}", + "amounts": [money(v, c) for c, v in sorted(a["amounts"].items())]}) + return {"rows": out, "entries": items, + "total": hm(totals["m"]), "billable": hm(totals["bm"]), "unbillable": hm(totals["m"] - totals["bm"]), + "decimal": f"{totals['m'] / 60:.2f}", + "amounts": [money(v, c) for c, v in sorted(totals["amounts"].items())]} + + +# ---- customers page ------------------------------------------------------------------ + +def customers(con, tree, show_archived): + booked = db.booked_minutes(con) + first = date.today().replace(day=1) + month = {} + for e in db.entries_between(con, datetime.combine(first, time()), datetime.now() + timedelta(days=1)): + for n in tree.chain(e["node_id"]): + month[n["id"]] = month.get(n["id"], 0) + (e["e"] - e["s"]).total_seconds() / 60 + today = date.today().isoformat() + rows, detail = [], {} + for n, depth in tree.walk(include_archived=show_archived): + nid = n["id"] + total = sum(booked.get(i, 0) for i in tree.subtree(nid)) + rate, _ = tree.rate(nid, today) + billable, _ = tree.billable(nid) + own_rate = tree.rates.get(nid, []) + rows.append({"id": nid, "name": n["name"], "kind": n["kind"], "depth": depth, "archived": tree.archived(nid), + "colour": tree.colour(nid), "sub": n["kind"] == "client" and n["parent_id"] is not None, + "month": hm(month.get(nid, 0)) if month.get(nid) else "", + "rate": f"{rate:g} {tree.currency(nid)}", "own_rate": bool(own_rate), + "billable": billable, "own_billable": n["billable"] is not None}) + inh_parent = tree.nodes.get(n["parent_id"]) + p_rate, p_rsrc = tree.rate(n["parent_id"], today) if inh_parent else (tree.default_rate, None) + p_bill, p_bsrc = tree.billable(n["parent_id"]) if inh_parent else (True, None) + detail[nid] = { + "id": nid, "kind": n["kind"], "parent_id": n["parent_id"], "name": n["name"], + "colour": n["colour"] or "", "billable": n["billable"], "currency": n["currency"] or "", + "notes": n["notes"], "archived": bool(n["archived"]), + "rates": [{"since": "" if r["since"] == db.EPOCH else r["since"], "rate": r["rate"]} for r in own_rate], + "booked": hm(total), "has_time": total > 0, "path": tree.path(nid), + "inherit": {"rate": f"{p_rate:g} {tree.currency(n['parent_id']) if inh_parent else tree.default_currency}/h" + + (f" from {p_rsrc['name']}" if p_rsrc else " (default)"), + "billable": ("billable" if p_bill else "not billable") + + (f" from {p_bsrc['name']}" if p_bsrc else " (default)"), + "currency": (tree.currency(n["parent_id"]) if inh_parent else tree.default_currency), + "colour": tree.colour(n["parent_id"]) if inh_parent else ""}, + } + parents = [{"id": n["id"], "kind": n["kind"], "label": tree.path(n["id"])} + for n, _ in tree.walk(include_archived=True) if n["kind"] in ("client", "project")] + return {"rows": rows, "detail": detail, "parents": parents, "show_archived": show_archived, + "archived_count": sum(1 for n in tree.nodes.values() if n["archived"])} diff --git a/dashboard/requirements.txt b/dashboard/requirements.txt new file mode 100644 index 0000000..2774c5a --- /dev/null +++ b/dashboard/requirements.txt @@ -0,0 +1,12 @@ +# For a virtualenv / pip install. On Raspberry Pi OS / Debian, install.sh uses the apt packages instead +# (python3-pil python3-numpy python3-evdev python3-caldav python3-recurring-ical-events python3-flask python3-nacl +# python3-qrcode python3-paho-mqtt). evdev only matters with the touch screen; leave it out elsewhere. +Pillow>=9.4 +numpy>=1.24 +Flask>=2.2 +caldav>=1.0 # the Nextcloud / CalDAV calendar (optional) +recurring-ical-events>=2.0 # repeating events in ICS subscriptions (optional) +PyNaCl>=1.5 # sync (optional) +qrcode>=7.0 # the phone's QR code in Settings ▸ General ▸ Sync (optional) +paho-mqtt>=1.6 # MQTT sensors (optional) +evdev>=1.6; sys_platform == "linux" # the touch screen (optional) diff --git a/dashboard/screens.py b/dashboard/screens.py new file mode 100644 index 0000000..85f8e10 --- /dev/null +++ b/dashboard/screens.py @@ -0,0 +1,89 @@ +"""The 3.5" panel's frame: Home, the plugins' screens, Settings + the compositor. + +The screens are a list (`screen_list`): Home (the core's), then every screen of the plugins +that are on (ctx.screen — the stations' Temp, the weather, the calendar …), then Settings +(the core's); `store.screen` indexes it, the bottom bar (panel.draw_nav) shows one button +each. `render()` paints the background, the coloured top line, the screen and the bar — +exactly one frame. + +Home = the clock and the date (the core) + three parts the plugins draw (ctx.home_screen): +"agenda" (the left column under the date: the calendar), "corner" (top right: the weather), +"indoor" (bottom right: the main temperature). A part nobody draws stays empty. + +To redesign the UI: colours in `config.THEME`, shared widgets in `panel.py`, the plugins' +screens in their screens.py. +""" +from datetime import datetime + +from PIL import Image, ImageDraw + +import backlight +import pluginhost +from config import THEME, TOP_H +from panel import draw_nav, ic_home, ic_settings +from store import hit + + +def screen_home(img, d, panel, store): + now = datetime.now() + d.text((16, 6), now.strftime("%H:%M"), font=panel.f["xl"], fill=THEME["fg"]) + d.text((16, 64), now.strftime("%A, %d %B"), font=panel.f["md"], fill=THEME["muted"]) + for slot in ("corner", "indoor", "agenda"): + fn = pluginhost.home_slot(store, slot) + if fn: + fn(img, d, panel, store) + + +def screen_settings(img, d, panel, store): + d.text((16, 8), "Settings", font=panel.f["lg"], fill=THEME["fg"]) + + # Brightness — auto from sunrise/sunset (the weather plugin), else fixed hours. Read-only. + d.text((16, 44), f"Brightness (auto · {store.brightness * 100:.0f}%)", + font=panel.f["md"], fill=THEME["fg"]) + sr, ss = backlight.sun_times(store) + sun = (f"Sun ↑ {sr.strftime('%H:%M')} · ↓ {ss.strftime('%H:%M')}" + if sr and ss else "Sun times: loading…") + d.text((16, 74), sun, font=panel.f["sm"], fill=THEME["muted"]) + + # Temperature unit row + d.text((16, 116), "Temperature unit", font=panel.f["md"], fill=THEME["fg"]) + bx, by = 16, 144 + for label, val in (("Celsius", "metric"), ("Fahrenheit", "imperial")): + w = d.textlength(label, font=panel.f["md"]) + 24 + sel = store.units == val + d.rounded_rectangle([bx, by, bx + w, by + 34], radius=8, + fill=THEME["highlight"] if sel else THEME["card"]) + d.text((bx + 12, by + 5), label, font=panel.f["md"], + fill=THEME["ink"] if sel else THEME["muted"]) + hit(store, (bx, by, bx + w, by + 34), lambda v=val: store.set_units(v)) + bx += w + 12 + d.text((16, 190), "‹ › toggle units", font=panel.f["xs"], fill=THEME["dim"]) + + wx = pluginhost.ask(store, "weather", "status") + if wx is not None: + d.text((16, 216), f"Weather: {wx}", font=panel.f["sm"], fill=THEME["muted"]) + d.text((16, 240), f"Location: {store.cfg.get('location_name', '—')}", + font=panel.f["xs"], fill=THEME["dim"]) + + +HOME = {"label": "Home", "icon": ic_home, "render": screen_home, "key": None, "open": None, "stay": lambda: True} +SETTINGS = {"label": "Set", "icon": ic_settings, "render": screen_settings, + "key": lambda ch: None, "open": None, "stay": None, "units": True} + + +def screen_list(store): + """Home, the plugins' screens (the ones on), Settings.""" + return [HOME] + pluginhost.screens(store) + [SETTINGS] + + +def render(panel, store): + img = Image.new("RGB", (panel.w, panel.h), THEME["bg"]) + d = ImageDraw.Draw(img) + d.rectangle([0, 0, panel.w, TOP_H], fill=THEME["topline"]) # the one coloured line + store.hits = [] + screens = screen_list(store) + if store.screen >= len(screens): # a plugin was switched off under it + store.screen = 0 + screens[store.screen]["render"](img, d, panel, store) + draw_nav(d, panel, store, screens) + return img diff --git a/dashboard/settings.py b/dashboard/settings.py new file mode 100644 index 0000000..c8809f5 --- /dev/null +++ b/dashboard/settings.py @@ -0,0 +1,331 @@ +"""Settings page (/settings): what dash_config.json holds, editable from the browser. + +`view(store)` gives the template the current values (secrets only as "set / not +set" — they never leave the Pi), `apply(store, data)` validates a submitted form, +writes dash_config.json and applies what it can live: + + live units, location + OWM key (weather worker woken), extra weather places, + everything under calendar (the sync is rebuilt), the day-view bands, cards + elsewhere the sensors (Settings ▸ Sensors, plugins/stations), the web address (Settings ▸ General, + system.py — after `restart()`, which re-executes the dashboard process in place) +""" +import copy +import json +import os +import re +import sys +import threading +import time +import urllib.parse +import urllib.request +from datetime import datetime + +from config import save_config +import pluginhost + +SECRETS = ("owm_api_key", "calendar.app_password") +GEOCODE = "https://geocoding-api.open-meteo.com/v1/search" +MAX_PLACES = 6 +WEEKDAYS = ("Mo", "Tu", "We", "Th", "Fr", "Sa", "Su") + + +class Invalid(ValueError): + """A field the form must fix: (field name, message).""" + + def __init__(self, field, msg): + super().__init__(msg) + self.field = field + + +def _get(cfg, path, default=None): + node = cfg + for k in path.split("."): + if not isinstance(node, dict) or k not in node: + return default + node = node[k] + return node + + +def calendar_names(store, pictograms=False): + """Display names of every calendar the sync knows (read-only ones included); + pictograms=True leaves out the contacts' birthdays (they always get 🎂).""" + from plugins.calendar.cal import BIRTHDAY_CAL + with store.lock: + names = {meta.get("cal_name") for meta, _, _ in store.cal_sources + if not (pictograms and meta.get("cal") == BIRTHDAY_CAL)} + return sorted(n for n in names if n) + + +def view(store): + cfg = store.cfg + c = cfg.get("calendar") or {} + + def band(key, default): + b = c.get(key) + return {"on": bool(b), "start": (b or default)["start"], "end": (b or default)["end"], + "weekdays": (b or {}).get("weekdays") or []} + + names = calendar_names(store) + icons = c.get("icons") or {} + with store.lock: + cols = list(store.cal_collections) + def failing(e): # "since 16 Oct 16:35 · 414× · last 00:12" + if not e: + return None + f = lambda t: datetime.fromtimestamp(t).strftime("%-d %b %H:%M" if time.time() - t > 86400 else "%H:%M") + return {"error": e.get("error", ""), "count": e.get("count", 0), "since": f(e["since"]), "last": f(e.get("last", e["since"]))} + rows = [dict(r, glyph=icons.get(r["name"], ""), failing=failing(r.get("error"))) for r in cols] + return { + "units": cfg.get("units", "metric"), + "location": {"name": cfg.get("location_name", ""), "lat": cfg.get("lat"), "lon": cfg.get("lon")}, + "places": cfg.get("weather_locations") or [], + "secret": {k: bool(_get(cfg, k)) for k in SECRETS}, + "cal": {"enabled": bool(c.get("enabled")), "caldav_url": c.get("caldav_url", ""), + "username": c.get("username", ""), "rows": rows, "other_glyph": icons.get("*", ""), + "anniv": bool(c.get("show_anniversaries")), "death": bool(c.get("show_death_dates")), + "feed_language": c.get("feed_language", ""), + "feeds": "\n".join(f"{f['name']} = {f['url']}" if f.get("name") and f["name"] != f["url"] else f["url"] + for f in c.get("feeds") or [] if isinstance(f, dict) and f.get("url")), + "local_name": c.get("local_name") or "Local", "local_color": c.get("local_color") or "#c792ea", + "cards": list(c.get("card_calendars") or [])[:2], + "sleep": band("sleep", {"start": "00:00", "end": "07:00"}), + "lunch": band("lunch_break", {"start": "13:00", "end": "14:00"})}, + "names": names, + "web": {"host": _get(cfg, "web.host", "0.0.0.0"), "port": _get(cfg, "web.port", 8080)}, + "status": status(store), + "restart": store.restart_needed, + "weekdays": WEEKDAYS, + "plugins": pluginhost.settings_view(store), + } + + +def status(store): + """What the workers say right now (the page shows it next to each section).""" + return {"weather": store.wx_status, "openmeteo": store.om_status, "calendar": store.cal_status, + "sensors": store.sensors_status, + "sources": [s.name or f"#{s.device_id}" for s in store.sources if s.device_id is not None]} + + +# ---- validation --------------------------------------------------------------------- + +def _str(d, key, field, max_len=200): + v = d.get(key, "") + if not isinstance(v, str): + raise Invalid(field, "Must be text.") + v = v.strip() + if len(v) > max_len: + raise Invalid(field, f"At most {max_len} characters.") + return v + + +def _float(v, field, lo, hi): + try: + f = float(str(v).replace(",", ".")) + except (TypeError, ValueError): + raise Invalid(field, "Must be a number.") + if not lo <= f <= hi: + raise Invalid(field, f"Must be between {lo} and {hi}.") + return f + + +def _url(v, field, required=False): + if not v: + if required: + raise Invalid(field, "Required.") + return "" + p = urllib.parse.urlparse(v) + if p.scheme not in ("http", "https") or not p.netloc: + raise Invalid(field, "Must start with https:// (or http://).") + return v + + +def _feeds(text): + """Settings ▸ Calendar ▸ Calendar feeds: one a line, "Name = https://…/calendar.ics" or just the address.""" + out = [] + for i, line in enumerate(str(text or "").splitlines()[:20]): + line = line.strip() + if not line: + continue + name, _, url = line.rpartition(" = ") if " = " in line else ("", "", line) + url = url.strip().replace("webcals://", "https://").replace("webcal://", "https://") + p = urllib.parse.urlparse(url) + if p.scheme not in ("http", "https") or not p.netloc or len(url) > 1000: + raise Invalid("cal.feeds", f"Line {i + 1}: an address starting with https:// (or webcal://).") + out.append({"name": name.strip()[:60] or p.netloc, "url": url}) + return out + + +def _hhmm(v, field): + if not re.fullmatch(r"([01]\d|2[0-3]):[0-5]\d", str(v or "")): + raise Invalid(field, "Time as HH:MM.") + return v + + +def _band(d, field): + if not d or not d.get("on"): + return None + out = {"start": _hhmm(d.get("start"), field + ".start"), "end": _hhmm(d.get("end"), field + ".end")} + if out["start"] == out["end"]: + raise Invalid(field + ".end", "Start and end are the same.") + days = sorted({int(x) for x in d.get("weekdays") or [] if str(x).isdigit() and 1 <= int(x) <= 7}) + if days and len(days) < 7: + out["weekdays"] = days + return out + + +def build(cfg, d): + """New config from the old one + the submitted form `d` (raises Invalid).""" + new = copy.deepcopy(cfg) + new["units"] = d.get("units") if d.get("units") in ("metric", "imperial") else "metric" + + loc = d.get("location") or {} + new["location_name"] = _str(loc, "name", "location.name", 80) or "Home" + new["lat"] = _float(loc.get("lat"), "location.lat", -90, 90) + new["lon"] = _float(loc.get("lon"), "location.lon", -180, 180) + + places = [] + for i, p in enumerate((d.get("places") or [])[:MAX_PLACES]): + name = _str(p, "name", f"places.{i}.name", 80) + if not name: + raise Invalid(f"places.{i}.name", "Give the place a name.") + places.append({"name": name, "lat": _float(p.get("lat"), f"places.{i}.lat", -90, 90), + "lon": _float(p.get("lon"), f"places.{i}.lon", -180, 180)}) + if places: + new["weather_locations"] = places + else: + new.pop("weather_locations", None) + + c = d.get("cal") or {} + cc = new.setdefault("calendar", {}) + cc["enabled"] = bool(c.get("enabled")) + cc["caldav_url"] = _url(_str(c, "caldav_url", "cal.caldav_url", 300), "cal.caldav_url", cc["enabled"]) + cc["username"] = _str(c, "username", "cal.username", 100) + if cc["enabled"] and not cc["username"]: + raise Invalid("cal.username", "Required when the calendar is on.") + cc["feeds"] = _feeds(c.get("feeds")) + cc["show_anniversaries"] = bool(c.get("anniv")) + cc["show_death_dates"] = bool(c.get("death")) + lang = _str(c, "feed_language", "cal.feed_language", 10) + if lang and not re.fullmatch(r"[a-zA-Z]{2,3}(-[a-zA-Z]{2})?", lang): + raise Invalid("cal.feed_language", "A language code like en, sk or en-GB.") + if lang: + cc["feed_language"] = lang + else: + cc.pop("feed_language", None) + cc["local_name"] = _str(c, "local_name", "cal.local_name", 40) or "Local" + colour = _str(c, "local_color", "cal.local_color", 7) + if not re.fullmatch(r"#[0-9a-fA-F]{6}", colour): + raise Invalid("cal.local_color", "A colour like #c792ea.") + cc["local_color"] = colour.lower() + cards = [_str({"v": v}, "v", "cal.cards", 100) for v in (c.get("cards") or [])][:2] + cc["card_calendars"] = [v for v in cards if v] + for key, field in (("sleep", "cal.sleep"), ("lunch_break", "cal.lunch")): + b = _band(c.get(field.split(".")[1]), field) + if b: + cc[key] = b + else: + cc.pop(key, None) + # the calendars table: one row per calendar Nextcloud has (+ Local). No rows = the sync + # hasn't listed them yet -> keep what is configured. + rows = [r for r in c.get("rows") or [] if isinstance(r, dict) and str(r.get("name") or "").strip()] + if rows: + icons = {k: v for k, v in (cc.get("icons") or {}).items() # keep calendars not listed now + if k != "*" and k not in {str(r["name"]).strip() for r in rows}} + hidden, no_create = [], [] + for i, r in enumerate(rows): + name, glyph = str(r["name"]).strip(), str(r.get("glyph") or "").strip() + if len(glyph) > 4: + raise Invalid(f"cal.rows.{i}.glyph", f"{name}: one pictogram, please.") + if glyph: + icons[name] = glyph + if not r.get("shown"): + hidden.append(name) + if r.get("create") is False: # absent = read-only row (its box is disabled) + no_create.append(name) + cc["hidden_calendars"], cc["no_create"] = hidden, no_create + cc.pop("calendar_name", None) # the old "show only one" setting, now per row + else: + icons = {k: v for k, v in (cc.get("icons") or {}).items() if k != "*"} + other = _str(c, "other_glyph", "cal.other_glyph", 4) + if other: + icons["*"] = other + cc["icons"] = icons + + if "plugins" in d: # Settings ▸ Plugins (pluginhost.build_settings) + try: + new["plugins"] = pluginhost.build_settings(cfg, d.get("plugins")) + except pluginhost.Invalid as e: + raise Invalid(e.field, str(e)) + + # secrets: only replaced when something was typed + for path in SECRETS: + v = _get(d.get("secret") or {}, path.replace(".", "_")) + if isinstance(v, str) and v.strip(): + *parents, leaf = path.split(".") + node = new + for k in parents: + node = node.setdefault(k, {}) + node[leaf] = v.strip() + if cc["enabled"] and not cc.get("app_password"): + raise Invalid("secret.calendar_app_password", "Required when the calendar is on.") + return new + + +# ---- applying -------------------------------------------------------------------------- + +def save_part(store, key, value): + """One top-level section changed outside the Settings form (Settings ▸ General ▸ Sync, ▸ Web): saved and live.""" + new = json.loads(json.dumps(store.cfg)) + new[key] = value + save_config(new) + with store.lock: + store.cfg.clear() + store.cfg.update(new) + + +def apply(store, d): + """Validate + save + apply live. Returns {"restart": bool} (raises Invalid).""" + old = store.cfg + new = build(old, d) + save_config(new) + restart = False + with store.lock: # same dict object the workers hold + old.clear() + old.update(new) + store.units = new["units"] + store.om_wake.set() # Open-Meteo: the main place + from plugins.weather.weather import forget_places + forget_places() # extra places: re-fetched on next view + store.cal_reset = True # rebuild the calendar sync (URL, icons, …) + store.cal_wake.set() + if restart: + store.restart_needed = True + return {"restart": bool(getattr(store, "restart_needed", False))} + + +def restart(store): + """Re-execute the dashboard in place (same PID, so systemd doesn't notice) after a + short delay, so the HTTP answer still goes out. The plugins save what's in memory first + (the stations' 24 h history and the readings of the current 5 minutes).""" + def go(): + time.sleep(0.5) + try: + import pluginhost + pluginhost.shutdown() + finally: + os.execv(sys.executable, [sys.executable] + sys.argv) + threading.Thread(target=go, daemon=True).start() + + +def geocode(q): + """Open-Meteo place search -> [{name, label, lat, lon}] (max 6).""" + url = GEOCODE + "?" + urllib.parse.urlencode({"name": q, "count": 6, "language": "en", "format": "json"}) + with urllib.request.urlopen(url, timeout=10) as r: + data = json.load(r) + out = [] + for p in data.get("results") or []: + region = ", ".join(x for x in (p.get("admin1"), p.get("country_code")) if x) + out.append({"name": f"{p['name']}, {p.get('country_code', '')}".rstrip(", "), + "label": f"{p['name']}" + (f" — {region}" if region else ""), + "lat": round(p["latitude"], 5), "lon": round(p["longitude"], 5)}) + return out diff --git a/dashboard/static/dash.css b/dashboard/static/dash.css new file mode 100644 index 0000000..ea97973 --- /dev/null +++ b/dashboard/static/dash.css @@ -0,0 +1,749 @@ +/* Dashboard web pages — responsive. + + Every size is written as calc(var(--k) * N), where N is the size in "design px" + of the 1920×1080 wall layout. --k is what one design px is worth: + + - wall mode (a landscape window at least 1000 px wide): --k scales the design to + fit the window, and Home / week / month (body.wall) fill it without scrolling — + the TV / monitor look; + - stacked mode (phones, tablets, portrait windows): --k is a fixed-ish 0.62–0.9 px, + the page scrolls, Home's regions reflow into one or two columns, the week view + and the weather charts scroll sideways, the month grid shows dots on phones. */ +@font-face { font-family: "DejaVu Web"; src: url("/fonts/dejavu.ttf"); font-weight: 400; font-display: swap; } +@font-face { font-family: "DejaVu Web"; src: url("/fonts/dejavu-bold.ttf"); font-weight: 700; font-display: swap; } +@font-face { font-family: "Symbola Web"; src: url("/fonts/emoji.ttf"); font-display: block; } + +:root { --k: clamp(0.62px, calc(100vw / 1000), 0.9px); --gap: calc(var(--k) * 16); --r: calc(var(--k) * 14); } + +html { background: var(--bg); } +body { margin: 0; min-height: 100vh; background: var(--bg); color: var(--fg); + font-family: "DejaVu Web", "Symbola Web", sans-serif; font-size: calc(var(--k) * 20); + -webkit-text-size-adjust: 100%; } +body::before { content: ""; position: fixed; left: 0; right: 0; top: 0; z-index: 5; /* amber top line */ + height: calc(var(--k) * 7); background: var(--accent); } +a { color: inherit; text-decoration: none; } +#page { box-sizing: border-box; padding: calc(var(--k) * 19) var(--gap) var(--gap); } +.g { font-family: "Symbola Web", "DejaVu Web"; font-variant-emoji: text; } +.cool { color: var(--cool); } .muted { color: var(--muted); } .dim { color: var(--dim); } +.caption { font: 700 calc(var(--k) * 18)/1 "DejaVu Web"; color: var(--dim); text-transform: uppercase; } +.hscroll { overflow-x: auto; overflow-y: hidden; -webkit-overflow-scrolling: touch; + scrollbar-width: thin; scrollbar-color: #2c3343 transparent; } +.wp-card .hscroll { margin: 0 calc(var(--k) * -20); padding: 0 calc(var(--k) * 20); } /* room for the edge ticks */ + +/* ---- Home --------------------------------------------------------------------- */ +.page-home { display: grid; gap: var(--gap); align-items: stretch; + grid-template-columns: minmax(0, 2fr) minmax(0, 3fr); + grid-template-areas: "nav nav" "clock main" "weather weather" "day day" + "up up" "side side" "stations stations"; } +.home-nav { grid-area: nav; display: flex; justify-content: flex-end; gap: 8px; margin-top: 2px; } +.home-nav a { padding: 6px 12px; border-radius: 8px; background: var(--card); color: var(--muted); font-size: 14px; } + +/* clock */ +.clock { grid-area: clock; width: 100%; height: calc(var(--k) * 260); } + +/* weather */ +.weather { grid-area: weather; display: flex; flex-direction: column; min-width: 0; } +.wx-status { padding: calc(var(--k) * 40) calc(var(--k) * 24); font-size: calc(var(--k) * 28); color: var(--dim); } +.wx-top { display: flex; flex-wrap: wrap; align-items: center; column-gap: calc(var(--k) * 28); row-gap: 10px; } +.wx-icon { flex: none; width: calc(var(--k) * 170); height: calc(var(--k) * 150); + display: flex; align-items: center; justify-content: center; } +.wx-icon img { max-width: 100%; max-height: 100%; } +.wx-now { flex: 1 1 0; min-width: 0; } +.wx-temp { font: 700 calc(var(--k) * 104)/1 "DejaVu Web"; } +.wx-desc { margin-top: calc(var(--k) * 20); display: flex; flex-wrap: wrap; column-gap: calc(var(--k) * 26); + font-size: calc(var(--k) * 30); line-height: 1.2; white-space: nowrap; } +.wx-desc .d { color: var(--muted); overflow: hidden; text-overflow: ellipsis; min-width: 0; } +.wx-desc .hl { color: var(--dim); flex: none; } +.wx-extras { margin-top: calc(var(--k) * 12); display: flex; flex-wrap: wrap; + column-gap: calc(var(--k) * 34); row-gap: 2px; font-size: calc(var(--k) * 28); white-space: nowrap; } +.outdoor { flex: 1 0 100%; display: flex; flex-wrap: wrap; gap: calc(var(--k) * 10); } +.wx-days { display: flex; margin-top: calc(var(--k) * 18); } +.wx-day { flex: 1; min-width: 0; text-align: center; } +.wx-day .lbl { font-size: calc(var(--k) * 26); white-space: nowrap; } +.wx-day .hl { margin-top: calc(var(--k) * 10); display: flex; flex-direction: column; align-items: center; + font-size: calc(var(--k) * 30); } +.wx-day .hl b { font-weight: 700; } +.wx-day .hl span { color: var(--dim); } +.wx-day .hl img { order: -1; height: calc(var(--k) * 42); margin-bottom: calc(var(--k) * 6); } + +/* reading boxes (outdoor + stations) */ +.rbox { position: relative; width: calc(var(--k) * 189); height: calc(var(--k) * 74); box-sizing: border-box; flex: none; + background: var(--card); border-radius: var(--r); padding: calc(var(--k) * 9) calc(var(--k) * 12) 0; } +.rn { font-size: max(11px, calc(var(--k) * 17)); line-height: 1.2; color: var(--muted); + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.rv { position: absolute; left: calc(var(--k) * 12); right: calc(var(--k) * 12); top: calc(var(--k) * 34); + display: flex; justify-content: space-between; align-items: baseline; } +.rt { font: 700 calc(var(--k) * 28)/1 "DejaVu Web"; } .rt.dim { color: var(--dim); } +.rh { font-size: calc(var(--k) * 20); color: var(--cool); } + +/* stations + main temperature */ +.stations { grid-area: stations; display: flex; flex-direction: column; justify-content: center; align-items: center; + gap: calc(var(--k) * 10); } +.stations.empty { display: none; } +.srow { display: flex; flex-wrap: wrap; justify-content: center; gap: calc(var(--k) * 10); } +.main-temp { grid-area: main; display: flex; flex-direction: column; justify-content: center; align-items: center; + min-width: 0; text-align: center; container-type: inline-size; } +.mt { font: 700 min(calc(var(--k) * 140), 24cqi)/1 "DejaVu Web"; white-space: nowrap; } /* never wider than its column */ +.mt-sub { margin-top: calc(var(--k) * 28); display: flex; flex-wrap: wrap; justify-content: center; align-items: center; + row-gap: 4px; } +.mt-sub .house { width: calc(var(--k) * 24); height: calc(var(--k) * 24); margin-right: calc(var(--k) * 8); } +.mt-sub .nm { font-size: calc(var(--k) * 32); color: var(--muted); } +.mt-sub .hm { font-size: calc(var(--k) * 40); color: var(--cool); margin-left: calc(var(--k) * 36); } + +/* birthdays + next-event cards */ +.side { grid-area: side; display: flex; flex-direction: column; gap: var(--gap); min-width: 0; } +.bdays { min-height: calc(var(--k) * 150); display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); + align-items: center; text-align: center; } +.bw { font-size: calc(var(--k) * 21); } +.bn { font: 700 calc(var(--k) * 36)/1.3 "DejaVu Web"; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.by { font-size: calc(var(--k) * 18); margin-top: calc(var(--k) * 4); } +.cake { font-size: calc(var(--k) * 92); line-height: 1; } +.bnone { font-size: calc(var(--k) * 22); color: var(--dim); } +.cards { flex: 1; display: flex; flex-direction: column; gap: var(--gap); } +.ncard { flex: 1; display: flex; flex-direction: column; justify-content: center; min-width: 0; + padding: calc(var(--k) * 14) calc(var(--k) * 22); } +.nwhen { font-size: calc(var(--k) * 24); } +.ntitle { font: 700 calc(var(--k) * 36)/1.3 "DejaVu Web", "Symbola Web"; margin-top: calc(var(--k) * 4); + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.nempty { font-size: calc(var(--k) * 24); color: var(--dim); } + +/* upcoming */ +.upcoming { grid-area: up; display: block; position: relative; min-width: 0; overflow: hidden; + padding: calc(var(--k) * 14) calc(var(--k) * 20) calc(var(--k) * 12); } +.ugrid { margin-top: calc(var(--k) * 8); display: grid; + grid-template-columns: max-content max-content minmax(0, 1fr); column-gap: calc(var(--k) * 28); + font-size: calc(var(--k) * 26); line-height: calc(var(--k) * 42); } +.ugrid .gap { margin-top: calc(var(--k) * 8); } +.ue { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } + +/* stacked mode: the bottom band reads better as cards */ +.side, .upcoming { background: var(--card); border-radius: var(--r); } +.side { padding: calc(var(--k) * 10) 0; } + +/* day view */ +.dayview { grid-area: day; display: flex; flex-direction: column; box-sizing: border-box; min-height: 0; min-width: 0; + height: clamp(520px, 80vh, 900px); background: var(--card); border-radius: var(--r); + padding: calc(var(--k) * 16) calc(var(--k) * 16) calc(var(--k) * 18); } +.dv-wd { margin-left: calc(var(--k) * 6); font: 700 calc(var(--k) * 36)/1 "DejaVu Web"; } +.dv-date { margin: calc(var(--k) * 8) 0 0 calc(var(--k) * 6); font-size: calc(var(--k) * 26); color: var(--muted); } +.pills { margin-top: calc(var(--k) * 18); display: flex; flex-direction: column; gap: calc(var(--k) * 6); } +.pill { height: calc(var(--k) * 34); border-radius: calc(var(--k) * 8); padding: 0 calc(var(--k) * 12); + font-size: calc(var(--k) * 22); line-height: calc(var(--k) * 34); + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.pmore { font-size: calc(var(--k) * 22); color: var(--muted); } +.dv-tl { flex: 1; min-height: 0; position: relative; margin: calc(var(--k) * 22) 0 0 calc(var(--k) * 58); } + +/* ---- timeline (day view + week columns) ----------------------------------------- */ +.tl { position: relative; width: 100%; height: 100%; } +.band { position: absolute; left: 0; right: 0; background: var(--band); } +.band span { position: absolute; right: calc(var(--k) * 8); top: 50%; transform: translateY(-50%); + font-size: calc(var(--k) * 18); color: var(--dim); } +.hline { position: absolute; left: 0; right: 0; height: 1px; background: #1f2430; } +.hline.tick { left: calc(var(--k) * -8); } +.hlabel { position: absolute; left: calc(var(--k) * -52); font-size: max(10px, calc(var(--k) * 18)); line-height: 1; + transform: translateY(-50%); color: var(--dim); } +.blk { position: absolute; box-sizing: border-box; overflow: hidden; } +.blk.future { background: var(--c); } +.blk.past { background: var(--t); } +.blk.live { background: linear-gradient(to bottom, var(--t) 0 var(--s), var(--c) var(--s) 100%); } /* spans "now" (not .now: that is the now line) */ +.blk .lbl { padding: calc(var(--k) * 3) calc(var(--k) * 6) 0; line-height: 1.15; + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.now { position: absolute; left: calc(var(--k) * -12); right: 0; height: 3px; margin-top: -1px; background: var(--accent); } +.now::before { content: ""; position: absolute; left: -7px; top: -5.5px; width: 14px; height: 14px; + border-radius: 50%; background: var(--accent); } +.now.edge { left: -4px; } + +/* ---- page header (week / month / weather) ------------------------------------- */ +/* the top bar: buttons as tall as the yellow title's line, nothing else in it */ +/* three columns: nav buttons | title (centred on the page, like the sub-heading under it) | cog */ +.head { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); align-items: center; + gap: calc(var(--k) * 14); min-height: calc(var(--k) * 54); flex: none; } +.navb { display: flex; gap: calc(var(--k) * 14); min-width: 0; } +.btn { flex: none; width: calc(var(--k) * 54); height: calc(var(--k) * 54); border-radius: calc(var(--k) * 10); + background: var(--card); color: var(--fg); display: flex; align-items: center; justify-content: center; } +.btn svg { width: calc(var(--k) * 24); height: calc(var(--k) * 24); } +.btn.plug { font-size: calc(var(--k) * 26); color: var(--muted); } +/* nav buttons sink darker on hover, darker still while pressed; the page you're on stays sunk */ +.btn { transition: background-color .12s; } +.btn:hover, .btn.on { background: #10131a; box-shadow: inset 0 0 0 1px #1f2430; } +.btn:active { background: #0a0c11; } +.btn:active > * { filter: brightness(.8); } +.btn.gear { justify-self: end; } /* always the last one, at the right edge */ +/* the yellow title in a fixed-width slot with round ‹ › either side: the arrows stay put + whatever the title ("CW 42", "October 2026"), and so do the nav buttons and the cog */ +.cw-wrap { min-width: 0; display: flex; align-items: center; justify-content: center; gap: calc(var(--k) * 16); } +.cw-wrap .cw { flex: none; width: calc(var(--k) * 440); max-width: 100%; overflow: hidden; text-overflow: ellipsis; } +.btn.prev, .btn.next { width: calc(var(--k) * 54); height: calc(var(--k) * 54); border-radius: 50%; } +.btn.prev svg, .btn.next svg { width: calc(var(--k) * 20); height: calc(var(--k) * 20); } +/* the grey sub-heading, under the bar (below the title) */ +.subhead { flex: none; text-align: center; font-size: calc(var(--k) * 20); color: var(--muted); + white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: calc(var(--k) * -6); } +.btn.prev svg { margin-left: calc(var(--k) * -3); } .btn.next svg { margin-right: calc(var(--k) * -3); } /* optical centre */ +/* a page's sections, a row under the top bar (Week | Month, Overview | Body | …) */ +.tabs { flex: none; display: flex; flex-wrap: wrap; gap: 4px; border-bottom: 1px solid #262c39; } +.tabs a { padding: calc(var(--k) * 10) calc(var(--k) * 18); margin-bottom: -1px; border-bottom: 3px solid transparent; + color: var(--muted); font: 700 max(14px, calc(var(--k) * 19)) "DejaVu Web", sans-serif; } +.tabs a:hover { color: var(--fg); } +.tabs a.on { color: var(--accent); border-bottom-color: var(--accent); } +/* ⋯ at the right end of a tab row: the section's other pages (Health: the report) */ +.tabs-more { margin-left: auto; position: relative; align-self: center; } +.tabs-more summary { list-style: none; cursor: pointer; display: flex; align-items: center; justify-content: center; + width: max(34px, calc(var(--k) * 40)); height: max(34px, calc(var(--k) * 40)); border-radius: 50%; + color: var(--muted); } +.tabs-more summary svg { width: 5px; height: 18px; fill: currentColor; } /* ⋮ kebab */ +.tabs-more summary::-webkit-details-marker { display: none; } +.tabs-more summary:hover, .tabs-more[open] summary { color: var(--fg); background: #1d222d; } +.tabs-menu { position: absolute; right: 0; top: calc(100% + 6px); z-index: 20; min-width: 200px; padding: 6px; border-radius: 10px; + background: var(--card); box-shadow: 0 8px 24px rgba(0, 0, 0, .5); display: flex; flex-direction: column; } +.tabs .tabs-menu a { margin: 0; border: 0; padding: 9px 12px; border-radius: 7px; font-size: 15px; color: var(--fg); white-space: nowrap; } +.tabs .tabs-menu a:hover, .tabs .tabs-menu a.on { background: #262d3b; color: var(--accent); } +.pico { width: 1em; height: 1em; display: inline-block; vertical-align: -0.12em; } +.wx-extras .pico.arrow { width: 0.9em; height: 0.9em; margin: 0; color: inherit; } +.btn.home svg { width: calc(var(--k) * 23); height: calc(var(--k) * 23); } +.btn.off { opacity: .3; pointer-events: none; } +.cw { flex: 1; min-width: 0; text-align: center; white-space: nowrap; } +.cw-n { font: 700 calc(var(--k) * 40)/1 "DejaVu Web"; } +.cw.current .cw-n { color: var(--accent); } +.seg { flex: none; display: flex; height: calc(var(--k) * 70); border-radius: calc(var(--k) * 12); + background: var(--card); overflow: hidden; } +.seg a { width: calc(var(--k) * 84); display: flex; align-items: center; justify-content: center; + font: 700 calc(var(--k) * 22)/1 "DejaVu Web"; color: var(--muted); } +.seg a.on { background: #262d3b; color: var(--accent); } +.seg.locs a { width: auto; padding: 0 calc(var(--k) * 22); } +.seg a:not(.on):hover { background: #1d222d; color: var(--fg); } + +.cw .cw-n { display: block; color: inherit; text-decoration: none; overflow: hidden; text-overflow: ellipsis; } +/* weather page: the place under the title opens a list of the other places */ +.wx-loc { display: inline-block; position: relative; } +.page-weather .subhead { overflow: visible; } /* the place list hangs below it */ +.wx-loc summary { display: inline; list-style: none; cursor: pointer; color: var(--fg); } +.wx-loc summary::-webkit-details-marker { display: none; } +.wx-loc summary:hover, .wx-loc[open] summary { color: var(--accent); } +.wx-caret { font-size: .8em; color: var(--muted); } +.wx-menu { position: absolute; z-index: 15; left: 50%; transform: translateX(-50%); top: calc(100% + 6px); min-width: 100%; + display: flex; flex-direction: column; padding: 6px; border-radius: 10px; background: #232a38; + box-shadow: 0 8px 24px rgba(0, 0, 0, .5); text-align: left; } +.wx-menu a { padding: 7px 12px; border-radius: 7px; color: var(--fg); text-decoration: none; white-space: nowrap; } +.wx-menu a:hover { background: #2c3445; } .wx-menu a.on { color: var(--accent); } + +/* ---- week view -------------------------------------------------------------------- */ +.page-week, .page-month { display: flex; flex-direction: column; gap: calc(var(--k) * 14); } +.wk { position: relative; height: max(560px, calc(100vh - 150px)); background: var(--card); border-radius: var(--r); } +.wk-in { position: relative; height: 100%; min-width: 720px; } /* phones scroll sideways, tablets fit */ +.wk-cols { position: absolute; left: calc(var(--k) * 64); right: calc(var(--k) * 12); top: 0; bottom: 0; } +.wk-day { position: absolute; top: calc(var(--k) * 14); text-align: center; font-size: calc(var(--k) * 24); line-height: 1.2; + white-space: nowrap; } +.wk-day.weekend { color: var(--muted); } +.wk-day.today { color: var(--accent); font-weight: 700; } +.wk-day.today::after { content: ""; position: absolute; left: calc(var(--k) * 6); right: calc(var(--k) * 6); + top: calc(var(--k) * 36); height: calc(var(--k) * 4); border-radius: 2px; background: var(--accent); } +.wk-sep { position: absolute; top: calc(var(--k) * 10); bottom: calc(var(--k) * 10); width: 2px; margin-left: -1px; background: #232937; } +.bar { position: absolute; top: calc(var(--k) * (64 + var(--lane) * 32)); height: calc(var(--k) * 28); + border-radius: calc(var(--k) * 7); font-size: calc(var(--k) * 18); line-height: calc(var(--k) * 28); + padding: 0 calc(var(--k) * 8); box-sizing: border-box; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.wk-tl { position: absolute; left: 0; right: 0; top: calc(var(--k) * (64 + var(--lanes) * 32 + 14)); bottom: calc(var(--k) * 16); } +.wk-col { position: absolute; top: 0; bottom: 0; padding: 0 calc(var(--k) * 4); box-sizing: border-box; } + +/* ---- month view ------------------------------------------------------------------- */ +.mo { position: relative; height: max(480px, calc(100vh - 150px)); background: var(--card); border-radius: var(--r); } +.mo-cols { position: absolute; left: calc(var(--k) * 12); right: calc(var(--k) * 12); top: 0; bottom: 0; } +.mo-dow { position: absolute; top: calc(var(--k) * 16); text-align: center; font-size: calc(var(--k) * 22); } +.mo-dow.weekend { color: var(--muted); } +.mo-grid { position: absolute; left: 0; right: 0; top: calc(var(--k) * 56); bottom: calc(var(--k) * 16); } +.mo-row { position: absolute; left: 0; right: 0; border-top: 2px solid #232937; box-sizing: border-box; } +.mo-cell { position: absolute; top: 0; bottom: 0; box-sizing: border-box; border-left: 2px solid #232937; overflow: hidden; } +.mo-cell.first { border-left: none; } +.mo-cell:hover { background: #1c212c; } +.mo-num { padding: calc(var(--k) * 6) calc(var(--k) * 10) 0; font-size: calc(var(--k) * 20); line-height: calc(var(--k) * 24); + height: calc(var(--k) * 28); box-sizing: border-box; white-space: nowrap; } +.mo-cell.out .mo-num { color: var(--dim); } +.mo-cell.today .mo-num span { background: var(--accent); color: var(--bg); font-weight: 700; + border-radius: calc(var(--k) * 12); padding: calc(var(--k) * 1) calc(var(--k) * 9); } +.mo-items { position: absolute; left: calc(var(--k) * 8); right: calc(var(--k) * 8); bottom: 0; + top: calc(var(--k) * (34 + var(--lanes) * 26)); overflow: hidden; } +.mi { font-size: calc(var(--k) * 17); line-height: calc(var(--k) * 24); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.mi .t { color: var(--muted); } +.mi.done, .mo-cell.out .mi { opacity: .45; } +.mo-more { font-size: calc(var(--k) * 16); line-height: calc(var(--k) * 24); color: var(--muted); white-space: nowrap; } +.mo-bar { top: calc(var(--k) * (34 + var(--lane) * 26)); height: calc(var(--k) * 22); font-size: calc(var(--k) * 16); + line-height: calc(var(--k) * 22); border-radius: calc(var(--k) * 6); padding: 0 calc(var(--k) * 7); } + +/* ---- weather page (/weather) --------------------------------------------------- */ +.page-weather { display: grid; gap: var(--gap); grid-template-columns: minmax(0, 1fr); + grid-template-areas: "head" "now" "hours" "days"; } +.page-weather .headwrap { grid-area: head; display: flex; flex-direction: column; gap: calc(var(--k) * 12); } +@media (min-width: 1000px) { /* Forecast | Stations beside the centred sub-heading, so the page still fits */ + .page-weather .headwrap { position: relative; } + .page-weather .headwrap > .tabs { position: absolute; left: 0; bottom: calc(var(--k) * -6); border-bottom: 0; } + .page-weather .headwrap > .tabs a { padding: calc(var(--k) * 2) calc(var(--k) * 18) calc(var(--k) * 4); } +} +.wp-status { grid-column: 1 / -1; padding: calc(var(--k) * 300) 0; text-align: center; font-size: calc(var(--k) * 26); color: var(--dim); } +.arrow { width: calc(var(--k) * 18); height: calc(var(--k) * 18); vertical-align: -3px; margin-right: calc(var(--k) * 5); color: var(--muted); } +.wp-now { grid-area: now; box-sizing: border-box; min-width: 0; display: flex; flex-direction: column; gap: var(--gap); } +.wp-hero { display: flex; align-items: center; gap: calc(var(--k) * 18); } +.wp-icon { width: calc(var(--k) * 160); height: calc(var(--k) * 130); display: flex; align-items: center; justify-content: center; flex: none; } +.wp-icon img { max-width: 100%; max-height: 100%; } +.wp-temp { font: 700 calc(var(--k) * 96)/1 "DejaVu Web"; } +.wp-desc { font-size: calc(var(--k) * 26); margin-top: calc(var(--k) * 6); } +.wp-feels { font-size: calc(var(--k) * 20); color: var(--muted); margin-top: calc(var(--k) * 4); } +/* the now card's values: an icon + the value, four a row, no boxes (what each is: hover) */ +.wp-stats { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: calc(var(--k) * 12) calc(var(--k) * 10); + margin-top: calc(var(--k) * 18); font-size: calc(var(--k) * 20); } +.wp-stats > div { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; cursor: default; } +.wp-stats .g { color: var(--muted); margin-right: calc(var(--k) * 6); } +.wp-l { font-size: max(10px, calc(var(--k) * 14)); color: var(--dim); text-transform: uppercase; letter-spacing: .03em; } +/* sun | air quality, two half cards */ +.wp-pair { display: grid; grid-template-columns: 1fr 1fr; gap: var(--gap); } +.wp-sun { position: relative; display: flex; flex-direction: column; } +.wp-sun svg { display: block; width: 100%; height: auto; margin-top: calc(var(--k) * 10); } +.wp-sun .hz { stroke: #2c3343; stroke-width: 1.5; } +.wp-sun .track { fill: none; stroke: var(--muted); stroke-opacity: .5; stroke-width: 1.5; stroke-dasharray: 5 5; } +.wp-sun .gone { fill: none; stroke: var(--accent); stroke-width: 2.5; stroke-linecap: round; } +.wp-sun .glow { fill: var(--accent); opacity: .14; } +.wp-sun .halo { fill: var(--accent); opacity: .25; } .wp-sun .sun { fill: var(--accent); } +.wp-sun .end { fill: var(--muted); } .wp-sun .end.on { fill: var(--accent); } +.wp-sun .dl { position: absolute; top: calc(var(--k) * 12); left: 50%; transform: translateX(-50%); background: var(--card); + padding: 0 calc(var(--k) * 8); font-size: calc(var(--k) * 18); white-space: nowrap; } +.wp-sun .ends { display: flex; justify-content: space-between; font-size: calc(var(--k) * 18); margin-top: calc(var(--k) * 6); } +.wp-aq { display: flex; flex-direction: column; justify-content: space-between; gap: calc(var(--k) * 6); cursor: default; } +.wp-aqi { font: 700 calc(var(--k) * 44)/1 "DejaVu Web"; } +.wp-aqi span { font: 400 calc(var(--k) * 18)/1 "DejaVu Web"; margin-left: calc(var(--k) * 10); } +.wp-scale { position: relative; height: 6px; border-radius: 3px; } +.wp-scale i { position: absolute; top: -4px; width: 7px; height: 14px; margin-left: -3.5px; background: #fff; border: 2px solid var(--card); border-radius: 4px; box-sizing: content-box; } +.wp-parts { font-size: max(11px, calc(var(--k) * 15)); color: var(--muted); } +@media (max-width: 520px) { .wp-stats { grid-template-columns: repeat(2, minmax(0, 1fr)); } } + +.wp-card { position: relative; min-width: 0; background: var(--card); border-radius: var(--r); + padding: calc(var(--k) * 14) calc(var(--k) * 20); } +.wp-hours { grid-area: hours; } .wp-days { grid-area: days; } +.wp-cap { display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; gap: 6px 20px; } +.wp-legend { display: flex; flex-wrap: wrap; gap: 4px calc(var(--k) * 22); font-size: max(11px, calc(var(--k) * 15)); color: var(--muted); } +.wp-legend span::before { content: ""; display: inline-block; width: 20px; height: 0; margin-right: 7px; vertical-align: 4px; } +.wp-legend .lt::before { border-top: 3px solid var(--accent); } +.wp-legend .lf::before { border-top: 2px dashed var(--muted); } +.wp-legend .lr::before { height: 10px; vertical-align: -1px; background: var(--cool); opacity: .5; border-radius: 2px; } +.wp-legend .lw::before { display: none; } +.wp-hin { position: relative; min-width: 900px; } +.wp-ticks { position: relative; height: calc(var(--k) * 70); margin-top: calc(var(--k) * 10); } +.wp-tick { position: absolute; transform: translateX(-50%); text-align: center; } +.wp-tick .th { font-size: max(11px, calc(var(--k) * 17)); color: var(--muted); } +.wp-tick img { height: calc(var(--k) * 40); margin-top: 2px; } +.wp-chart { display: block; width: 100%; height: auto; overflow: visible; } +.wp-temp-l { fill: none; stroke: var(--accent); stroke-width: 3; stroke-linejoin: round; } +.wp-feels-l { fill: none; stroke: var(--muted); stroke-width: 2; stroke-dasharray: 6 5; } +.wp-area { fill: var(--accent); opacity: .07; } +.wp-bar { fill: var(--cool); opacity: .22; } +.wp-bar.wet { opacity: .55; } +.wp-dot { fill: var(--accent); } +.wp-tl { font: 15px "DejaVu Web"; fill: var(--fg); text-anchor: middle; } +.wp-rl { font: 13px "DejaVu Web"; fill: var(--cool); text-anchor: middle; } +.wp-daysep { stroke: #2c3343; stroke-width: 2; stroke-dasharray: 4 4; } +.wp-dayl { font: 700 15px "DejaVu Web"; fill: var(--muted); } +.wp-grid-l { stroke: #222837; stroke-width: 1; } +.wp-wind { position: relative; height: calc(var(--k) * 56); margin-top: calc(var(--k) * 8); } +.wp-w { position: absolute; transform: translateX(-50%); text-align: center; font-size: max(11px, calc(var(--k) * 16)); } +.wp-w .arrow { margin: 0; } +.wp-w span { color: var(--dim); font-size: max(9px, calc(var(--k) * 13)); } + +.wp-dcols { display: grid; grid-template-columns: repeat(14, minmax(64px, 1fr)); gap: calc(var(--k) * 4); margin-top: calc(var(--k) * 14); } +.wp-day { display: flex; flex-direction: column; align-items: center; border-radius: calc(var(--k) * 10); padding: calc(var(--k) * 6) 2px; } +.wp-day.today { background: #1d222d; } +.wp-day .dl { font: 700 calc(var(--k) * 20)/1.2 "DejaVu Web"; } +.wp-day.weekend .dl { color: var(--muted); } +.wp-day.today .dl { color: var(--accent); } +.wp-day .dd { font-size: max(10px, calc(var(--k) * 14)); color: var(--muted); height: calc(var(--k) * 18); } +.wp-day img { height: calc(var(--k) * 44); margin: calc(var(--k) * 6) 0; } +.wp-day .dh { font: 700 calc(var(--k) * 22)/1.2 "DejaVu Web"; } +.wp-day .track { position: relative; width: calc(var(--k) * 10); height: calc(var(--k) * 110); background: #222837; + border-radius: calc(var(--k) * 5); margin: calc(var(--k) * 6) 0; } +.wp-day .range { position: absolute; left: 0; right: 0; border-radius: calc(var(--k) * 5); } +.wp-day .dlo { font-size: calc(var(--k) * 20); color: var(--dim); } +.wp-day .dr { font-size: max(11px, calc(var(--k) * 16)); color: var(--cool); margin-top: calc(var(--k) * 8); text-align: center; } +.wp-day .dr span { display: block; font-size: max(9px, calc(var(--k) * 13)); color: var(--dim); } +.wp-day .dw { font-size: max(10px, calc(var(--k) * 15)); color: var(--muted); margin-top: calc(var(--k) * 6); white-space: nowrap; } +.wp-day .dw .arrow { width: calc(var(--k) * 14); height: calc(var(--k) * 14); margin-right: 2px; } +.wp-day .du { font-size: max(9px, calc(var(--k) * 13)); color: var(--dim); margin-top: calc(var(--k) * 4); } + +/* ---- phones ------------------------------------------------------------------------ */ +@media (max-width: 599px) { + /* title (+ arrows) on its own row, the nav buttons and the cog under it */ + .head { grid-template-columns: minmax(0, 1fr) auto; grid-template-areas: "title title" "nav gear"; row-gap: 10px; } + .head .cw-wrap { grid-area: title; } .head .navb { grid-area: nav; flex-wrap: wrap; gap: 8px; } .head .btn.gear { grid-area: gear; } + .btn { width: 42px; height: 42px; } + .cw-wrap .cw { flex: 1; width: auto; } + .btn.prev, .btn.next { width: 40px; height: 40px; } + .subhead { font-size: 14px; margin-top: 0; } + .tabs a { padding: 8px 10px; font-size: 14px; } + .btn.plug { font-size: 20px; } + .seg { height: 44px; } .seg a { width: 52px; } + /* month: a dot per event instead of its title; tap a day -> its week */ + .mo-bar { top: calc(var(--k) * 30 + var(--lane) * 9px); height: 6px; padding: 0; font-size: 0; border-radius: 3px; } + .mo-items { top: calc(var(--k) * 34 + var(--lanes) * 9px + 2px); display: flex; flex-wrap: wrap; align-content: flex-start; gap: 3px; } + .mi { width: 7px; height: 7px; border-radius: 50%; background: currentColor; font-size: 0; line-height: 0; } + .mo-more { flex: 1 0 100%; font-size: 10px; line-height: 12px; } + .mo-num { padding: 4px 4px 0; } +} + +/* ---- tablets / portrait windows: two columns ------------------------------------- */ +@media (min-width: 700px) { + .page-home { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); + grid-template-areas: "nav nav" "clock main" "weather weather" "day up" "day side" "stations stations"; } + .wx-icon { width: calc(var(--k) * 240); height: calc(var(--k) * 216); } + .wx-day .hl { flex-direction: row; justify-content: center; } + .wx-day .hl span { margin-left: .55em; } + .wx-day .hl img { order: 0; margin: 0 0 0 calc(var(--k) * 14); } + .page-home .dayview { height: auto; min-height: 560px; } +} + +/* ---- wall mode: a landscape window -> the 1920×1080 layout, scaled to fit ------------ */ +@media (min-width: 1000px) and (min-aspect-ratio: 5/4) { + :root { --k: min(calc(100vw / 1920), calc(100vh / 1080)); } + body.wall { height: 100vh; overflow: hidden; } + body.wall #page { height: 100vh; } + + .page-home { grid-template-columns: 456fr 240fr 712fr 464fr; grid-template-rows: 370fr 244fr 399fr; + grid-template-areas: "clock weather weather day" "stations stations main day" "side up up day"; } + /* a plugin off (home.html: data-off) → its regions are left out, the others take the room */ + .page-home[data-off~="off-cal"] { grid-template-areas: "clock weather weather weather" "stations stations main main" "stations stations main main"; } + .page-home[data-off~="off-wx"] { grid-template-areas: "clock main main day" "stations stations stations day" "side up up day"; } + .page-home[data-off~="off-st"] { grid-template-areas: "clock weather weather day" "side up up day" "side up up day"; } + .page-home[data-off~="off-cal"][data-off~="off-wx"] { grid-template-areas: "clock main main main" "stations stations stations stations" "stations stations stations stations"; } + .page-home[data-off~="off-cal"][data-off~="off-st"] { grid-template-areas: "clock weather weather weather" "clock weather weather weather" "clock weather weather weather"; } + .page-home[data-off~="off-wx"][data-off~="off-st"] { grid-template-areas: "clock up up day" "side up up day" "side up up day"; } + .page-home[data-off~="off-cal"][data-off~="off-wx"][data-off~="off-st"] { grid-template-areas: "clock clock clock clock" "clock clock clock clock" "clock clock clock clock"; } + .home-nav { display: none; } + .clock { height: 100%; } + .weather { justify-content: space-between; } + .wx-top { flex-wrap: nowrap; align-items: flex-start; padding-top: calc(var(--k) * 12); } + .wx-desc, .wx-extras { flex-wrap: nowrap; overflow: hidden; } + .outdoor { flex: none; flex-direction: column; flex-wrap: nowrap; } + .wx-days { margin-top: 0; } + .stations.empty { display: flex; } + .side, .upcoming { background: none; border-radius: 0; } + .side { padding: 0; } + .bdays { min-height: 0; height: calc(var(--k) * 150); flex: none; } + .upcoming::before { content: ""; position: absolute; top: calc(var(--k) * 12); bottom: calc(var(--k) * 12); + left: 0; width: 2px; background: var(--card); } /* divides it from the side column */ + .page-home .dayview { height: auto; min-height: 0; } + + .wk, .mo { flex: 1; height: auto; min-height: 0; } + .wk { overflow: hidden; } + .wk-in { min-width: 0; } + + .page-weather { grid-template-columns: 600fr 1272fr; grid-template-rows: auto auto 1fr; + grid-template-areas: "head head" "now hours" "now days"; } + .wp-hin { min-width: 0; } + .wp-card .hscroll { overflow: visible; } + .wp-dcols { grid-template-columns: repeat(14, minmax(0, 1fr)); } +} + +/* ---- event info card + reminder bits (real px) ------------------------------------- */ +[data-ev] { cursor: pointer; } +#evcard[hidden] { display: none; } +#evcard { position: fixed; inset: 0; z-index: 10; display: flex; align-items: center; justify-content: center; } +.ec-back { position: absolute; inset: 0; background: rgba(0, 0, 0, .55); } +.ec-box { position: relative; width: min(560px, 92vw); max-height: 86vh; overflow: auto; box-sizing: border-box; + background: var(--card); border-radius: 16px; padding: 26px 28px 24px; + border-top: 6px solid var(--ec, var(--accent)); box-shadow: 0 12px 40px rgba(0, 0, 0, .5); + font-size: 17px; line-height: 1.45; } +.ec-x { position: absolute; top: 12px; right: 14px; background: none; border: 0; color: var(--muted); + font: 22px/1 "DejaVu Web"; cursor: pointer; padding: 4px 6px; } +.ec-x:hover { color: var(--fg); } +.ec-title { font: 700 26px/1.25 "DejaVu Web", "Symbola Web"; color: var(--ec, var(--fg)); padding-right: 34px; margin-bottom: 12px; } +.ec-row { color: var(--fg); margin-top: 4px; } +.ec-row:empty, .ec-desc:empty, .ec-url:empty { display: none; } +.ec-cal, .ec-extra { color: var(--muted); } +.ec-loc::before { content: "📍 "; font-family: "Symbola Web"; color: var(--muted); } +.ec-desc { margin-top: 14px; padding-top: 12px; border-top: 1px solid #262c39; color: var(--fg); + white-space: pre-wrap; overflow-wrap: anywhere; } +.ec-desc a, .ec-url { color: var(--cool); } +.ec-url { display: inline-block; margin-top: 12px; overflow-wrap: anywhere; } +.ec-edit { display: inline-block; margin-top: 16px; padding: 8px 14px; border-radius: 10px; + background: #262d3b; color: var(--accent); font: 700 16px "DejaVu Web"; } +.ec-edit:empty { display: none; } +.ec-edit:hover { background: #2e3647; } +.sound-off { position: fixed; right: 14px; bottom: 14px; z-index: 11; padding: 8px 14px; border: 0; border-radius: 10px; + background: var(--card); color: var(--muted); font: 15px "DejaVu Web", "Symbola Web"; cursor: pointer; + box-shadow: 0 4px 16px rgba(0, 0, 0, .4); } +.sound-off:hover { color: var(--fg); } +.sound-off[hidden] { display: none; } +.demo-hint { position: fixed; left: 50%; top: 14px; transform: translateX(-50%); z-index: 11; padding: 8px 16px; + border-radius: 10px; background: var(--accent); color: var(--bg); font: 700 15px "DejaVu Web"; } + +/* ---- new event: drag ghost, form (real px, like the info card) -------------------- */ +.tl { user-select: none; -webkit-user-select: none; } +.tl[data-day], .mo-cell { cursor: cell; } +.ghost { position: absolute; left: 2px; right: 2px; z-index: 2; box-sizing: border-box; border-radius: 4px; + background: rgba(255, 179, 58, .28); border: 2px solid var(--accent); pointer-events: none; + font-size: max(11px, calc(var(--k) * 16)); color: var(--fg); padding: 2px 6px; overflow: hidden; white-space: nowrap; } +.wk-day.pick { background: rgba(255, 179, 58, .2); border-radius: 6px; } +#newev[hidden], #newev [hidden] { display: none !important; } +#newev { position: fixed; inset: 0; z-index: 10; display: flex; align-items: center; justify-content: center; } +.ne-box { display: flex; flex-direction: column; gap: 12px; border-top-color: var(--accent); } +.ne-box input, .ne-box select { font: 16px "DejaVu Web", sans-serif; color: var(--fg); background: #1d222d; + border: 1px solid #2c3343; border-radius: 8px; padding: 7px 10px; color-scheme: dark; } +.ne-box input:focus, .ne-box select:focus { outline: 2px solid var(--accent); outline-offset: -1px; } +.ne-title { font: 700 22px "DejaVu Web", sans-serif !important; margin-right: 34px; } +.ne-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; color: var(--muted); } +.ne-times, .ne-days { display: inline-flex; align-items: center; gap: 8px; } +.ne-check { cursor: pointer; } .ne-check input { width: 18px; height: 18px; accent-color: var(--accent); } +.ne-cal select { flex: 1; min-width: 0; } +.ne-dot { width: 14px; height: 14px; border-radius: 50%; flex: none; } +.mo-cell.pick { background: rgba(255, 179, 58, .14); } +/* anchored (dash.js place): a small box beside the slot, the page stays visible behind it */ +#newev.anchored, .wl-modal.anchored { display: block; } +#newev.anchored .ec-back, .wl-modal.anchored .ec-back { background: none; } +#newev.anchored .ec-box, .wl-modal.anchored .ec-box { position: fixed; width: 400px; max-height: calc(100vh - 16px); + padding: 16px 18px 16px; border-radius: 12px; border-top-width: 4px; font-size: 15px; box-shadow: 0 10px 34px rgba(0, 0, 0, .6); } +#newev.anchored .ne-box { gap: 10px; } +#newev.anchored .ne-title { font-size: 18px !important; } +#newev.anchored .ne-box input, #newev.anchored .ne-box select { font-size: 15px; padding: 6px 9px; } +#newev.anchored .ec-x { top: 8px; right: 10px; font-size: 18px; } +.ne-actions { display: flex; align-items: center; justify-content: flex-end; gap: 14px; } +.ne-err { flex: 1; color: #ff7a7a; font-size: 15px; } +.ne-save, .ec-del { padding: 9px 18px; border: 0; border-radius: 10px; cursor: pointer; + font: 700 16px "DejaVu Web", sans-serif; } +.ne-save { background: var(--accent); color: var(--bg); } +.ne-save:disabled { opacity: .5; cursor: wait; } +.ec-del { display: block; margin-top: 16px; background: #262d3b; color: #ff9a9a; } +.ec-del.armed { background: #8a2b2b; color: #fff; } +.ec-del[hidden] { display: none; } + +/* ---- settings page (/settings) ------------------------------------------------------ */ +.page-settings { padding-bottom: 90px !important; } +/* the content is centred at 1400 px; the header spans the window like on every page, so its + buttons stay put */ +.page-settings > :not(.head) { max-width: 1400px; margin-left: auto; margin-right: auto; } +.page-settings .head { margin-bottom: var(--gap); } +.st-mini { margin-left: auto; border: 0; border-radius: 8px; background: #262d3b; color: var(--fg); cursor: pointer; + font: 400 14px "DejaVu Web", sans-serif; padding: 6px 12px; } +.st-mini:hover { color: var(--accent); } .st-mini:disabled { opacity: .5; cursor: wait; } +.st-plugin.off .st-pfields { opacity: .45; } +/* General ▸ Plugins: one row per plugin, its On box and what it does */ +.st-plug { padding: 10px 0; border-top: 1px solid #262c39; } +.st-plug:first-of-type { border-top: 0; } +.st-span > .st-plug { border-top: 0; padding: 12px 14px; border-radius: 10px; background: #1b2030; } +.st-plug .st-plug-h { font-size: 15px; } +.st-plug .st-note { margin: 4px 0 0 28px; } +.st-plug.off .st-plug-h b { color: var(--muted); } +.st-panel { margin-bottom: 0; } +.st-wide { margin-bottom: 16px; } +.st-wide:last-child { margin-bottom: 0; } /* a panel's box: the row gap is enough */ +.st-pfields { display: flex; flex-direction: column; gap: 12px; } +.st-fhelp { margin-top: -6px; } +.st-plinks { display: flex; flex-wrap: wrap; gap: 8px; } +.st-plink { margin-left: 0; color: var(--accent); } +.st-pnote { margin-bottom: 14px; } +.st-bad { color: #ff7a7a; } +/* calendars table */ + +.st-cals { width: 100%; border-collapse: collapse; font-size: 15px; } +.st-cals th { text-align: left; font: 400 13px "DejaVu Web", sans-serif; color: var(--dim); padding: 6px 10px; + border-bottom: 1px solid #262c39; white-space: nowrap; } +.st-cals td { padding: 7px 10px; border-bottom: 1px solid #1f2430; vertical-align: middle; } +.st-cals th:first-child, .st-cals td:first-child, .st-cals th:last-child, .st-cals td:last-child { text-align: center; width: 1%; } +.st-cals input[type=checkbox] { accent-color: var(--accent); width: 18px; height: 18px; margin: 0; cursor: pointer; } +.st-cals input[type=checkbox]:disabled { opacity: .25; cursor: not-allowed; } +.st-cname { display: flex; align-items: center; gap: 10px; } +.st-dot { width: 12px; height: 12px; border-radius: 50%; flex: none; } +.st-cals tr.ro .st-cname { color: var(--muted); } +.st-cals tr.off .st-cname, .st-cals tr.off .st-glyph { opacity: .4; } +.st-badge { display: inline-block; padding: 3px 9px; border-radius: 6px; font-size: 13px; white-space: nowrap; background: #262d3b; } +.st-badge.nextcloud { color: #7fd6a3; } .st-badge.google { color: var(--cool); } .st-badge.local { color: #c792ea; } +.st-badge.ro { color: var(--dim); background: #1b1f29; } +/* a calendar that fails to load: ⚠ next to its name, details on hover / focus */ +.st-warn { position: relative; margin-left: 8px; color: #ffb33a; cursor: help; font: 15px "Symbola Web", "DejaVu Web"; outline: none; } +.st-pop { display: none; position: absolute; z-index: 20; left: -10px; top: calc(100% + 6px); width: 320px; padding: 10px 12px; + border-radius: 8px; background: #2a3242; box-shadow: 0 6px 18px rgba(0, 0, 0, .45); color: var(--muted); + font: 13px/1.45 "DejaVu Web", sans-serif; white-space: normal; } +.st-pop b { display: block; color: var(--fg); margin-bottom: 2px; } +.st-pop code { display: block; margin: 6px 0; color: #ff9a9a; font: 12px "DejaVu Sans Mono", monospace; word-break: break-word; } +.st-warn:hover .st-pop, .st-warn:focus .st-pop { display: block; } +.st-why { display: block; color: var(--dim); font-size: 12px; margin-top: 3px; } +.st-empty { color: var(--dim); text-align: left !important; padding: 16px 10px !important; } +.st-fixed { display: inline-block; width: 52px; text-align: center; font-size: 20px; color: var(--muted); } +.st-other { color: var(--muted); font-size: 14px; flex-wrap: wrap; } +/* pictogram field + picker: always the black-and-white Symbola glyphs */ +.st-glyph { display: inline-flex; align-items: stretch; } +.st-card .st-glyph input { width: 46px !important; text-align: center; padding: 4px !important; border-radius: 8px 0 0 8px !important; + font: 20px "Symbola Web", "DejaVu Web" !important; font-variant-emoji: text; } +.st-pick { border: 1px solid #2c3343; border-left: 0; border-radius: 0 8px 8px 0; background: #262d3b; color: var(--muted); + cursor: pointer; padding: 0 8px; font-size: 12px; } +.st-pick:hover { color: var(--accent); } +.st-glyphs { position: absolute; z-index: 12; width: 296px; display: grid; grid-template-columns: repeat(8, 1fr); gap: 2px; + padding: 8px; border-radius: 12px; background: #1d222d; border: 1px solid #2c3343; box-shadow: 0 10px 30px rgba(0, 0, 0, .5); } +.st-glyphs[hidden] { display: none; } +.st-glyphs button { border: 0; background: none; color: var(--fg); font: 20px "Symbola Web", "DejaVu Web"; font-variant-emoji: text; + padding: 5px 0; border-radius: 6px; cursor: pointer; } +.st-glyphs button:hover { background: #262d3b; color: var(--accent); } +.st-glyphs .none { grid-column: span 3; font: 13px "DejaVu Web", sans-serif; color: var(--muted); } +.st-local input[type=color] { flex: none; } +/* tabs; inside a pane the cards flow in columns (masonry: no holes under short cards) */ +.st-tabs { display: flex; gap: 4px; margin-bottom: 16px; border-bottom: 1px solid #262c39; overflow-x: auto; scrollbar-width: none; } +.st-tabs button { flex: none; } +.st-tabs button { border: 0; background: none; color: var(--muted); font: 700 16px "DejaVu Web", sans-serif; + padding: 10px 18px; cursor: pointer; border-bottom: 3px solid transparent; margin-bottom: -1px; white-space: nowrap; } +.st-tabs button:hover { color: var(--fg); } +.st-tabs button.on { color: var(--accent); border-bottom-color: var(--accent); } +.st-pane[hidden] { display: none; } +/* The boxes of a tab: rows that wrap, up to three boxes a row (380 px or wider), every row (the last one too) + stretched to the full width and its boxes made the same height. A box alone in its row, or marked .st-span, + takes the whole width and lays its fields out in columns (below). General merges its form boxes with Sync's + and System's (.st-merge: the wrappers step aside, the boxes join .st-body's rows). */ +.st-body, .st-cols { display: flex; flex-wrap: wrap; gap: 16px; align-items: stretch; } +.st-body > *, .st-body > form > * { flex: 1 1 100%; min-width: 0; } +.st-body > form, .st-merge:not([hidden]), .st-merge > .st-cols { display: contents; } +.st-cols > .st-card, .st-merge > .st-cols > .st-card { flex: 1 1 340px; } /* + 40 px padding: 380 px boxes */ +.st-cols > .st-span { flex-basis: 100%; } +.st-merge > .st-cols > .st-span { flex-basis: 100%; order: 1; } /* General: Plugins under the rest */ +.st-card > .us-bar:last-child, .st-card > .st-plinks:last-child { margin-top: auto; } /* buttons line up at the bottom */ +:is(:not(.st-merge) > .st-cols > .st-card:only-child, .st-cols > .st-span), +:is(:not(.st-merge) > .st-cols > .st-card:only-child, .st-cols > .st-span) .st-pfields { + display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 300px), 1fr)); gap: 12px 28px; align-content: start; } +:is(:not(.st-merge) > .st-cols > .st-card:only-child, .st-cols > .st-span) > * { grid-column: 1 / -1; } +:is(:not(.st-merge) > .st-cols > .st-card:only-child, .st-cols > .st-span) > + :is(.us-f, .st-field, .st-check, .us-two, .st-plug, .st-band, .us-member) { grid-column: auto; } +:is(:not(.st-merge) > .st-cols > .st-card:only-child, .st-cols > .st-span) > :is(.us-bar, .st-plinks) { margin-top: 4px; } +.st-pf { display: flex; flex-direction: column; gap: 12px; min-width: 0; } +.st-card { background: var(--card); border-radius: 14px; padding: 18px 20px; display: flex; flex-direction: column; gap: 12px; + font-size: 15px; min-width: 0; } +.st-card h2 { margin: 0; font: 700 18px "DejaVu Web", sans-serif; display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px 12px; } +.st-status { font: 400 13px "DejaVu Web", sans-serif; color: var(--dim); } +.st-note { margin: 0; color: var(--dim); font-size: 13.5px; line-height: 1.45; } +.st-note b { color: var(--muted); font-weight: 400; } +.st-field { display: flex; flex-direction: column; gap: 5px; min-width: 0; } +.st-field > span { color: var(--muted); font-size: 13.5px; } +.st-card input:not([type=checkbox]):not([type=radio]):not([type=color]), .st-card select, .st-card textarea { + font: 15px "DejaVu Web", sans-serif; color: var(--fg); background: #1d222d; border: 1px solid #2c3343; + border-radius: 8px; padding: 8px 10px; min-width: 0; width: 100%; box-sizing: border-box; color-scheme: dark; } +.st-card input:focus, .st-card select:focus, .st-card textarea:focus { outline: 2px solid var(--accent); outline-offset: -1px; } +.st-card .bad { outline: 2px solid #ff6b6b !important; outline-offset: -1px; } +.st-card input[type=color] { width: 54px; height: 38px; padding: 2px; border: 1px solid #2c3343; border-radius: 8px; background: #1d222d; flex: none; } +.st-check { display: flex; align-items: center; gap: 9px; cursor: pointer; } +.st-check input, .st-days input, .st-seg input { accent-color: var(--accent); width: 17px; height: 17px; margin: 0; } +.st-pair { display: flex; gap: 10px; } +.st-pair > * { flex: 1; } +.st-seg { display: flex; gap: 8px; flex-wrap: wrap; } +.st-seg label { display: flex; align-items: center; gap: 8px; padding: 8px 14px; border-radius: 8px; background: #1d222d; cursor: pointer; } +.st-seg label:has(input:checked) { background: #262d3b; color: var(--accent); } +.st-places { display: flex; flex-direction: column; gap: 8px; } +.st-places:empty { display: none; } +.st-place { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr) minmax(0, 1fr) auto; gap: 8px; } +.st-x { border: 0; background: #262d3b; color: var(--muted); border-radius: 8px; padding: 0 12px; cursor: pointer; font-size: 15px; } +.st-x:hover { color: #ff8a8a; } +.st-search { position: relative; } +.st-results { display: flex; flex-direction: column; margin-top: 4px; color: var(--dim); font-size: 13.5px; } +.st-results button { text-align: left; border: 0; background: #1d222d; color: var(--fg); padding: 8px 10px; cursor: pointer; + font: 14px "DejaVu Web", sans-serif; border-bottom: 1px solid #262c39; } +.st-results button:first-child { border-radius: 8px 8px 0 0; } .st-results button:last-child { border-radius: 0 0 8px 8px; border: 0; } +.st-results button:only-child { border-radius: 8px; } +.st-results button:hover { background: #262d3b; color: var(--accent); } +.st-band { display: flex; flex-wrap: wrap; align-items: center; gap: 10px 18px; padding: 10px 0; border-top: 1px solid #262c39; } +.st-inline { display: flex; align-items: center; gap: 8px; color: var(--muted); } +.st-card .st-inline input { width: auto; } +.st-days { display: flex; flex-wrap: wrap; gap: 4px; } +.st-days label { display: flex; align-items: center; gap: 4px; padding: 4px 7px; border-radius: 6px; background: #1d222d; font-size: 13px; cursor: pointer; } +.st-bar { position: fixed; left: 0; right: 0; bottom: 0; z-index: 6; display: flex; align-items: center; justify-content: flex-end; + gap: 16px; padding: 12px max(16px, calc((100vw - 1400px) / 2 + 16px)); background: rgba(13, 16, 23, .94); + border-top: 1px solid #222837; backdrop-filter: blur(6px); } +.st-msg { flex: 1; color: var(--muted); font-size: 15px; } +.st-msg.ok { color: var(--t-ok, #7fd6a3); } .st-msg.err { color: #ff7a7a; } +.st-btn { padding: 10px 22px; border: 0; border-radius: 10px; background: var(--accent); color: var(--bg); cursor: pointer; + font: 700 16px "DejaVu Web", sans-serif; } +.st-btn:disabled { opacity: .5; cursor: wait; } +.st-restart { display: flex; flex-wrap: wrap; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 16px; + padding: 14px 18px; border-radius: 12px; background: #3a2f17; color: #ffd28a; font-size: 15px; } +.st-restart[hidden] { display: none; } +.page-settings ~ .sound-off { bottom: 76px; } +@media (max-width: 599px) { + .st-place { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; } + .st-place input:first-child { grid-column: 1 / -1; } +} + +/* phones: each calendar as a two-line row — [show] name ............ [new events] + pictogram editing badge */ +@media (max-width: 699px) { + .st-tabs button { padding: 10px 12px; } + .st-cals thead { display: none; } + .st-cals tbody tr { display: grid; grid-template-columns: 34px minmax(0, 1fr) auto; grid-template-areas: "s n c" ". g e"; + align-items: center; gap: 6px 8px; padding: 10px 0; border-bottom: 1px solid #1f2430; } + .st-cals td { padding: 0; border: 0; width: auto !important; text-align: left !important; } + .st-cs { grid-area: s; } .st-cn { grid-area: n; } .st-cc { grid-area: c; } + .st-cg { grid-area: g; } .st-ce { grid-area: e; justify-self: end; text-align: right !important; } + .st-cc::before { content: "New events"; color: var(--dim); font-size: 12px; margin-right: 6px; vertical-align: 3px; } + .st-cals tr.ro .st-cc { visibility: hidden; } + .st-cals .st-empty { grid-column: 1 / -1; } +} + +/* ---- log in (/login) ---------------------------------------------------------- */ +.page-login { display: flex; flex-direction: column; gap: 24px; } +.lg-box { align-self: center; width: min(380px, 100%); box-sizing: border-box; background: var(--card); border-radius: 14px; + padding: 22px 24px; font-size: 16px; display: flex; flex-direction: column; gap: 14px; } +.lg-box p { margin: 0; } +.lg-note { color: var(--muted); } +.lg-note a { color: var(--accent); } +.lg-form { display: flex; flex-direction: column; gap: 14px; } +.lg-form label { display: flex; flex-direction: column; gap: 6px; color: var(--muted); font-size: 14px; } +.lg-form input { font: inherit; font-size: 16px; color: var(--fg); background: #10131a; border: 1px solid #2c3343; + border-radius: 8px; padding: 9px 11px; } +.lg-form input:focus { outline: none; border-color: var(--accent); } +.lg-err { color: #ff7a6b; font-size: 14px; } +.lg-btn { font: inherit; font-size: 15px; font-weight: 700; color: #10131a; background: var(--accent); border: 0; + border-radius: 8px; padding: 9px 18px; cursor: pointer; align-self: flex-start; } + +/* ---- Settings ▸ Users (users.js) ------------------------------------------------- */ +.st-users .st-card h2 small { font: 400 13px "DejaVu Web", sans-serif; color: var(--dim); } +.us-f { display: flex; flex-direction: column; gap: 6px; color: var(--muted); font-size: 14px; min-width: 0; } +.us-two { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 12px 20px; align-items: start; } +.us-l { color: var(--muted); font-size: 13px; margin-bottom: 6px; text-transform: uppercase; letter-spacing: .03em; } +.us-picks { display: flex; flex-direction: column; gap: 7px; } +.us-sub { margin-left: 26px; } +.us-calbox { display: flex; flex-direction: column; gap: 8px; } +.us-cals { max-height: 260px; overflow: auto; padding-left: 26px; } +.us-cals input:disabled + * , .us-cals label:has(input:disabled) { opacity: .55; } +.us-member { display: flex; flex-direction: column; gap: 12px; } +.us-bar { display: flex; align-items: center; justify-content: flex-end; gap: 14px; flex-wrap: wrap; } +.us-bar .st-msg { color: var(--muted); font-size: 14px; } +.us-bar .st-msg.bad { color: #ff7a6b; } +.us-left { margin-right: auto; display: flex; gap: 18px; } +.us-link { background: none; border: 0; padding: 4px 0; color: var(--muted); font: inherit; font-size: 14px; cursor: pointer; } +.us-link:hover { color: var(--fg); } +.us-del.armed { color: #ff7a6b; } +.us-add { align-items: center; justify-content: center; min-height: 120px; border: 2px dashed #2c3343; background: none; + color: var(--accent); font: 700 16px "DejaVu Web", sans-serif; cursor: pointer; } +.us-add:hover, .us-add:focus-visible { border-color: var(--accent); } +.us-member[hidden], .st-bar[hidden] { display: none; } + +/* Settings ▸ General ▸ Sync / ▸ System (system.js) */ +.sy-code { margin: 0; padding: 14px; border-radius: 10px; background: #1d222d; font: 700 17px "DejaVu Web", monospace; + letter-spacing: .04em; white-space: pre-wrap; word-break: break-all; user-select: all; } +.sy-dev { display: flex; align-items: baseline; gap: 4px 12px; flex-wrap: wrap; } +.sy-dev.off { opacity: .55; } +.sy-dev .us-link { margin-left: auto; } +.sy-pair { display: flex; flex-direction: column; gap: 10px; } +.sy-qr { width: 240px; max-width: 100%; image-rendering: pixelated; border-radius: 8px; background: #fff; padding: 6px; } +.st-note.st-bad { color: #ff6b6b; } + +/* Settings ▸ Sensors (plugins/stations/static/sensors.js) */ +.sn-row { display: flex; flex-direction: column; gap: 8px; padding: 12px 0; border-top: 1px solid #262c39; } +.sn-row:first-of-type { border-top: 0; } +/* the sensors: boxes in columns; the kinds of source to add: tiles */ +.sn-rows { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 320px), 1fr)); gap: 12px; } +.sn-rows > .sn-row { border-top: 0; padding: 12px 14px; border-radius: 10px; background: #1b2030; } +.sn-rows > p { grid-column: 1 / -1; } +.sn-srcs { flex: 1 1 100%; } /* the sources: a row group of their own */ +.sn-kinds { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 240px), 1fr)); gap: 10px; } +.sn-kind { display: flex; flex-direction: column; gap: 4px; text-align: left; padding: 12px 14px; border: 1px solid #2c3343; + border-radius: 10px; background: #1b2030; color: var(--fg); font: inherit; cursor: pointer; } +.sn-kind span { color: var(--dim); font-size: 13.5px; line-height: 1.4; } +.sn-kind:hover, .sn-kind:focus-visible { border-color: var(--accent); } +.sn-kind:hover b { color: var(--accent); } +.sn-add { color: var(--accent); font-weight: 700; } +.sn-close { margin-left: auto; } +.sn-head { display: flex; align-items: baseline; gap: 4px 12px; flex-wrap: wrap; } +.sn-move { margin-left: auto; display: flex; gap: 10px; } +.sn-main { margin: 0; font-size: .9em; } +.sn-list { display: flex; flex-direction: column; gap: 4px; max-height: 320px; overflow: auto; } +.sn-item { display: grid; grid-template-columns: minmax(0, 1fr) auto auto; gap: 12px; align-items: baseline; } +.sn-ref { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.st-card textarea { resize: vertical; font: 14px "DejaVu Sans Mono", monospace; line-height: 1.5; } diff --git a/dashboard/static/dash.js b/dashboard/static/dash.js new file mode 100644 index 0000000..ea2538f --- /dev/null +++ b/dashboard/static/dash.js @@ -0,0 +1,720 @@ +// Tick the analog clock, open event cards, ding reminders, and keep the page fresh: +// it re-fetches itself every minute and whenever the tab comes back into view, +// swapping only the #page contents (a full reload when a deploy changed the CSS / JS). +(function () { + const page = document.getElementById("page"); + const BUILD = document.querySelector('meta[name="build"]')?.content; + + function tick() { + const h = document.getElementById("hand-h"); + if (!h) return; + const d = new Date(), sec = d.getSeconds(), min = d.getMinutes() + sec / 60; + const hr = (d.getHours() % 12) + min / 60; + h.setAttribute("transform", `rotate(${hr * 30})`); + document.getElementById("hand-m").setAttribute("transform", `rotate(${min * 6})`); + document.getElementById("hand-s").setAttribute("transform", `rotate(${sec * 6})`); + } + + // ---- event info card ---- + const card = document.getElementById("evcard"); + const newev = document.getElementById("newev"); // the new-event form, see below + const canCreate = document.body.dataset.create !== "0"; // the household / a read-only login: no new events + + function linkified(text) { // plain text -> nodes, URLs as safe links + const frag = document.createDocumentFragment(); + const re = /https?:\/\/[^\s<>"]+/g; + let last = 0, m; + while ((m = re.exec(text))) { + frag.append(text.slice(last, m.index)); + const a = document.createElement("a"); + a.href = m[0]; a.textContent = m[0]; a.target = "_blank"; a.rel = "noopener noreferrer"; + frag.append(a); + last = m.index + m[0].length; + } + frag.append(text.slice(last)); + return frag; + } + + function openCard(id) { + const data = JSON.parse(document.getElementById("evdata")?.textContent || "[]")[id]; + if (data) showCard(data); + } + + function showCard(data) { + const q = (c) => card.querySelector(c); + card.style.setProperty("--ec", data.colour); + q(".ec-title").textContent = (data.icon ? data.icon + " " : "") + data.title; + q(".ec-when").textContent = data.when; + q(".ec-extra").textContent = data.extra || ""; + q(".ec-cal").textContent = data.cal || ""; + q(".ec-loc").textContent = data.loc || ""; + q(".ec-desc").replaceChildren(linkified(data.desc || "")); + const u = q(".ec-url"); + if (/^https?:\/\//.test(data.url || "")) { u.href = data.url; u.textContent = data.url; } + else { u.removeAttribute("href"); u.textContent = ""; } + const ed = q(".ec-edit"); // open / edit the event where it lives + if (/^https:\/\//.test(data.edit || "")) { ed.href = data.edit; ed.textContent = data.edit_label + " ↗"; } + else { ed.removeAttribute("href"); ed.textContent = ""; } + const del = q(".ec-del"); // local events live only here: delete in place + del.hidden = !data.local_uid || !canCreate; + del.dataset.uid = data.local_uid || ""; + del.textContent = "Delete"; + del.classList.remove("armed"); + card.hidden = false; + } + function closeCard() { + card.hidden = true; + if (current) { markDismissed(current.key); current = null; } // a reminder: dismissed for good + if (/^#ev=/.test(location.hash)) history.replaceState(null, "", location.pathname + location.search); + setTimeout(nextReminder, 250); + if (missed) refresh(); // a refresh was skipped while the card was open + } + + // ---- reminders: ding + open the event's card when a VALARM fires ---- + const DKEY = "dash.dismissed"; + const DING_VOLUME = 0.33; // reminder chime loudness (1 = the original level) + const timers = {}, queue = []; + let current = null, actx = null; + + function dismissed() { + try { return JSON.parse(localStorage.getItem(DKEY) || "{}"); } catch (e) { return {}; } + } + function markDismissed(key) { + try { + const d = dismissed(), now = Date.now(); + d[key] = now; + for (const k in d) if (now - d[k] > 3 * 86400e3) delete d[k]; // forget after 3 days + localStorage.setItem(DKEY, JSON.stringify(d)); + } catch (e) { /* private window: dismissals last until reload */ } + } + function ding() { // two-tone chime, generated (no sound file) + try { + actx = actx || new (window.AudioContext || window.webkitAudioContext)(); + if (actx.state === "suspended") actx.resume(); + if (actx.state !== "running") { soundBtn.hidden = false; return; } // still blocked + const t = actx.currentTime; + [[880, 0], [1318.5, 0.18]].forEach(([f, o]) => { + const osc = actx.createOscillator(), g = actx.createGain(); + osc.type = "sine"; osc.frequency.value = f; + g.gain.setValueAtTime(0.0001, t + o); + g.gain.exponentialRampToValueAtTime(0.35 * DING_VOLUME, t + o + 0.02); + g.gain.exponentialRampToValueAtTime(0.0001, t + o + 1.2); + osc.connect(g).connect(actx.destination); + osc.start(t + o); osc.stop(t + o + 1.3); + }); + } catch (e) { /* no audio */ } + } + // Browsers only allow sound after a click / key press / tap on the page. Every such + // interaction (re)unlocks the audio; until then a corner button says sound is off. + const soundBtn = document.createElement("button"); + soundBtn.className = "sound-off"; + soundBtn.textContent = "🔇 Click to enable sound"; + soundBtn.hidden = true; + document.body.append(soundBtn); + function unlockAudio() { + try { + actx = actx || new (window.AudioContext || window.webkitAudioContext)(); + const p = actx.resume(); + const done = () => { soundBtn.hidden = actx.state === "running"; }; + p && p.then ? p.then(done, done) : done(); + } catch (e) { /* no Web Audio */ } + } + ["click", "keydown", "pointerdown", "touchend"].forEach((t) => addEventListener(t, unlockAudio, true)); + soundBtn.addEventListener("click", (e) => { e.stopPropagation(); unlockAudio(); setTimeout(ding, 150); }); + try { // show the button right away if audio starts blocked + actx = new (window.AudioContext || window.webkitAudioContext)(); + soundBtn.hidden = actx.state === "running"; + } catch (e) { /* no Web Audio */ } + + function nextReminder() { + if (current || !card.hidden || !newev.hidden) return; // one at a time; yours go first + current = queue.shift() || null; + if (!current) return; + if (dismissed()[current.key]) { current = null; return nextReminder(); } + ding(); + showCard(current.card); + } + function fire(r) { + delete timers[r.key]; + if (dismissed()[r.key] || queue.some((q) => q.key === r.key) || current?.key === r.key) return; + queue.push(r); + nextReminder(); + } + async function pollReminders() { + try { + const r = await fetch("/api/reminders", { cache: "no-store" }); + if (!r.ok) return; + for (const rem of await r.json()) { + if (timers[rem.key] || dismissed()[rem.key] || current?.key === rem.key) continue; + timers[rem.key] = setTimeout(() => fire(rem), Math.max(0, rem.at - Date.now())); + } + } catch (e) { /* offline: try again next minute */ } + } + card.addEventListener("click", async (e) => { + if (e.target.closest(".ec-x") || e.target.classList.contains("ec-back")) return closeCard(); + const del = e.target.closest(".ec-del"); + if (!del) return; + if (!del.classList.contains("armed")) { // two clicks, no browser dialog + del.classList.add("armed"); + del.textContent = "Click again to delete"; + return; + } + try { + const r = await fetch("/api/events/delete", { method: "POST", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ uid: del.dataset.uid }) }); + if (!r.ok || !(await r.json()).ok) throw new Error(); + closeCard(); + setTimeout(refresh, 2500); + } catch (err) { del.textContent = "Could not delete — try again"; del.classList.remove("armed"); } + }); + document.addEventListener("click", (e) => { // an event inside a link (day view, Upcoming) wins + const el = e.target.closest("#page [data-ev]"); + if (!el) return; + e.preventDefault(); e.stopPropagation(); + openCard(Number(el.dataset.ev)); + }, true); + + // ---- keeping the page fresh ---- + // setInterval alone isn't enough: browsers throttle or freeze background tabs (and a + // phone puts the whole page to sleep), so the view also refreshes as soon as it is + // visible again. Only one fetch at a time, given up after 20 s. + const EVERY = 60000; + let busy = false, missed = false, last = Date.now(); + + async function refresh() { + if (page.dataset.page === "settings" || "norefresh" in page.dataset) return; // forms: never swapped under your edits + if (!card.hidden || !newev.hidden) { missed = true; return; } // not under an open card / form + if (busy) return; + busy = true; + const ctl = new AbortController(), stop = setTimeout(() => ctl.abort(), 20000); + try { + const r = await fetch(location.href, { cache: "no-store", signal: ctl.signal }); + if (!r.ok) return; + const doc = new DOMParser().parseFromString(await r.text(), "text/html"); + const build = doc.querySelector('meta[name="build"]')?.content; + if (BUILD && build && build !== BUILD) { location.reload(); return; } // new CSS / JS deployed + const fresh = doc.getElementById("page"); + if (!fresh || !card.hidden || !newev.hidden) { missed = !!fresh; return; } + const scrolls = [...page.querySelectorAll(".hscroll")].map((el) => el.scrollLeft); + page.innerHTML = fresh.innerHTML; + page.querySelectorAll(".hscroll").forEach((el, i) => { if (scrolls[i]) el.scrollLeft = scrolls[i]; }); + document.title = doc.title; + missed = false; + last = Date.now(); + tick(); + } catch (e) { /* offline / Pi restarting: keep the old view, try again later */ } + finally { clearTimeout(stop); busy = false; } + } + function refreshIfStale() { + if (document.visibilityState === "visible" && Date.now() - last > 20000) refresh(); + } + document.addEventListener("visibilitychange", refreshIfStale); + addEventListener("pageshow", (e) => { if (e.persisted) refresh(); }); // back / forward cache + addEventListener("online", refresh); + addEventListener("focus", refreshIfStale); + + function scrollToToday() { // narrow week view: today's column in sight + const wk = page.querySelector(".wk"), t = page.querySelector(".wk-day.today"); + if (!wk || !t || wk.scrollWidth <= wk.clientWidth) return; + wk.scrollLeft = t.offsetLeft + t.offsetParent.offsetLeft - (wk.clientWidth - t.offsetWidth) / 2; + } + + // ---- new events, Google Calendar style ------------------------------------------- + // Mouse: click an empty spot on a timeline (week columns, Home's day view) for a 1-hour + // event, or drag from start to end; drag across the week's all-day row (day headers + + // bars) for an all-day / multi-day one; click an empty part of a month day for an + // all-day one (the day number still opens that week). Touch: taps only, so the page + // still scrolls. A form then asks for the title and the calendar (see cal.create_event). + const SCALE = JSON.parse(document.body.dataset.scale || "[]"); // webview.SCALE: the time axis + const form = newev.querySelector("form"), F = form.elements; + const SNAP = 0.25; // 15 minutes + const TOTAL = SCALE.reduce((s, [a, b, w]) => s + (b - a) * w, 0); + + function hourAt(frac) { // 0..1 down a timeline -> hour (webview.hour_to_y⁻¹) + let acc = Math.max(0, Math.min(1, frac)) * TOTAL; + for (const [a, b, w] of SCALE) { + if (acc <= (b - a) * w) return a + acc / w; + acc -= (b - a) * w; + } + return 24; + } + function pctAt(h) { // hour -> % down a timeline + let acc = 0; + for (const [a, b, w] of SCALE) { acc += (Math.min(h, b) - a) * w; if (h <= b) break; } + return acc / TOTAL * 100; + } + const floorQ = (h) => Math.floor(h / SNAP) * SNAP; + const ceilQ = (h) => Math.ceil(h / SNAP) * SNAP; + function hhmm(h) { + if (h >= 24) return "23:59"; + const m = Math.round(h * 60); + return String(Math.floor(m / 60)).padStart(2, "0") + ":" + String(m % 60).padStart(2, "0"); + } + + let drag = null, swallow = false, ghost = null; + function clearGhost() { ghost?.remove(); ghost = null; } + function showGhost(tl, a, b) { + if (!ghost || ghost.parentNode !== tl) { clearGhost(); ghost = document.createElement("div"); ghost.className = "ghost"; tl.append(ghost); } + ghost.style.top = pctAt(a) + "%"; + ghost.style.height = (pctAt(b) - pctAt(a)) + "%"; + ghost.textContent = hhmm(a) + " – " + hhmm(b); + } + function weekCol(x) { // the week column under x (all-day row) + const cols = [...page.querySelectorAll(".wk-col[data-day]")]; + return cols.findIndex((c) => { const r = c.getBoundingClientRect(); return x >= r.left && x < r.right; }); + } + + page.addEventListener("pointerdown", (e) => { + if (!canCreate || e.button !== 0 || !newev.hidden || !card.hidden || e.target.closest("[data-ev]")) return; + const base = { x: e.clientX, y: e.clientY, moved: false, touch: e.pointerType !== "mouse" }; + const tl = e.target.closest(".tl[data-day]"); + if (tl) { + const r = tl.getBoundingClientRect(); + drag = { ...base, kind: "timed", tl, r, h0: floorQ(hourAt((e.clientY - r.top) / r.height)) }; + } else if (e.target.closest(".wk-cols") && !e.target.closest(".wk-tl")) { + const c = weekCol(e.clientX); + if (c < 0) return; + drag = { ...base, kind: "allday", c0: c, c1: c }; + } else return; + if (!base.touch) e.preventDefault(); // no text selection / link dragging + }); + addEventListener("pointermove", (e) => { + if (!drag) return; + if (!drag.moved && Math.hypot(e.clientX - drag.x, e.clientY - drag.y) < 6) return; + if (drag.touch) { drag = null; return; } // a finger moving = scrolling, not selecting + drag.moved = true; + if (drag.kind === "timed") { + const h = hourAt((e.clientY - drag.r.top) / drag.r.height); + drag.a = Math.min(drag.h0, floorQ(h)); + drag.b = Math.max(drag.h0 + SNAP, ceilQ(h)); + showGhost(drag.tl, drag.a, drag.b); + } else { + const c = weekCol(e.clientX); + if (c >= 0) drag.c1 = c; + page.querySelectorAll(".wk-day").forEach((el, i) => + el.classList.toggle("pick", i >= Math.min(drag.c0, drag.c1) && i <= Math.max(drag.c0, drag.c1))); + } + }); + addEventListener("pointerup", () => { + if (!drag) return; + const d = drag; + drag = null; + swallow = true; // the click that follows must not follow a link + setTimeout(() => { swallow = false; }, 400); + if (d.kind === "timed") { + const day = d.tl.dataset.day; + if (!d.moved) { const s = Math.min(d.h0, 23); d.a = s; d.b = s + 1; showGhost(d.tl, s, s + 1); } + openNew({ date: day, start: d.a, end: d.b, tl: d.tl, anchor: () => ghost?.getBoundingClientRect() }); + } else { + const days = [...page.querySelectorAll(".wk-col[data-day]")].map((c) => c.dataset.day); + if (!d.moved) page.querySelectorAll(".wk-day").forEach((el, i) => el.classList.toggle("pick", i === d.c0)); + openNew({ date: days[Math.min(d.c0, d.c1)], endDate: days[Math.max(d.c0, d.c1)], allDay: true, + anchor: () => span([...page.querySelectorAll(".wk-day.pick")]) }); + } + }); + addEventListener("pointercancel", () => { drag = null; }); + document.addEventListener("click", (e) => { + if (swallow) { swallow = false; e.preventDefault(); e.stopPropagation(); return; } + const cell = e.target.closest("#page .mo-cell[data-day]"); // month: empty part of a day + if (!cell || e.target.closest(".mo-num, [data-ev]") || matchMedia("(max-width: 599px)").matches) return; + e.preventDefault(); e.stopPropagation(); // (phones: the day opens its week, as before) + cell.classList.add("pick"); + openNew({ date: cell.dataset.day, allDay: true, anchor: () => cell.getBoundingClientRect() }); + }, true); + + // A composer opens next to what it's for (the new-event form here, workload.js's entry form): + // right of the anchor if it fits, else left, else over it; top level with it, kept inside the + // window. Narrow windows (phones) keep the centred dialog. rect = a DOMRect or null. + function place(wrap, box, rect) { + const on = !!rect && innerWidth >= 700; + wrap.classList.toggle("anchored", on); + if (!on) { box.style.left = box.style.top = ""; return; } + const w = box.offsetWidth, h = box.offsetHeight, gap = 12; + let x = rect.right + gap; + if (x + w > innerWidth - 8) x = rect.left - gap - w; + if (x < 8) x = Math.max(8, Math.min(innerWidth - w - 8, rect.left + rect.width / 2 - w / 2)); + box.style.left = x + "px"; + box.style.top = Math.max(8, Math.min(innerHeight - h - 8, rect.top)) + "px"; + } + window.dashPlace = place; + function span(els) { // the box around several elements (picked days) + const rs = els.map((el) => el.getBoundingClientRect()); + if (!rs.length) return null; + const l = Math.min(...rs.map((r) => r.left)), t = Math.min(...rs.map((r) => r.top)); + return new DOMRect(l, t, Math.max(...rs.map((r) => r.right)) - l, Math.max(...rs.map((r) => r.bottom)) - t); + } + + let targets = null; + const HINT = { caldav: "Saved to Nextcloud, then opened there to add details.", + google: "Opens Google Calendar to finish it there.", + local: "Saved on this dashboard only." }; + async function loadTargets() { + if (!targets || !targets.length) { + try { targets = await (await fetch("/api/calendars", { cache: "no-store" })).json(); } + catch (e) { targets = []; } + } + return targets; + } + function syncForm() { + const allDay = F.all_day.checked; + form.querySelector(".ne-times").hidden = allDay; + form.querySelector(".ne-days").hidden = !allDay; + const t = (targets || []).find((x) => x.id === F.cal.value); + form.querySelector(".ne-dot").style.background = t?.colour || "var(--muted)"; + form.querySelector(".ne-save").title = form.querySelector(".ne-dot").title = t ? HINT[t.kind] : ""; + form.querySelector(".ne-save").textContent = t && t.kind !== "local" ? "Save & open ↗" : "Save"; + // the ghost follows the times typed (same day as where it was drawn) + if (newTl && !allDay && F.date.value === newTl.dataset.day && F.start.value && F.end.value) { + const [a, b] = [F.start.value, F.end.value].map((v) => { const [h, m] = v.split(":").map(Number); return h + m / 60; }); + if (b > a) showGhost(newTl, a, b); + } else if (newTl) clearGhost(); + place(newev, form, newAnchor?.() || null); + } + function formError(msg) { form.querySelector(".ne-err").textContent = msg || ""; } + let newTl = null, newAnchor = null; // the timeline the event was drawn on; its rect + async function openNew(o) { + newTl = o.tl || null; newAnchor = o.anchor || null; + form.reset(); + F.date.value = o.date; + F.end_date.value = o.endDate || o.date; + F.start.value = hhmm(o.start ?? 9); + F.end.value = hhmm(o.end ?? 10); + F.all_day.checked = !!o.allDay; + formError(""); + newev.hidden = false; + place(newev, form, newAnchor?.() || null); + F.title.focus(); + const ts = await loadTargets(); + const groups = { caldav: "Nextcloud", google: "Google Calendar", local: "This dashboard" }; + F.cal.replaceChildren(...Object.entries(groups).map(([kind, label]) => { + const g = document.createElement("optgroup"); + g.label = label; + g.append(...ts.filter((t) => t.kind === kind).map((t) => new Option(t.name, t.id))); + return g; + }).filter((g) => g.children.length)); + let lastCal = null; + try { lastCal = localStorage.getItem("dash.newcal"); } catch (e) { /* private window */ } + if (ts.some((t) => t.id === lastCal)) F.cal.value = lastCal; + if (!ts.length) formError("Calendars not loaded yet — try again in a minute."); + syncForm(); + } + function closeNew() { + newev.hidden = true; + clearGhost(); + newTl = newAnchor = null; + page.querySelectorAll(".wk-day.pick, .mo-cell.pick").forEach((el) => el.classList.remove("pick")); + if (missed) refresh(); + } + form.addEventListener("change", syncForm); + form.addEventListener("input", (e) => { if (e.target === F.start || e.target === F.end) syncForm(); }); + addEventListener("resize", () => { if (!newev.hidden) place(newev, form, newAnchor?.() || null); }); + newev.addEventListener("click", (e) => { + if (e.target.closest(".ec-x") || e.target.classList.contains("ec-back")) closeNew(); + }); + form.addEventListener("submit", async (e) => { + e.preventDefault(); + const t = (targets || []).find((x) => x.id === F.cal.value); + if (!F.title.value.trim()) return formError("Add a title."); + if (!t) return formError("Pick a calendar."); + try { localStorage.setItem("dash.newcal", t.id); } catch (err) { /* private window */ } + // open the tab now, while this is still a click: after the await, popup blockers say no + const win = t.kind !== "local" ? open("", "_blank") : null; + const save = form.querySelector(".ne-save"); + save.disabled = true; + formError(""); + try { + const r = await fetch("/api/events", { + method: "POST", headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ cal: t.id, title: F.title.value, date: F.date.value, start: F.start.value, + end: F.end.value, end_date: F.end_date.value, all_day: F.all_day.checked, + location: F.location.value }) }); + const j = await r.json().catch(() => ({})); + if (!r.ok) { win?.close(); return formError(j.error || `Error ${r.status}`); } + closeNew(); + if (j.open) { if (win) win.location = j.open; else location.href = j.open; } + else win?.close(); + setTimeout(refresh, 3000); // the sync picks the new event up within seconds + setTimeout(refresh, 10000); + } catch (err) { win?.close(); formError("The dashboard is not reachable."); } + finally { save.disabled = false; } + }); + + // ---- settings page (/settings, settings.py) ------------------------------------------ + // Fields carry data-f="a.b.0.c"; collect() turns them into the nested JSON + // settings.apply() expects. Errors come back naming the same path. + let settingsDirty = false; + function initSettings() { + const form = document.getElementById("settings"); + if (!form) return; + const msg = document.getElementById("st-msg"), places = document.getElementById("st-places"); + + // ---- tabs: panes of one form (one Save); the open tab is kept in the URL (#calendar). + // A plugin's tab may also have a panel outside the form (it saves on its own) and keep + // its own state after the name: #work&n=5. + const tabs = [...document.querySelectorAll(".st-tabs [data-tab]")]; + function showTab(name, rest = "") { + if (name === "sync" || name === "system") name = "general"; // their own tabs once; now part of General + if (!tabs.some((t) => t.dataset.tab === name && !t.hidden)) name = "general"; + tabs.forEach((t) => { t.classList.toggle("on", t.dataset.tab === name); t.setAttribute("aria-selected", t.dataset.tab === name); }); + document.querySelectorAll(".st-pane").forEach((p) => { p.hidden = p.dataset.pane !== name; }); + // a tab with no fields in the form (Users, Sensors) saves on its own: no form Save + form.querySelector(".st-bar").hidden = !form.querySelector(`.st-pane[data-pane="${name}"]`); + history.replaceState(null, "", "#" + name + rest); + } + tabs.forEach((t) => t.addEventListener("click", () => showTab(t.dataset.tab))); + const fromHash = () => { const [name, ...rest] = location.hash.slice(1).split("&"); showTab(name, rest.length ? "&" + rest.join("&") : ""); }; + fromHash(); + window.addEventListener("hashchange", fromHash); // a link to another tab of this page (#sensors) + // General ▸ Plugins: ticking one shows its tab right away (the setting itself waits for Save) + form.querySelectorAll("[data-tab-toggle]").forEach((cb) => cb.addEventListener("change", () => { + const t = tabs.find((x) => x.dataset.tab === cb.dataset.tabToggle); + if (t) t.hidden = !cb.checked; + cb.closest(".st-plug")?.classList.toggle("off", !cb.checked); + })); + + // ---- pictogram picker (Symbola glyphs, black-and-white like on the screen) + const picker = document.getElementById("st-glyphs"); + let pickFor = null; + form.addEventListener("click", (e) => { + const b = e.target.closest(".st-pick"); + if (!b) return; + pickFor = b.previousElementSibling; + const r = b.getBoundingClientRect(); + picker.hidden = false; + picker.style.top = (r.bottom + scrollY + 4) + "px"; + picker.style.left = Math.max(8, Math.min(r.right - picker.offsetWidth, innerWidth - picker.offsetWidth - 8) + scrollX) + "px"; + }); + picker.addEventListener("click", (e) => { + const b = e.target.closest("button"); + if (!b || !pickFor) return; + pickFor.value = b.hasAttribute("data-none") ? "" : b.textContent; + picker.hidden = true; + dirty(); + }); + document.addEventListener("pointerdown", (e) => { + if (!picker.hidden && !e.target.closest("#st-glyphs, .st-pick")) picker.hidden = true; + }); + addEventListener("keydown", (e) => { if (e.key === "Escape") picker.hidden = true; }); + + // ---- calendars table: a row's Show off greys it; "Reload from Nextcloud" re-lists them + const cals = document.getElementById("st-cals"); + const markRows = () => cals.querySelectorAll("tbody tr").forEach((tr) => { + const show = tr.querySelector('[data-f$=".shown"]'); + tr.classList.toggle("off", !!show && !show.checked); + }); + cals.addEventListener("change", markRows); + markRows(); + document.getElementById("st-reload").addEventListener("click", async (e) => { + const btn = e.target; + btn.disabled = true; + say("Asking Nextcloud…"); + try { + const r = await fetch("/api/calendars/reload", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" }); + if (!r.ok) throw new Error((await r.json().catch(() => ({}))).error || r.status); + // fresh rows from the server, keeping what you already changed in rows it still has + const keep = {}; + cals.querySelectorAll("tbody tr[data-name]").forEach((tr) => { + keep[tr.dataset.name] = [...tr.querySelectorAll("[data-f]")].map((el) => [el.dataset.f.split(".").pop(), el.type === "checkbox" ? el.checked : el.value]); + }); + const doc = new DOMParser().parseFromString(await (await fetch("/settings", { cache: "no-store" })).text(), "text/html"); + cals.tBodies[0].replaceWith(doc.getElementById("st-cals").tBodies[0]); + cals.querySelectorAll("tbody tr[data-name]").forEach((tr) => { + for (const [k, val] of keep[tr.dataset.name] || []) { + const el = tr.querySelector(`[data-f$=".${k}"]`); + if (!el || el.disabled) continue; + if (el.type === "checkbox") el.checked = val; else if (el.type !== "hidden") el.value = val; + } + }); + markRows(); + pollStatus(); + say(`Calendars reloaded — ${cals.querySelectorAll("tbody tr[data-name]").length} found.`, "ok"); + } catch (err) { say(`Reload failed (${err.message}).`, "err"); } + finally { btn.disabled = false; } + }); + const say = (text, kind) => { msg.textContent = text; msg.className = "st-msg " + (kind || ""); }; + const dirty = () => { settingsDirty = true; say("Unsaved changes"); }; + form.addEventListener("input", (e) => { e.target.classList.remove("bad"); if (!e.target.closest(".st-search")) dirty(); }); + + function collect() { + const out = {}; + form.querySelectorAll("[data-f]").forEach((el) => { + if (el.disabled) return; // e.g. "New events" on a read-only calendar + const path = el.dataset.f.split("."); + let o = out; + for (let i = 0; i < path.length - 1; i++) { + o[path[i]] = o[path[i]] ?? (/^\d+$/.test(path[i + 1]) ? [] : {}); + o = o[path[i]]; + } + const k = path[path.length - 1]; + if (el.dataset.multi) { o[k] = o[k] || []; if (el.checked) o[k].push(Number(el.dataset.multi)); } + else if (el.type === "radio") { if (el.checked) o[k] = el.value; } + else if (el.type === "checkbox") o[k] = el.checked; + else o[k] = el.value; + }); + if (out.places) out.places = out.places.filter(Boolean); + return out; + } + + // ---- extra weather places: rows, renumbered after every add / remove + function renumber() { + [...places.children].forEach((row, i) => row.querySelectorAll("[data-f]").forEach((el) => { + el.dataset.f = el.dataset.f.replace(/^places\.(\d+|N)/, "places." + i); + })); + } + function addPlace(p) { + if (places.children.length >= 6) return say("Up to 6 places.", "err"); + const row = document.getElementById("st-place-row").content.firstElementChild.cloneNode(true); + const [n, la, lo] = row.querySelectorAll("input"); + n.value = p.name; la.value = p.lat; lo.value = p.lon; + places.append(row); + renumber(); + dirty(); + } + places.addEventListener("click", (e) => { + const x = e.target.closest(".st-x"); + if (!x) return; + x.closest(".st-place").remove(); + renumber(); + dirty(); + }); + + // ---- place search (Open-Meteo geocoding via /api/geocode) + form.querySelectorAll(".st-search").forEach((box) => { + const input = box.querySelector("input"), results = box.querySelector(".st-results"); + let timer = null, seq = 0; + input.addEventListener("input", () => { + clearTimeout(timer); + const q = input.value.trim(); + if (q.length < 2) { results.replaceChildren(); return; } + timer = setTimeout(async () => { + const my = ++seq; + try { + const list = await (await fetch("/api/geocode?q=" + encodeURIComponent(q))).json(); + if (my !== seq) return; // a newer search is on its way + results.replaceChildren(...(Array.isArray(list) ? list : []).map((p) => { + const b = document.createElement("button"); + b.type = "button"; + b.textContent = `${p.label} (${p.lat}, ${p.lon})`; + b.addEventListener("click", () => { + if (box.dataset.target === "location") { + form.querySelector('[data-f="location.name"]').value = p.name; + form.querySelector('[data-f="location.lat"]').value = p.lat; + form.querySelector('[data-f="location.lon"]').value = p.lon; + dirty(); + } else addPlace(p); + input.value = ""; + results.replaceChildren(); + }); + return b; + })); + if (!results.children.length) results.textContent = "No place found."; + } catch (err) { results.textContent = "Search failed — is the Pi online?"; } + }, 350); + }); + }); + + // ---- worker states next to the section titles + async function pollStatus() { + try { + const st = await (await fetch("/api/status", { cache: "no-store" })).json(); + form.querySelectorAll("[data-status]").forEach((el) => { el.textContent = st[el.dataset.status] || ""; }); + document.getElementById("st-restart").hidden = !st.restart; + return true; + } catch (err) { return false; } + } + + form.addEventListener("submit", async (e) => { + e.preventDefault(); + form.querySelectorAll(".bad").forEach((el) => el.classList.remove("bad")); + const save = form.querySelector(".st-save"); + save.disabled = true; + say("Saving…"); + try { + const r = await fetch("/api/settings", { method: "POST", headers: { "Content-Type": "application/json" }, + body: JSON.stringify(collect()) }); + const j = await r.json().catch(() => ({})); + if (!r.ok) { + say(j.error || `Error ${r.status}`, "err"); + const el = j.field && (form.querySelector(`[data-f="${j.field}"]`) || form.querySelector(`[data-f^="${j.field}"]`)); + if (el) showTab(el.closest(".st-pane")?.dataset.pane); // the field may sit in another tab + if (el) { el.classList.add("bad"); el.scrollIntoView({ block: "center", behavior: "smooth" }); el.focus({ preventScroll: true }); } + return; + } + settingsDirty = false; + say("Saved ✓ — applying…", "ok"); + form.querySelectorAll('input[type="password"]').forEach((el) => { + if (el.value) { el.value = ""; el.placeholder = "•••••••• saved — type to replace"; } + }); + document.getElementById("st-restart").hidden = !j.restart; + setTimeout(pollStatus, 4000); // the workers report back within seconds + setTimeout(async () => { await pollStatus(); say("Saved ✓", "ok"); }, 12000); + } catch (err) { say("The dashboard is not reachable.", "err"); } + finally { save.disabled = false; } + }); + + document.getElementById("st-restart-btn").addEventListener("click", async (e) => { + if (settingsDirty) return say("Save your changes first.", "err"); + e.target.disabled = true; + say("Restarting…"); + try { await fetch("/api/restart", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" }); } + catch (err) { /* it may go down before answering */ } + const t0 = Date.now(); + await new Promise((ok) => setTimeout(ok, 3000)); + while (Date.now() - t0 < 60000) { // back up? then show the fresh state + if (await pollStatus()) { location.reload(); return; } + await new Promise((ok) => setTimeout(ok, 2000)); + } + say("No answer after a minute — check `journalctl -u dashboard` on the Pi.", "err"); + e.target.disabled = false; + }); + } + initSettings(); + + addEventListener("keydown", (e) => { // h/Esc = home, w = week, m = month, s = settings, ←/→ + if (!newev.hidden) { if (e.key === "Escape") closeNew(); return; } // typing in the form + if (!card.hidden) { if (e.key === "Escape") closeCard(); return; } // card open: Esc closes it + if (e.target.closest?.("input, select, textarea")) return; + if (document.body.classList.contains("modal")) return; // a plugin's dialog is open + if (settingsDirty) return; // unsaved settings: no accidental navigation + if (page.dataset.page === "settings" && e.key === "Escape") return; // Esc closes the picker there + if (e.key === "s") { location.href = document.querySelector(".btn.gear")?.href || "/settings"; return; } + if (e.key === "h" || e.key === "Escape") location.href = "/"; + else if (e.key === "w") location.href = "/week"; + else if (e.key === "m") location.href = "/month"; + else if (e.key === "ArrowLeft" || e.key === "ArrowRight") { + const a = document.querySelector(e.key === "ArrowLeft" ? ".btn.prev" : ".btn.next"); + if (a && !a.classList.contains("off")) location.href = a.href; + } + }); + tick(); + scrollToToday(); + const deep = /^#ev=(\d+)$/.exec(location.hash); // e.g. /month#ev=3 opens that card + if (deep) openCard(Number(deep[1])); + setInterval(tick, 1000); + setInterval(refresh, EVERY); + pollReminders(); + setInterval(pollReminders, 60000); + + // ?demo-reminder: after your first click, a fake reminder for the next event fires in 5 s + if (/[?&]demo-reminder/.test(location.search)) { + const hint = document.createElement("div"); + hint.className = "demo-hint"; + hint.textContent = "Test reminder: click anywhere to start (fires 5 s later)"; + document.body.append(hint); + addEventListener("click", async function start() { + removeEventListener("click", start, true); + hint.textContent = "Test reminder fires in 5 s…"; + try { + const [rem] = await (await fetch("/api/reminders?demo=1", { cache: "no-store" })).json(); + if (rem) setTimeout(() => { hint.remove(); fire(rem); }, 5000); + } catch (e) { hint.textContent = "Test reminder failed to load"; } + }, true); + } + // weather page: the place dropdown closes on a click elsewhere or Esc + document.addEventListener("click", (e) => { + document.querySelectorAll("details.wx-loc[open], details.tabs-more[open]").forEach((d) => { if (!d.contains(e.target)) d.open = false; }); + }); + document.addEventListener("keydown", (e) => { + if (e.key === "Escape") document.querySelectorAll("details.wx-loc[open], details.tabs-more[open]").forEach((d) => { d.open = false; }); + }); +})(); diff --git a/dashboard/static/favicon.svg b/dashboard/static/favicon.svg new file mode 100644 index 0000000..a3994e7 --- /dev/null +++ b/dashboard/static/favicon.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/dashboard/static/system.js b/dashboard/static/system.js new file mode 100644 index 0000000..464c5c7 --- /dev/null +++ b/dashboard/static/system.js @@ -0,0 +1,292 @@ +// Settings ▸ General ▸ Sync (sync.py, web /api/sync…) and Settings ▸ General (system.py, /api/system…): set up the +// sync from the browser, the account's devices + the phone's QR code, the web address, touch calibration, +// backup / restore. Like users.js: each card saves on its own; no browser dialogs (a risky button arms +// on the first click). +(() => { + const syncRoot = document.getElementById("st-sync"), sysRoot = document.getElementById("st-system"); + if (!syncRoot && !sysRoot) return; + const el = (tag, attrs = {}, ...kids) => { + const e = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (k === "class") e.className = v; else if (k === "text") e.textContent = v; + else if (k.startsWith("on")) e.addEventListener(k.slice(2), v); else if (v !== false && v != null) e.setAttribute(k, v === true ? "" : v); + } + kids.flat().forEach((k) => k != null && e.append(k)); + return e; + }; + const post = async (url, body) => { + let r; + try { r = await fetch(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body || {}) }); } + catch (_) { return { error: "No answer from the dashboard." }; } + let d = {}; try { d = await r.json(); } catch (_) { d = { error: `Failed (${r.status}).` }; } + if (!r.ok && !d.error) d.error = `Failed (${r.status}).`; + return d; + }; + const get = async (url) => (await fetch(url, { cache: "no-store" })).json(); + const ago = (t) => { + if (!t) return "never"; + const s = Date.now() / 1000 - (typeof t === "number" ? t : Date.parse(t) / 1000); + return s < 120 ? "just now" : s < 7200 ? `${Math.round(s / 60)} min ago` : s < 172800 ? `${Math.round(s / 3600)} h ago` : `${Math.round(s / 86400)} days ago`; + }; + const field = (label, input, title) => el("label", { class: "us-f", title }, label, input); + function bar(text, onClick, extra = []) { + const msg = el("span", { class: "st-msg" }); + const btn = el("button", { type: "button", class: "st-btn", text }); + btn.addEventListener("click", async () => { + btn.disabled = true; msg.textContent = ""; msg.classList.remove("bad"); + const d = await onClick(); + btn.disabled = false; + if (d && d.error) { msg.textContent = d.error; msg.classList.add("bad"); } else if (d && d.msg) msg.textContent = d.msg; + }); + return el("div", { class: "us-bar" }, el("div", { class: "us-left" }, extra), msg, btn); + } + function armed(text, armedText, onClick) { // click once to arm, again to do it + const b = el("button", { type: "button", class: "us-link us-del", text }); + b.addEventListener("click", async () => { + if (!b.classList.contains("armed")) { b.classList.add("armed"); b.textContent = armedText; return; } + b.disabled = true; + const d = await onClick(); + if (d && d.error) { b.textContent = d.error; b.disabled = false; } + }); + return b; + } + const restartBanner = () => { const r = document.getElementById("st-restart"); if (r) r.hidden = false; }; + const card = (title, status, ...kids) => el("section", { class: "st-card" }, + el("h2", {}, title, status ? el("small", { class: "st-status", text: status }) : null), ...kids); + const note = (html) => { const p = el("p", { class: "st-note" }); p.innerHTML = html; return p; }; + + // ================================ Sync ================================ + async function loadSync() { + let S; + try { S = await get("/api/sync"); } catch (_) { syncRoot.replaceChildren(note("Could not load the sync state.")); return; } + if (!S.nacl) { + syncRoot.replaceChildren(card("Sync", "not available", + note("Sync needs PyNaCl on this computer: sudo apt install python3-nacl, then restart the dashboard."))); + return; + } + syncRoot.replaceChildren(...(S.configured ? syncOn(S) : [connectCard()])); + } + + function connectCard() { + const server = el("input", { type: "url", placeholder: "https://sync.example.com", autocomplete: "off" }); + const token = el("input", { type: "password", autocomplete: "off" }); + const step2 = el("div", { class: "us-member" }); + const intro = note("Sync keeps the phone app and other dashboards in step through your sync server, end-to-end encrypted. " + + "The server's set-up prints a device token for this dashboard (docs/server.md)."); + const c = card("Connect to a sync server", "not set up", intro, + field("Server", server), field("Device token", token), step2, + bar("Next", async () => { + const d = await post("/api/sync/probe", { server: server.value, token: token.value }); + if (d.error) return d; + server.disabled = token.disabled = true; + c.querySelector(".us-bar").hidden = true; + step2.replaceChildren(...(d.has_key ? joinStep(server, token, d) : firstStep(server, token, d))); + return d; + })); + return c; + } + + function firstStep(server, token, info) { // the account's first device: the data key is made here + const p1 = el("input", { type: "password", autocomplete: "new-password" }); + const p2 = el("input", { type: "password", autocomplete: "new-password" }); + return [note(`Account ${esc(info.account)}, this device is ${esc(info.device)} — the account's first: choose the ` + + "sync passphrase (10+ characters, a few random words are best). Every other device joins with it."), + field("Passphrase", p1), field("Passphrase again", p2), + bar("Set up", async () => { + if (p1.value !== p2.value) return { error: "The passphrases differ." }; + const d = await post("/api/sync/connect", { server: server.value, token: token.value, passphrase: p1.value }); + if (d.error) return d; + syncRoot.replaceChildren(recoveryCard(d.recovery)); + return d; + })]; + } + + function joinStep(server, token, info) { + const pass = el("input", { type: "password", autocomplete: "off" }); + const rec = el("input", { autocomplete: "off", placeholder: "ABCD-EFGH-…" }); + const recBox = field("Recovery key (instead of the passphrase)", rec); + recBox.hidden = true; + const toggle = el("button", { type: "button", class: "us-link", text: "Forgot it? Use the recovery key" }); + toggle.addEventListener("click", () => { recBox.hidden = !recBox.hidden; pass.parentElement.hidden = !recBox.hidden; }); + return [note(`Account ${esc(info.account)}, this device is ${esc(info.device)}: it has a key already — unlock it.`), + field("Sync passphrase", pass), recBox, + bar("Join", async () => { + const d = await post("/api/sync/connect", recBox.hidden + ? { server: server.value, token: token.value, passphrase: pass.value } + : { server: server.value, token: token.value, recovery: rec.value }); + if (!d.error) setTimeout(loadSync, 1500); + return d; + }, [toggle])]; + } + + function recoveryCard(code) { + const done = el("input", { type: "checkbox" }); + const b = el("button", { type: "button", class: "st-btn", text: "Done", disabled: true }); + done.addEventListener("change", () => { b.disabled = !done.checked; }); + b.addEventListener("click", loadSync); + return card("Write down the recovery key", "shown only now", + note("With it you can set a new passphrase if you forget yours. Without the passphrase and this key, " + + "the synced data can't be read by anyone — keep it on paper or in a password manager."), + el("pre", { class: "sy-code", text: code }), + el("label", { class: "st-check" }, done, "I've written it down"), + el("div", { class: "us-bar" }, b)); + } + + function syncOn(S) { + const r = S.result; + const last = S.last ? `last sync ${ago(S.last)}` + (r ? ` · got ${r.pulled.applied ?? 0}, sent ${r.pushed}` : "") : "not synced yet"; + const status = card("Sync", S.error ? "error" : "on", + note(`${esc(S.account)} · this dashboard is ${esc(S.device)} · ${esc(S.server)}`), + note(esc(last) + " · every 5 minutes"), + S.error ? el("p", { class: "st-note st-bad", text: S.error }) : null, + bar("Sync now", async () => { const d = await post("/api/sync/now"); if (!d.error) loadSync(); return d; }, + [armed("Disconnect", "Click again: this dashboard stops syncing (its data stays)", async () => { + const d = await post("/api/sync/disconnect"); if (!d.error) loadSync(); return d; })])); + + const prim = el("input", { type: "checkbox", checked: !!S.primary }); + const primary = card("Primary dashboard", null, + note("With several dashboards on one account, only one is primary: it works out the Health summaries for the app " + + "and keeps the station history, and mirrors the phone app for /app. The others get them through the sync."), + el("label", { class: "st-check" }, prim, "This is the primary dashboard"), + bar("Save", async () => { const d = await post("/api/sync/primary", { on: prim.checked }); return d.error ? d : { msg: "Saved" }; })); + + return [status, devicesCard(S), primary, passphraseCard(S)]; + } + + function devicesCard(S) { + if (S.devices_error) return card("Devices", "server not reachable", el("p", { class: "st-note st-bad", text: S.devices_error })); + const boss = S.devices.find((d) => d.manager); + const rows = S.devices.map((d) => el("div", { class: "sy-dev" + (d.revoked ? " off" : "") }, + el("b", { text: d.name }), + el("span", { class: "st-note", text: [d.you ? "this dashboard" : null, d.manager ? "manages the devices" : null, + d.revoked ? "revoked" : "seen " + ago(d.last_seen)].filter(Boolean).join(" · ") }), + S.manager && !d.you && !d.revoked ? armed("Revoke", "Click again: its token stops working", async () => { + const r = await post("/api/sync/revoke", { name: d.name }); if (!r.error) loadSync(); return r; }) : null)); + const out = el("div"); + let add = null; + if (S.manager) { + const name = el("input", { value: S.devices.some((d) => d.name === "phone" && !d.revoked) ? "" : "phone", autocomplete: "off" }); + add = el("div", { class: "us-member" }, field("New device's name", name), + bar("Add a device", async () => { + const d = await post("/api/sync/add", { name: name.value }); + if (d.error) return d; + out.replaceChildren(pairCard(d)); + return { msg: "Added" }; + })); + } + return card("Devices", `${S.devices.filter((d) => !d.revoked).length} active`, ...rows, + S.manager ? add : note(boss ? `Only ${esc(boss.name)} (it set up the key) can add or revoke devices.` : ""), out); + } + + function pairCard(d) { + const link = el("input", { value: d.link, readonly: true }); + link.addEventListener("focus", () => link.select()); + return el("div", { class: "sy-pair" }, + d.qr ? el("img", { src: d.qr, alt: "QR code for the phone app", class: "sy-qr" }) + : note("No QR code here (sudo apt install python3-qrcode for one) — type these in the app instead:"), + note(`In the phone app: Connect ▸ Scan the code, then type the sync passphrase. ` + + `Shown only now — ${esc(d.name)}'s token isn't kept here.`), + field("Server", el("input", { value: d.server, readonly: true })), + field("Token", el("input", { value: d.token, readonly: true })), + field("Or this link", link)); + } + + function passphraseCard(S) { + const old = el("input", { type: "password", autocomplete: "off" }); + const rec = el("input", { autocomplete: "off", placeholder: "or the recovery key: ABCD-EFGH-…" }); + const p1 = el("input", { type: "password", autocomplete: "new-password" }); + const p2 = el("input", { type: "password", autocomplete: "new-password" }); + return card("Change the passphrase", null, + note("Devices already set up keep working; new ones join with the new passphrase." + + (S.manager ? "" : " Only the device that set up the key can change it.")), + field("Current passphrase", old), field("…or the recovery key", rec), + field("New passphrase", p1), field("New passphrase again", p2), + bar("Change", async () => { + if (p1.value !== p2.value) return { error: "The new passphrases differ." }; + const d = await post("/api/sync/passphrase", { old: old.value, recovery: rec.value, new: p1.value }); + if (!d.error) { [old, rec, p1, p2].forEach((i) => { i.value = ""; }); return { msg: "Changed" }; } + return d; + })); + } + + // ================================ System ================================ + async function loadSystem() { + let Y; + try { Y = await get("/api/system"); } catch (_) { sysRoot.replaceChildren(note("Could not load.")); return; } + sysRoot.replaceChildren(webCard(Y), screenCard(Y), backupCard(Y)); + } + + function webCard(Y) { + const all = el("input", { type: "radio", name: "sy-scope", checked: Y.host !== "127.0.0.1" }); + const local = el("input", { type: "radio", name: "sy-scope", checked: Y.host === "127.0.0.1" }); + const port = el("input", { type: "number", min: 1024, max: 65535, value: Y.port, inputmode: "numeric" }); + const hosts = el("input", { value: Y.hosts.join(", "), placeholder: "e.g. dash.home.arpa", autocomplete: "off" }); + return card("Web pages", `${Y.host}:${Y.port}`, + el("div", { class: "st-field" }, el("span", { text: "Who can open them" }), + el("label", { class: "st-check" }, all, "Everyone on the home network"), + el("label", { class: "st-check" }, local, "Only this computer (a dashboard on your own PC)")), + field("Port", port), + field("Other names it answers to (comma separated)", hosts, + "Against DNS rebinding the pages only answer to their own names. IP addresses always work."), + note(`Always work: its IP addresses, localhost, ${esc(Y.name)} and ${esc(Y.name)}.local. ` + + "A new port or “who” applies after a restart — then open the new address."), + bar("Save", async () => { + const d = await post("/api/system/web", { scope: local.checked ? "local" : "all", port: port.value, + hosts: hosts.value.split(",").map((h) => h.trim()).filter(Boolean) }); + if (d.error) return d; + if (d.restart) restartBanner(); + return { msg: d.restart ? "Saved — restart to apply" : "Saved" }; + })); + } + + function screenCard(Y) { + const pick = el("select", {}, + el("option", { value: "auto", text: "Find it (a small SPI screen; never this computer's own display)", selected: Y.fb === "auto" }), + el("option", { value: "none", text: "None — web pages only", selected: Y.fb === "none" }), + Y.fbs.map((f) => el("option", { value: f.dev, selected: Y.fb === f.dev, + text: `${f.dev} — ${f.name}, ${f.w}×${f.h}${f.small ? "" : " (a big display: its console gets drawn over)"}` }))); + const now = Y.fb_now ? `drawing on ${Y.fb_now}` : "no screen — web pages only"; + return card("Screen", Y.screen ? (Y.calibrated ? "touch calibrated" : "touch not calibrated") : "none", + note(`The small screen on the Pi (a 480×320 SPI panel: dtoverlay=piscreen in /boot/firmware/config.txt). Now: ${esc(now)}.`), + field("Draw on", pick), + bar("Save", async () => { + const d = await post("/api/system/screen", { fb: pick.value }); + if (d.error) return d; + restartBanner(); + return { msg: "Saved — restart to apply" }; + }, Y.screen ? [armed("Recalibrate touch", "Click again: restart and calibrate", () => post("/api/system/calibrate"))] : [])); + } + + function backupCard(Y) { + const file = el("input", { type: "file", accept: ".zip,application/zip" }); + const state = el("div"); + const pending = () => state.replaceChildren( + el("p", { class: "st-note", text: "A restore is waiting: it replaces the settings and all data at the next restart (what's here now is kept beside it)." }), + el("div", { class: "us-bar" }, + el("div", { class: "us-left" }, armed("Cancel the restore", "Click again to cancel", async () => { + const d = await post("/api/system/cancel-restore"); if (!d.error) state.replaceChildren(); return d; })), + armed("Restart and restore now", "Click again: restart now", () => post("/api/system/apply-restore")))); + if (Y.pending_restore) pending(); + return card("Backup", null, + note("Everything this dashboard keeps — settings, users, every plugin's data, the sync key — in one file. " + + "It holds your passwords: keep it like one. To move to a new Pi: install, then restore here (Settings ▸ General) on the new one."), + el("div", { class: "us-bar" }, el("a", { class: "st-btn", href: "/api/system/backup", text: "Download a backup" })), + field("Restore from a backup", file), + note("Moving to another computer? Switch the old dashboard off (or disconnect its sync) first — two copies with the same sync identity confuse each other."), + bar("Upload", async () => { + const f = file.files[0]; + if (!f) return { error: "Choose the backup file first." }; + let r; + try { r = await fetch("/api/system/restore", { method: "POST", headers: { "Content-Type": "application/zip" }, body: f }); } + catch (_) { return { error: "The upload failed." }; } + const d = await r.json().catch(() => ({ error: `Failed (${r.status}).` })); + if (d.error) return d; + pending(); + return { msg: `Backup from ${d.backup.host}, ${d.backup.made} — checked` }; + }), state); + } + + const esc = (s) => String(s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); + if (syncRoot) loadSync(); + if (sysRoot) loadSystem(); +})(); diff --git a/dashboard/static/users.js b/dashboard/static/users.js new file mode 100644 index 0000000..4140214 --- /dev/null +++ b/dashboard/static/users.js @@ -0,0 +1,147 @@ +// Settings ▸ Users (auth.py, web.api_users): the accounts and the household view (no login, +// read only). Fills #st-users from /api/users; every card saves on its own. No browser dialogs: +// Delete arms on the first click, deletes on the second. +(() => { + const root = document.getElementById("st-users"); + if (!root) return; + const el = (tag, attrs = {}, ...kids) => { + const e = document.createElement(tag); + for (const [k, v] of Object.entries(attrs)) { + if (k === "class") e.className = v; else if (k === "text") e.textContent = v; + else if (k.startsWith("on")) e.addEventListener(k.slice(2), v); else if (v !== false && v != null) e.setAttribute(k, v === true ? "" : v); + } + kids.flat().forEach((k) => k != null && e.append(k)); + return e; + }; + const post = async (what, body) => { + const r = await fetch("/api/users/" + what, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); + let d = {}; try { d = await r.json(); } catch (_) { d = { error: `Failed (${r.status}).` }; } + if (!r.ok && !d.error) d.error = `Failed (${r.status}).`; + return d; + }; + const ago = (t) => { + if (!t) return "never"; + const s = Date.now() / 1000 - t; + return s < 120 ? "just now" : s < 7200 ? `${Math.round(s / 60)} min ago` : s < 172800 ? `${Math.round(s / 3600)} h ago` : `${Math.round(s / 86400)} days ago`; + }; + let D = null; + + // ---- pieces: which plugins, which calendars ---- + function pluginPicks(chosen) { + const box = el("div", { class: "us-picks" }); + const tops = D.plugins.filter((p) => !p.host || !D.plugins.some((h) => h.name === p.host)); + const add = (p, sub) => box.append(el("label", { class: "st-check" + (sub ? " us-sub" : "") }, + el("input", { type: "checkbox", value: p.name, checked: chosen.includes(p.name) }), p.title)); + tops.forEach((p) => { add(p); D.plugins.filter((x) => x.host === p.name).forEach((x) => add(x, true)); }); + box.value = () => [...box.querySelectorAll("input:checked")].map((i) => i.value); + return box; + } + function calendarPicks(chosen) { // chosen null = all + const all = el("input", { type: "checkbox", checked: chosen === null }); + const list = el("div", { class: "us-picks us-cals" }, + D.calendars.map((c) => el("label", { class: "st-check" }, el("input", { type: "checkbox", value: c, checked: chosen === null || chosen.includes(c) }), c))); + const sync = () => list.querySelectorAll("input").forEach((i) => { i.disabled = all.checked; if (all.checked) i.checked = true; }); + all.addEventListener("change", sync); sync(); + const box = el("div", { class: "us-calbox" }, el("label", { class: "st-check", title: "Also every calendar added later" }, all, el("b", { text: "All calendars" })), list); + box.value = () => all.checked ? null : [...list.querySelectorAll("input:checked")].map((i) => i.value); + return box; + } + function bar(saveText, onSave, extra = []) { + const msg = el("span", { class: "st-msg" }); + const btn = el("button", { type: "button", class: "st-btn", text: saveText }); + btn.addEventListener("click", async () => { + btn.disabled = true; msg.textContent = ""; msg.classList.remove("bad"); + const d = await onSave(); + btn.disabled = false; + if (d.error) { msg.textContent = d.error; msg.classList.add("bad"); } else msg.textContent = "Saved"; + }); + return el("div", { class: "us-bar" }, el("div", { class: "us-left" }, extra), msg, btn); + } + + // ---- the first account ---- + function firstAdmin() { + const name = el("input", { autocomplete: "off", autocapitalize: "off" }); + const pw = el("input", { type: "password", autocomplete: "new-password" }); + const pw2 = el("input", { type: "password", autocomplete: "new-password" }); + const code = el("input", { autocomplete: "off", autocapitalize: "off", placeholder: "abcd-ef01-2345" }); + return el("section", { class: "st-card" }, + el("h2", { title: "Until it exists everyone sees everything. After it: without a login the household view (read only), logged in your own." }, "Create the admin account"), + el("label", { class: "us-f" }, "Name", name), + el("label", { class: "us-f" }, "Password (8+ characters)", pw), + el("label", { class: "us-f" }, "Password again", pw2), + el("label", { class: "us-f", title: "Printed when the dashboard starts: journalctl -u dashboard | grep 'setup code'" }, "Setup code (from the dashboard's log)", code), + bar("Create", async () => { + if (pw.value !== pw2.value) return { error: "The passwords differ." }; + const d = await post("save", { name: name.value, password: pw.value, role: "admin", setup: code.value }); + if (!d.error) location.reload(); + return d; + })); + } + + // ---- the household view ---- + function householdCard() { + const h = D.household; + const plugs = pluginPicks(h.plugins), cals = calendarPicks(h.calendars); + return el("section", { class: "st-card" }, + el("h2", { title: "What anyone sees without logging in — the wall screens (the 3.5\" one too). Read only: no new events, no changes." }, "Household view", el("small", { class: "st-status", text: "no login · read only" })), + el("div", { class: "us-two" }, el("div", {}, el("div", { class: "us-l", text: "Parts" }), plugs), el("div", {}, el("div", { class: "us-l", text: "Calendars" }), cals)), + bar("Save", () => post("household", { plugins: plugs.value(), calendars: cals.value() }))); + } + + // ---- one user (or a new one) ---- + function userCard(u) { + const isNew = !u; + u = u || { name: "", role: "member", plugins: ["weather", "stations", "calendar"], calendars: [], can_create: false }; + const me = u.id === D.me; + const name = el("input", { value: u.name, autocomplete: "off", autocapitalize: "off" }); + const role = el("select", {}, el("option", { value: "member", text: "Member — the parts and calendars below", selected: u.role !== "admin" }), + el("option", { value: "admin", text: "Admin — everything + Settings", selected: u.role === "admin", disabled: false })); + if (me) role.disabled = true; + const pw = el("input", { type: "password", autocomplete: "new-password", placeholder: isNew ? "" : "unchanged" }); + const create = el("input", { type: "checkbox", checked: !!u.can_create }); + const plugs = pluginPicks(u.plugins || []), cals = calendarPicks(u.calendars === undefined ? [] : u.calendars); + const memberPart = el("div", { class: "us-member" }, + el("label", { class: "st-check", title: "Only into the calendars ticked here that can take new events" }, create, "Can add events"), + el("div", { class: "us-two" }, el("div", {}, el("div", { class: "us-l", text: "Parts" }), plugs), el("div", {}, el("div", { class: "us-l", text: "Calendars" }), cals))); + const showMember = () => { memberPart.hidden = role.value === "admin"; }; + role.addEventListener("change", showMember); showMember(); + const extra = []; + if (!isNew) { + const out = el("button", { type: "button", class: "us-link", text: "Log out everywhere", title: `${u.sessions} signed-in device${u.sessions === 1 ? "" : "s"}` }); + out.addEventListener("click", async () => { await post("logout", { id: u.id }); if (me) location.href = "/login"; else load(); }); + extra.push(out); + if (!me) { + const del = el("button", { type: "button", class: "us-link us-del", text: "Delete" }); + del.addEventListener("click", async () => { + if (!del.classList.contains("armed")) { del.classList.add("armed"); del.textContent = "Click again to delete"; return; } + const d = await post("delete", { id: u.id }); + if (d.error) { del.textContent = d.error; } else load(); + }); + extra.push(del); + } + } + const card = el("section", { class: "st-card" + (isNew ? " us-new" : "") }, + el("h2", {}, isNew ? "New user" : u.name, isNew ? null : el("small", { class: "st-status", text: (u.role === "admin" ? "admin" : "member") + (me ? " · you" : "") + " · last seen " + ago(u.seen) })), + el("div", { class: "us-two" }, el("label", { class: "us-f" }, "Name", name), el("label", { class: "us-f" }, isNew ? "Password (8+ characters)" : "New password", pw)), + el("label", { class: "us-f" }, "Role", role), + memberPart, + bar(isNew ? "Add" : "Save", async () => { + const d = await post("save", { id: u.id, name: name.value, password: pw.value, role: role.value, + can_create: create.checked, plugins: plugs.value(), calendars: cals.value() }); + if (!d.error) load(); + return d; + }, extra)); + return card; + } + + async function load() { + try { D = await (await fetch("/api/users", { cache: "no-store" })).json(); } + catch (_) { root.replaceChildren(el("p", { class: "st-note", text: "Could not load the users." })); return; } + if (!D.active) { root.replaceChildren(firstAdmin()); return; } + // a box like the others: "+ Add user" turns into the new user's card + const add = el("button", { type: "button", class: "st-card us-add", text: "+ Add user" }); + add.addEventListener("click", () => { const c = userCard(null); add.replaceWith(c); c.querySelector("input")?.focus(); }); + root.replaceChildren(householdCard(), ...D.users.map(userCard), add); + } + load(); +})(); diff --git a/dashboard/store.py b/dashboard/store.py new file mode 100644 index 0000000..ce8dbe2 --- /dev/null +++ b/dashboard/store.py @@ -0,0 +1,115 @@ +"""Shared state. + +`Store` is the one object the renderers and workers all read/write. Two +free functions, `hit` and `dispatch_tap`, manage the per-frame list of +tappable regions — screens register hit-boxes while drawing, the input +loop later asks which one was tapped. + +`TempSource` is one slot in the temperature/humidity strip. Live values +arrive from the stations plugin (plugins/stations/sensors.py polls termix); +the rolling 24 h history is a deque of (unix_ts, °C) pairs. +""" +import threading +import time +from collections import deque + +from config import save_config + +POLL_INTERVAL_S = 30 +HISTORY_HOURS = 24 +HISTORY_MAXLEN = HISTORY_HOURS * 3600 // POLL_INTERVAL_S # 2880 points at 30 s + + +class TempSource: + """Live sensor: latest temp/humidity + a 24 h rolling history of (ts, °C).""" + def __init__(self, device_id=None, name=""): + self.device_id = device_id + self.name = name or (f"#{device_id}" if device_id is not None else "") + self.t = None + self.h = None + self.age_s = None + self.hist = deque(maxlen=HISTORY_MAXLEN) + + def update(self, name, t, h, age_s): + if name: + self.name = name + self.t = t + self.h = h + self.age_s = age_s + if t is not None: + self.hist.append((time.time(), t)) + + +class Store: + def __init__(self, cfg): + self.cfg = cfg + self.units = cfg.get("units", "metric") + self.brightness = 1.0 # live value, recomputed each frame by backlight.compute + self.screen = 0 + self.temp_tab = -1 # -1 = grid landing; 0..len-1 = detail view of that sensor + self.cal_page = 0 # Calendar screen page (0-based); cal_pages set by the renderer + self.cal_pages = 1 + self.hits = [] # tappable regions for the current frame + self.last_activity_t = time.monotonic() # for idle-return-to-Home (see dash.main) + + # the sensors (filled by the stations plugin from Settings ▸ Sensors) + self.sources = [] + self.outdoor = [] # outdoor readings next to the weather on the web Home (max 3) + self.main = None # the big temperature on Home: one of sources / outdoor (Settings ▸ Sensors) + self.sensors_status = "loading…" + + self.wx_current = None + self.om = None # Open-Meteo forecast (web weather page), see weather.openmeteo_worker + self.om_air = None # Open-Meteo air quality + self.om_status = "—" + self.wx_forecast = [] + self.wx_status = "loading…" + self.cal_events = [] + self.cal_window = None # (start, end) the expanded cal_events cover + self.cal_sources = [] # [(meta, parsed calendar)] — all history, see cal.events_between + self.cal_version = 0 # bumped when cal_sources change + self.cal_targets = [] # calendars a new event can go to (cal.CalendarSync.targets) + self.cal_collections = [] # every calendar found, for Settings (cal.CalendarSync.collections) + self.cal_synced = 0.0 # time of the last good sync (Settings: reload) + self.cal_status = "—" + self.lock = threading.Lock() + self.wake = threading.Event() + self.cal_wake = threading.Event() + self.om_wake = threading.Event() # Open-Meteo worker: refetch now (settings changed) + self.cal_reset = False # settings changed: rebuild the calendar sync + self.restart_needed = False # settings saved that only apply after a restart (termix) + + def toggle_units(self): + self.set_units("imperial" if self.units == "metric" else "metric") + + def set_units(self, val): + if val not in ("metric", "imperial"): + return + self.units = val + self.cfg["units"] = val + try: + save_config(self.cfg) + except Exception: + pass + + +def goto_screen(store, idx, screens=None): + """Switch to screen `idx` of `screens` (screens.screen_list) and run its on_open (the + Temp screen opens on its grid, the Calendar on page 1).""" + store.screen = idx + sc = screens[idx] if screens and 0 <= idx < len(screens) else None + if sc and sc.get("open"): + sc["open"]() + + +def hit(store, box, fn): + """Register a tappable region (x0,y0,x1,y1) -> fn() for the current frame.""" + store.hits.append((box[0], box[1], box[2], box[3], fn)) + + +def dispatch_tap(store, x, y): + for x0, y0, x1, y1, fn in store.hits: + if x0 <= x <= x1 and y0 <= y <= y1: + fn() + return True + return False diff --git a/dashboard/sync.py b/dashboard/sync.py new file mode 100644 index 0000000..163d863 --- /dev/null +++ b/dashboard/sync.py @@ -0,0 +1,622 @@ +"""Sync between the dashboard and other devices (the phone app) through a mailbox server +(dash-sync-server: stores encrypted batches it can't read). Each device keeps its own copy of +the data; syncdb.py stamps every change in the plugins' databases, this sends this device's +changes and applies everyone else's — the last change of a row wins. + + python3 sync.py setup [] the first device: makes the data key, + asks for a passphrase, prints the recovery key + python3 sync.py join [] another device: unlocks the key with the passphrase + (no token on the line: it's asked for, not echoed) + python3 sync.py now push + pull once + python3 sync.py status + python3 sync.py passphrase a new passphrase (needs the old one or the recovery key) + +Encryption (libsodium, PyNaCl): one random 32-byte data key; each batch = zlib(JSON) sealed with +XChaCha20-Poly1305 (24-byte random nonce, the account in the additional data). The server keeps +the data key only wrapped with a key made from the passphrase (Argon2id), so a new device can +join with the passphrase; the recovery key (the data key itself, base32) replaces a forgotten +passphrase. See dash-sync-server/PROTOCOL.md — the app speaks the same. + +State: dash_data/sync/state.json (chmod 600): this device's id, and once set up the server, +token, data key and how far it has read. Without it the databases are still stamped (sync-ready), +nothing is sent. +""" +import base64 +import getpass +import hashlib +import importlib +import json +import os +import sys +import threading +import time +import traceback +import urllib.error +import urllib.request +import zlib + +import syncdb + +HERE = os.path.dirname(os.path.abspath(__file__)) +DATA = os.path.join(HERE, "dash_data") +STATE = os.path.join(DATA, "sync", "state.json") +INTERVAL = 300 # s between syncs +CHUNK = 2000 # changes per batch +MAGIC = b"DS1\x00" +KEY_AD = b"dash-sync/key/1" +CHECK_AD = b"dash-sync/key-check/1" # "check" in the wrapped key: proves a recovery key without the passphrase +OPS, MEM = 3, 64 * 1024 * 1024 # Argon2id: fine on a Pi 3 (≈ 1 s) and a phone + +status = {"last": None, "error": None, "result": None} +_lock = threading.Lock() +kick_hooks = [] # plugins' steps after a kick's pull (ctx.on_sync) +KICK_EVERY = 60 # s: at most one kick a minute +KICK_AGE = 120 # s a kick message stays valid +_kick = {"t": 0, "made": 0} + + +# ---- state ------------------------------------------------------------------------------------ + +def load_state(): + try: + with open(STATE) as f: + st = json.load(f) + except (OSError, ValueError): + st = {} + if not st.get("device"): + st["device"] = syncdb.device_id() + save_state(st) + return st + + +def save_state(st): + os.makedirs(os.path.dirname(STATE), exist_ok=True) + tmp = STATE + ".tmp" + with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), "w") as f: + json.dump(st, f, indent=1) + os.replace(tmp, STATE) + + +def configured(st=None): + st = st or load_state() + return bool(st.get("server") and st.get("token") and st.get("key")) + + +# ---- what syncs (the plugins' META["sync"]) ---------------------------------------------------- + +def specs(): + """[(plugin, db path, tables)] — from the loaded plugins, or (command line) their modules.""" + import pluginhost + metas = {n: p.meta for n, p in pluginhost._plugins.items() if not p.error} + if not metas: + for n in pluginhost.discover(): + try: + metas[n] = getattr(importlib.import_module(f"plugins.{n}"), "META", {}) + except Exception: + continue + out = [] + for name, meta in metas.items(): + for fname, tables in (meta.get("sync") or {}).items(): + out.append((name, os.path.join(DATA, name, fname), tables)) + return out + + +_prepared = set() # the database files stamped since start (prepare_all / push) + + +def _prepare(name, path, tables, dev): + try: + syncdb.prepare(path, tables, dev) + _prepared.add(path) + except Exception: + print(f"sync: preparing {name}: {traceback.format_exc()}", flush=True) + + +def prepare_all(): + """Stamp the plugins' databases (at start-up, whether sync is set up or not).""" + dev = load_state()["device"] + for name, path, tables in specs(): + if os.path.exists(path): # made on first use: stamped by the first push after that + _prepare(name, path, tables, dev) + + +# ---- crypto ----------------------------------------------------------------------------------- + +def _nacl(): + try: + from nacl import bindings, pwhash, utils + except ImportError: + sys.exit("sync needs PyNaCl: sudo apt install python3-nacl") + return bindings, pwhash, utils + + +def seal(key, data, ad): + b, _, u = _nacl() + nonce = u.random(24) + return MAGIC + nonce + b.crypto_aead_xchacha20poly1305_ietf_encrypt(data, ad, nonce, key) + + +def unseal(key, blob, ad): + b, _, _ = _nacl() + if blob[:4] != MAGIC: + raise ValueError("not a sync batch") + return b.crypto_aead_xchacha20poly1305_ietf_decrypt(blob[28:], ad, blob[4:28], key) + + +def wrap(key, passphrase): + b, pw, u = _nacl() + salt = u.random(16) + kek = pw.argon2id.kdf(32, passphrase.encode(), salt, opslimit=OPS, memlimit=MEM) + nonce = u.random(24) + box = b.crypto_aead_xchacha20poly1305_ietf_encrypt(key, KEY_AD, nonce, kek) + e = lambda x: base64.b64encode(x).decode() + return {"v": 1, "kdf": "argon2id13", "ops": OPS, "mem": MEM, "salt": e(salt), "nonce": e(nonce), "box": e(box), + "check": e(seal(key, b"ok", CHECK_AD))} + + +def unwrap(w, passphrase): + b, pw, _ = _nacl() + d = lambda x: base64.b64decode(x) + kek = pw.argon2id.kdf(32, passphrase.encode(), d(w["salt"]), opslimit=w["ops"], memlimit=w["mem"]) + try: + return b.crypto_aead_xchacha20poly1305_ietf_decrypt(d(w["box"]), KEY_AD, d(w["nonce"]), kek) + except Exception: + raise ValueError("wrong passphrase") + + +def recovery_code(key): + s = base64.b32encode(key).decode().rstrip("=") + return "-".join(s[i:i + 4] for i in range(0, len(s), 4)) + + +def from_recovery(code): + s = code.replace("-", "").replace(" ", "").upper() + key = base64.b32decode(s + "=" * (-len(s) % 8)) + if len(key) != 32: + raise ValueError("that's not a recovery key") + return key + + +def _ad(st): + return f"dash-sync/1/{st['account']}".encode() + + +# ---- the server ------------------------------------------------------------------------------- + +def call(st, method, path, body=None, raw=False): + url = st["server"].rstrip("/") + path + data, headers = None, {"Authorization": "Bearer " + st["token"], "Accept": "application/json"} + if isinstance(body, bytes): + data, headers["Content-Type"] = body, "application/octet-stream" + elif body is not None: + data, headers["Content-Type"] = json.dumps(body).encode(), "application/json" + req = urllib.request.Request(url, data=data, method=method, headers=headers) + try: + with urllib.request.urlopen(req, timeout=60) as r: + out = r.read() + except urllib.error.HTTPError as e: + msg = e.read().decode(errors="replace") + try: + msg = json.loads(msg).get("error", msg) + except ValueError: + pass + raise RuntimeError(f"server: {e.code} {msg}") from None + return out if raw else json.loads(out or b"{}") + + +# ---- push / pull ------------------------------------------------------------------------------ + +def push(st): + """This device's changes → batches. Marked as sent only after every batch of a file is in.""" + sent = 0 + for name, path, tables in specs(): + if not os.path.exists(path): + continue + if path not in _prepared: # a plugin made it since start: its rows so far get stamped now + _prepare(name, path, tables, st["device"]) + items, mark = syncdb.changes(path, tables, name) + for i in range(0, len(items), CHUNK): + part = items[i:i + CHUNK] + plain = zlib.compress(json.dumps({"v": 1, "dev": st["device"], "made": int(time.time() * 1000), + "changes": part}, separators=(",", ":")).encode(), 6) + call(st, "POST", "/v1/batches", seal(st["key_bytes"], plain, _ad(st))) + sent += len(part) + if items: + syncdb.mark_pushed(path, mark) + return sent + + +def pull(st): + """Everyone else's batches since the last pull, applied in order. A synced file that's new here + and empty (a plugin installed after the phone already wrote to it) reads from the start, once — + else the batches before it would be passed by for good. state: "files" = the files seen at the + last pull, "behind" = {file: seq} for those still catching up (the rest are at "pulled").""" + got = {"batches": 0, "applied": 0, "skipped": 0, "failed": 0} + sp = [(name, path, tables) for name, path, tables in specs() if os.path.exists(path)] + for name, path, tables in sp: + if path not in _prepared: # made since start: columns + triggers before anything lands + _prepare(name, path, tables, st["device"]) + rel = lambda p: os.path.relpath(p, DATA) + pulled, known, behind = st.get("pulled", 0), st.get("files"), dict(st.get("behind") or {}) + for _, path, tables in sp: + if pulled and (known is None or rel(path) not in known) and rel(path) not in behind \ + and syncdb.is_empty(path, tables): + behind[rel(path)] = 0 + st["files"] = [rel(p) for _, p, _ in sp] + at = {path: behind.get(rel(path), pulled) for _, path, _ in sp} + after = min([*at.values(), pulled]) + if after < pulled: + print(f"sync: reading from {after} again for {', '.join(rel(p) for p, s in at.items() if s < pulled)}", flush=True) + while True: + j = call(st, "GET", f"/v1/batches?after={after}&limit=50") + if not j["batches"]: + break + for b in j["batches"]: + late = [(n, p, t) for n, p, t in sp if at[p] < b["seq"]] + if b["device"] != st["device_name"] and late: + batch = json.loads(zlib.decompress(unseal(st["key_bytes"], base64.b64decode(b["blob"]), _ad(st)))) + if batch.get("dev") != st["device"]: + for name, path, tables in late: + for k, v in syncdb.apply(path, tables, name, batch["changes"]).items(): + got[k] += v + if b["seq"] > st.get("pulled", 0): + got["batches"] += 1 + for _, path, _ in late: + at[path] = b["seq"] + after = b["seq"] + st["pulled"] = max(st.get("pulled", 0), b["seq"]) + st["behind"] = {rel(p): s for p, s in at.items() if s < st["pulled"]} + save_state({k: v for k, v in st.items() if k != "key_bytes"}) + st["behind"] = {rel(p): s for p, s in at.items() if s < st.get("pulled", 0)} + save_state({k: v for k, v in st.items() if k != "key_bytes"}) + return got + + +def sync_now(): + with _lock: + st = load_state() + if not configured(st): + raise RuntimeError("sync isn't set up (python3 sync.py setup …)") + st["key_bytes"] = base64.b64decode(st["key"]) + res = {"pulled": pull(st), "pushed": push(st)} + status.update(last=time.time(), error=None, result=res) + return res + + +def kick(blob): + """The phone app's "sync now" over the LAN (POST /api/sync/kick, right after it sent something): + pull, let the plugins work on what came (the band relay → import → summaries), push their + results — so the app gets them at its next pull instead of in 5-15 minutes. blob = a batch + sealed with the data key ({"kick": ms}) — only a device that has the key can send one; it must + be fresh and newer than the last. → (http status, answer).""" + st = load_state() + if not configured(st): + return 409, {"error": "sync isn't set up"} + try: + msg = json.loads(zlib.decompress(unseal(base64.b64decode(st["key"]), blob, _ad(st)))) + made = int(msg["kick"]) + except Exception: + return 403, {"error": "not a kick"} + now = time.time() + if abs(now * 1000 - made) > KICK_AGE * 1000 or made <= _kick["made"]: + return 403, {"error": "stale kick"} + if now - _kick["t"] < KICK_EVERY: + return 429, {"error": "kicked a moment ago"} + _kick.update(t=now, made=made) + res = sync_now() + wrote = False + for fn in kick_hooks: + try: + wrote = bool(fn()) or wrote + except Exception as e: + print(f"sync: kick step failed: {e}", flush=True) + if wrote: + res["pushed"] += sync_now()["pushed"] + print(f"sync: kick {res}, {round(time.time() - now, 1)} s", flush=True) + return 200, {"ok": True, "pushed": res["pushed"]} + + +# ---- the phone app's newest build, mirrored for the home network (web /app) ------------------- +# The app updates itself from the server (dash-app lib/app/updater.dart); this copy is for a first install / +# a phone that can't update itself yet: http://:8080/app. Only the primary dashboard keeps one. +APP_DIR = os.path.join(DATA, "app") +APP_EVERY = 3600 # s between looks at the server's app.json + + +def app_info(): + """The mirrored build's app.json (+ "file"), or None.""" + try: + with open(os.path.join(APP_DIR, "app.json")) as f: + info = json.load(f) + except (OSError, ValueError): + return None + apk = os.path.join(APP_DIR, "dash-app.apk") + return dict(info, file=apk) if os.path.exists(apk) and os.path.getsize(apk) == info.get("size") else None + + +def app_mirror(): + """Fetch a newer build than the one here (checksum checked) → its app.json, or None (nothing new).""" + st = load_state() + if not configured(st): + return None + try: + info = call(st, "GET", "/v1/app") + except RuntimeError as e: + if "404" in str(e): + return None + raise + have = app_info() + if have and have.get("build") == info.get("build"): + return None + os.makedirs(APP_DIR, exist_ok=True) + part = os.path.join(APP_DIR, "dash-app.apk.part") + req = urllib.request.Request(st["server"].rstrip("/") + "/v1/app/apk", headers={"Authorization": "Bearer " + st["token"]}) + h = hashlib.sha256() + with urllib.request.urlopen(req, timeout=120) as r, open(part, "wb") as f: + while chunk := r.read(1 << 16): + f.write(chunk) + h.update(chunk) + if os.path.getsize(part) != info.get("size") or h.hexdigest() != info.get("sha256"): + os.remove(part) + raise RuntimeError("the app download didn't check out") + os.replace(part, os.path.join(APP_DIR, "dash-app.apk")) + with open(os.path.join(APP_DIR, "app.json.tmp"), "w") as f: + json.dump(info, f) + os.replace(os.path.join(APP_DIR, "app.json.tmp"), os.path.join(APP_DIR, "app.json")) + return info + + +def worker(store=None): + time.sleep(30) + mirrored = 0 + while True: + if configured(): + try: + sync_now() + except Exception as e: + status.update(last=time.time(), error=str(e)) + print(f"sync: {e}", flush=True) + primary = ((store.cfg.get("sync") or {}).get("primary", True)) if store is not None else True + if primary and time.time() - mirrored > APP_EVERY: + mirrored = time.time() + try: + got = app_mirror() + if got: + print(f"sync: app {got.get('version')} ({got.get('build')}) mirrored for /app", flush=True) + except Exception as e: + print(f"sync: app mirror: {e}", flush=True) + time.sleep(INTERVAL) + + +_booted = False + + +def boot(store=None): + """At start-up (pluginhost.load): stamp the databases, start the worker.""" + global _booted + if _booted: + return + _booted = True + prepare_all() + threading.Thread(target=worker, args=(store,), daemon=True, name="sync").start() + + +# ---- setting up (the command line below and Settings ▸ General ▸ Sync, web.py) ---------------------------- + +PASS_MIN = 10 + + +def _connect(url, token): + st = load_state() + st.update(server=url.strip().rstrip("/"), token=token.strip()) + hello = call(st, "GET", "/v1/hello") + st.update(account=hello["account"], device_name=hello["device"]) + return st + + +def probe(url, token): + """Is the token good, and does the account have a data key yet? → {account, device, has_key}.""" + st = _connect(url, token) + try: + call(st, "GET", "/v1/key") + has = True + except RuntimeError as e: + if "404" not in str(e): + raise + has = False + return {"account": st["account"], "device": st["device_name"], "has_key": has} + + +def connect(url, token, passphrase=None, recovery=None): + """Join this dashboard to the sync account. The account's first device makes the data key (wrapped with + `passphrase`) and gets the recovery key back; the others unlock it with the passphrase or the recovery + key. → {"recovery": code or None, "account", "device"} (raises ValueError / RuntimeError).""" + if configured(): + raise ValueError("This dashboard is set up already — disconnect it first.") + st = _connect(url, token) + try: + w = call(st, "GET", "/v1/key") + except RuntimeError as e: + if "404" not in str(e): + raise + w = None + code = None + if w is None: + if len(passphrase or "") < PASS_MIN: + raise ValueError(f"The passphrase needs at least {PASS_MIN} characters.") + _, _, u = _nacl() + key = u.random(32) + call(st, "PUT", "/v1/key", wrap(key, passphrase)) + code = recovery_code(key) + elif recovery: + key = from_recovery(recovery) + if not recovery_fits(st, w, key): + raise ValueError("That recovery key doesn't open this account's data.") + else: + key = unwrap(w, passphrase or "") + st["key"] = base64.b64encode(key).decode() + st.setdefault("pulled", 0) + save_state(st) + prepare_all() + return {"recovery": code, "account": st["account"], "device": st["device_name"]} + + +def recovery_fits(st, w, key): + """Does this key open the account? The wrapped key's "check" says; keys wrapped before it existed: the first + batch (none yet = can't tell, accepted).""" + try: + if w.get("check"): + unseal(key, base64.b64decode(w["check"]), CHECK_AD) + return True + first = call(st, "GET", "/v1/batches?after=0&limit=1").get("batches") or [] + if first: + unseal(key, base64.b64decode(first[0]["blob"]), _ad(st)) + return True + except Exception: # a wrong key fails to open it (nacl's CryptoError) + return False + + +def new_passphrase(new, old=None, recovery=None): + """A new passphrase for the account's key (needs the old one or the recovery key).""" + st = load_state() + if not configured(st): + raise ValueError("Sync isn't set up.") + if len(new or "") < PASS_MIN: + raise ValueError(f"The passphrase needs at least {PASS_MIN} characters.") + key = from_recovery(recovery) if recovery else unwrap(call(st, "GET", "/v1/key"), old or "") + if key != base64.b64decode(st["key"]): + raise ValueError("That doesn't match this dashboard's key.") + call(st, "PUT", "/v1/key?replace=1", wrap(key, new)) + + +def disconnect(): + """Forget the server, token and key here (the data and its stamps stay; joining again resumes).""" + with _lock: + st = load_state() + for k in ("server", "token", "key", "account", "device_name", "pulled", "files", "behind"): + st.pop(k, None) + save_state(st) + status.update(last=None, error=None, result=None) + + +def devices(): + """The account's devices from the server ([{name, created, last_seen, revoked, you, manager}]) and + whether this one may add / revoke (the one that made the key).""" + j = call(load_state(), "GET", "/v1/devices") + return j.get("devices") or [], bool(j.get("manager")) + + +def add_device(name): + """A new device token (only the managing device may) → {name, token, server}.""" + st = load_state() + j = call(st, "POST", "/v1/devices", {"name": name}) + return {"name": j["name"], "token": j["token"], "server": st["server"]} + + +def revoke_device(name): + call(load_state(), "POST", "/v1/devices/revoke", {"name": name}) + + +def pair_link(server, token): + """What the app's connect screen scans: dashpi://connect?server=…&token=… (no passphrase in it).""" + from urllib.parse import urlencode + return "dashpi://connect?" + urlencode({"server": server, "token": token}) + + +def qr_png(text): + """A PNG of the QR code (python3-qrcode), or None without it.""" + try: + import io + import qrcode + except ImportError: + return None + img = qrcode.make(text, box_size=8, border=2) + buf = io.BytesIO() + img.save(buf, format="PNG") + return buf.getvalue() + + +def view(): + """Settings ▸ General ▸ Sync: where things stand (no secrets).""" + st = load_state() + on = configured(st) + return {"configured": on, "server": st.get("server"), "account": st.get("account"), + "device": st.get("device_name"), "pulled": st.get("pulled"), "last": status["last"], + "error": status["error"], "result": status["result"], "nacl": _have_nacl(), "qr": _have_qr()} + + +def _have_nacl(): + try: + import nacl # noqa: F401 + return True + except ImportError: + return False + + +def _have_qr(): + try: + import qrcode # noqa: F401 + return True + except ImportError: + return False + + +# ---- command line ----------------------------------------------------------------------------- + + +def _ask_new_passphrase(): + while True: + p = getpass.getpass("New sync passphrase (at least 10 characters): ") + if len(p) < 10: + print("Too short.") + elif p != getpass.getpass("Again: "): + print("They don't match.") + else: + return p + + +def main(argv): + if len(argv) < 2 or argv[1] not in ("setup", "join", "now", "status", "passphrase"): + sys.exit(__doc__) + cmd = argv[1] + if cmd in ("setup", "join"): + if len(argv) not in (3, 4): + sys.exit(f"python3 sync.py {cmd} []") + token = argv[3] if len(argv) == 4 else getpass.getpass("Device token: ").strip() # left out: asked, not echoed + has = probe(argv[2], token)["has_key"] + if cmd == "setup" and has: + sys.exit("This account already has a data key — use: python3 sync.py join …") + if cmd == "join" and not has: + sys.exit("No data key on the server yet — set up the first device with: python3 sync.py setup …") + try: + res = connect(argv[2], token, _ask_new_passphrase() if cmd == "setup" else getpass.getpass("Sync passphrase: ")) + except ValueError as e: + sys.exit(str(e)) + if res["recovery"]: + print("\nRecovery key — write it down and keep it somewhere safe. With it you can set a new\n" + "passphrase if you forget yours; without both, the synced data can't be read:\n\n " + + res["recovery"] + "\n") + print(f"Set up as “{res['device']}” (account {res['account']}). Syncing…") + print(json.dumps(sync_now(), indent=1)) + elif cmd == "now": + prepare_all() + print(json.dumps(sync_now(), indent=1)) + elif cmd == "status": + st = load_state() + print(json.dumps({"device": st["device"], "configured": configured(st), "server": st.get("server"), + "account": st.get("account"), "name": st.get("device_name"), "pulled": st.get("pulled")}, indent=1)) + if configured(st): + print(json.dumps(call(st, "GET", "/v1/hello"), indent=1)) + elif cmd == "passphrase": + how = input("Old passphrase (p) or recovery key (r)? ").strip().lower() + rec = input("Recovery key: ") if how == "r" else None + old = None if rec else getpass.getpass("Old passphrase: ") + try: + new_passphrase(_ask_new_passphrase(), old=old, recovery=rec) + except ValueError as e: + sys.exit(str(e)) + print("New passphrase set. Devices already set up keep working; new ones join with the new one.") + + +if __name__ == "__main__": + main(sys.argv) diff --git a/dashboard/syncdb.py b/dashboard/syncdb.py new file mode 100644 index 0000000..882bb53 --- /dev/null +++ b/dashboard/syncdb.py @@ -0,0 +1,342 @@ +"""Sync groundwork in the plugins' SQLite files: every synced row gets an id no other device +will make (`_uid`), a change stamp (`_hlc`) and the device that made the change (`_dev`); deletes +leave a marker (`_sync_tomb`). SQLite triggers keep them up to date, so plugin code writes its +tables as before. sync.py moves the changes between devices (encrypted, through the server). + +A plugin says what syncs in its META: + + "sync": {"food.db": { # file under dash_data// + "food": {"refs_in": {"recipe": "my:"}}, # "my:12" inside that text = food 12 + "entry": {"key": "'src:' || NEW.src_id", # natural id (SQL on NEW), else random + "refs": {"my_food_id": "food"}}, # integer column → a row of that table + }} + +Tables are applied in the order given (a table before the ones pointing at it). +- key: SQL on NEW giving a stable id when the row has a natural one (a day, an import's id) — two + devices making "the same" row then agree on it, and INSERT OR REPLACE keeps its identity. NULL + from it = a random id. A row whose key changes (a measurement moved to another day) becomes a + delete of the old id + the new one. +- refs: integer foreign keys, sent as the target's _uid and turned back into the local id. +- refs_in: text columns holding "" (JSON) — sent as "~". +- fork: [columns] — rows are documents (notes): those columns are a version of the text, named by + `rev` (new at every edit) with `revs` (the last ones, space-separated, newest last) beside it. + A change written on top of the other side's version wins its text whatever the stamps say (the + other columns — pinned, folder — still go by the stamp); two versions written at the same time: + the later one wins, the other is kept as a row of its own, `_uid` "copy:", `origin` = + that rev — every device makes the same copy, so they agree without sending it. + +_hlc is milliseconds since 1970, but never smaller than the last stamp + 1 (and pushed past what +arrives from other devices), so stamps keep their order even with a clock that's off. Ties: the +higher _dev wins. Changes applied from elsewhere keep their stamp and device (the triggers stand +aside while `applying` is 1 — set inside the applying transaction only). +""" +import json +import re +import sqlite3 +import uuid + +NOW_MS = "CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)" +META_SQL = """ +CREATE TABLE IF NOT EXISTS _sync_meta (k TEXT PRIMARY KEY, v); +CREATE TABLE IF NOT EXISTS _sync_tomb (tbl TEXT NOT NULL, uid TEXT NOT NULL, hlc INTEGER NOT NULL, dev TEXT NOT NULL, + PRIMARY KEY (tbl, uid)); +""" +CLOCK = "(SELECT v FROM _sync_meta WHERE k = 'clock')" +DEV = "(SELECT v FROM _sync_meta WHERE k = 'dev')" +QUIET = "(SELECT v FROM _sync_meta WHERE k = 'applying') = 0" +BUMP = f"UPDATE _sync_meta SET v = max(v + 1, {NOW_MS}) WHERE k = 'clock';" +RANDOM = "lower(hex(randomblob(16)))" + + +def connect(path): + con = sqlite3.connect(path, timeout=30) + con.row_factory = sqlite3.Row + return con + + +def _cols(con, t): + return [r["name"] for r in con.execute(f"PRAGMA table_info({t})")] + + +def _alias(con, t): + """The INTEGER PRIMARY KEY column (= the rowid, local only), or None.""" + pk = [r for r in con.execute(f"PRAGMA table_info({t})") if r["pk"]] + return pk[0]["name"] if len(pk) == 1 and pk[0]["type"].upper() == "INTEGER" else None + + +def prepare(path, tables, dev): + """Columns, markers, triggers — idempotent, at every start. Rows from before get their ids + and a stamp now (so a first sync sends them).""" + con = connect(path) + try: + con.executescript(META_SQL) + con.execute("INSERT OR IGNORE INTO _sync_meta VALUES ('clock', 0), ('applying', 0), ('pushed', 0)") + con.execute("INSERT OR REPLACE INTO _sync_meta VALUES ('dev', ?)", (dev,)) + con.execute("UPDATE _sync_meta SET v = 0 WHERE k = 'applying'") # a crash mid-apply + for t, spec in tables.items(): + have = _cols(con, t) + if not have: + continue # not created yet (the plugin makes it on first use) + for c, typ in (("_uid", "TEXT"), ("_hlc", "INTEGER"), ("_dev", "TEXT")): + if c not in have: + con.execute(f"ALTER TABLE {t} ADD COLUMN {c} {typ}") + con.execute(f"CREATE INDEX IF NOT EXISTS _sync_{t}_uid ON {t} (_uid)") + con.execute(f"CREATE INDEX IF NOT EXISTS _sync_{t}_hlc ON {t} (_hlc)") + key = spec.get("key") + new_uid = f"coalesce({key}, {RANDOM})" if key else RANDOM + for trig in ("i", "u", "d"): + con.execute(f"DROP TRIGGER IF EXISTS _sync_{t}_{trig}") + # rows from before the triggers: their ids + a stamp (NEW. → the row itself) + if con.execute(f"SELECT 1 FROM {t} WHERE _uid IS NULL LIMIT 1").fetchone(): + con.execute(BUMP) + con.execute(f"UPDATE {t} SET _uid = {new_uid.replace('NEW.', '')}, _hlc = {CLOCK}, _dev = {DEV} " + "WHERE _uid IS NULL") + con.executescript(f""" +CREATE TRIGGER _sync_{t}_i AFTER INSERT ON {t} WHEN {QUIET} BEGIN + {BUMP} + UPDATE {t} SET _uid = coalesce(NEW._uid, {new_uid}), _hlc = {CLOCK}, _dev = {DEV} WHERE rowid = NEW.rowid; +END; +CREATE TRIGGER _sync_{t}_u AFTER UPDATE ON {t} WHEN {QUIET} AND OLD._uid IS NOT NULL AND NEW._hlc IS OLD._hlc BEGIN + {BUMP} + {f'''INSERT OR REPLACE INTO _sync_tomb SELECT '{t}', OLD._uid, {CLOCK}, {DEV} WHERE ({key}) IS NOT NULL AND ({key}) IS NOT OLD._uid; + UPDATE {t} SET _uid = coalesce({key}, OLD._uid) WHERE rowid = NEW.rowid;''' if key else ''} + UPDATE {t} SET _hlc = {CLOCK}, _dev = {DEV} WHERE rowid = NEW.rowid; +END; +CREATE TRIGGER _sync_{t}_d AFTER DELETE ON {t} WHEN {QUIET} AND OLD._uid IS NOT NULL BEGIN + {BUMP} + INSERT OR REPLACE INTO _sync_tomb VALUES ('{t}', OLD._uid, {CLOCK}, {DEV}); +END;""") + con.commit() + finally: + con.close() + + +def _meta(con, k): + r = con.execute("SELECT v FROM _sync_meta WHERE k = ?", (k,)).fetchone() + return r[0] if r else None + + +def _uid_of(con, t, rowid): + if rowid is None: + return None + r = con.execute(f"SELECT _uid FROM {t} WHERE rowid = ?", (rowid,)).fetchone() + return r[0] if r else None + + +def _id_of(con, t, uid): + if uid is None: + return None + r = con.execute(f"SELECT rowid FROM {t} WHERE _uid = ?", (uid,)).fetchone() + return r[0] if r else None + + +def _refs_out(con, text, prefix, t): + if not text: + return text + return re.sub(re.escape(prefix) + r"(\d+)\b", + lambda m: prefix + "~" + (_uid_of(con, t, int(m.group(1))) or "gone"), text) + + +def _refs_back(con, text, prefix, t): + """→ (text with local ids, how many weren't found).""" + if not text: + return text, 0 + missing = 0 + def back(m): + nonlocal missing + i = _id_of(con, t, m.group(1)) + if i is None and m.group(1) != "gone": + missing += 1 + return prefix + str(i if i is not None else 0) # 0 = not here (any more): reads as gone + return re.sub(re.escape(prefix) + r"~([0-9a-z]+)", back, text), missing + + +def changes(path, tables, name): + """This device's changes since the last push: ([change], mark). Tables are named + "." in the changes ("food.entry"); call mark_pushed(path, mark) once sent.""" + con = connect(path) + try: + dev, since = _meta(con, "dev"), _meta(con, "pushed") or 0 + mark, out = since, [] + for t, spec in tables.items(): + cols = _cols(con, t) + if not cols: + continue + alias = _alias(con, t) + keep = [c for c in cols if c not in (alias, "_uid", "_hlc", "_dev")] + for r in con.execute(f"SELECT * FROM {t} WHERE _dev = ? AND _hlc > ? ORDER BY _hlc", (dev, since)): + row = {c: r[c] for c in keep} + for c, ref in spec.get("refs", {}).items(): + row[c] = _uid_of(con, ref, row[c]) + for c, prefix in spec.get("refs_in", {}).items(): + row[c] = _refs_out(con, row[c], prefix, t) + out.append({"t": f"{name}.{t}", "u": r["_uid"], "h": r["_hlc"], "d": dev, "row": row}) + mark = max(mark, r["_hlc"]) + for r in con.execute("SELECT * FROM _sync_tomb WHERE dev = ? AND hlc > ? ORDER BY hlc", (dev, since)): + if r["tbl"] in tables: + out.append({"t": f"{name}.{r['tbl']}", "u": r["uid"], "h": r["hlc"], "d": dev, "del": True}) + mark = max(mark, r["hlc"]) + return out, mark + finally: + con.close() + + +def is_empty(path, tables): + """Nothing synced in this file yet (no rows, no delete markers)? Read only.""" + con = connect(path) + try: + return not con.execute("SELECT 1 FROM _sync_tomb LIMIT 1").fetchone() and not any( + con.execute(f"SELECT 1 FROM {t} LIMIT 1").fetchone() for t in tables if _cols(con, t)) + except sqlite3.Error: + return False + finally: + con.close() + + +def mark_pushed(path, mark): + con = connect(path) + try: + con.execute("UPDATE _sync_meta SET v = max(v, ?) WHERE k = 'pushed'", (mark,)) + con.commit() + finally: + con.close() + + +def _newer(h, d, lh, ld): + """Does (h, d) win over the local (lh, ld)? Later stamp wins; on a tie the higher device.""" + return (h, d) > (lh or 0, ld or "") + + +def apply(path, tables, name, items): + """Changes from other devices (this file's part of a batch) → {applied, skipped, failed}. + Last change wins per row; a delete marker older than a row's change doesn't remove it.""" + stats = {"applied": 0, "skipped": 0, "failed": 0} + mine = [c for c in items if c["t"].split(".", 1)[0] == name and c["t"].split(".", 1)[1] in tables] + if not mine: + return stats + con = connect(path) + try: + con.execute("BEGIN IMMEDIATE") + con.execute("UPDATE _sync_meta SET v = 1 WHERE k = 'applying'") + top = max(c["h"] for c in mine) + con.execute("UPDATE _sync_meta SET v = max(v, ?) WHERE k = 'clock'", (top,)) + for t, spec in tables.items(): + cols = set(_cols(con, t)) + if not cols: + continue + rows = [c for c in mine if c["t"] == f"{name}.{t}" and not c.get("del")] + # a table pointing at itself (a tree): parents first — whatever can't resolve yet waits a round + while rows: + later = [] + for c in rows: + res = _apply_row(con, t, spec, cols, c) + if res == "wait": + later.append(c) + else: + stats[res] += 1 + if len(later) == len(rows): # nothing moved: apply them with the parent missing + for c in later: + stats[_apply_row(con, t, spec, cols, c, force=True)] += 1 + break + rows = later + for c in mine: + if not c.get("del"): + continue + t = c["t"].split(".", 1)[1] + r = con.execute(f"SELECT rowid AS rid, _hlc, _dev FROM {t} WHERE _uid = ?", (c["u"],)).fetchone() + tomb = con.execute("SELECT hlc, dev FROM _sync_tomb WHERE tbl = ? AND uid = ?", (t, c["u"])).fetchone() + if not tomb or _newer(c["h"], c["d"], tomb["hlc"], tomb["dev"]): + con.execute("INSERT OR REPLACE INTO _sync_tomb VALUES (?, ?, ?, ?)", (t, c["u"], c["h"], c["d"])) + if r and _newer(c["h"], c["d"], r["_hlc"], r["_dev"]): + con.execute(f"DELETE FROM {t} WHERE rowid = ?", (r["rid"],)) + stats["applied"] += 1 + else: + stats["skipped"] += 1 + con.execute("UPDATE _sync_meta SET v = 0 WHERE k = 'applying'") + con.commit() + except Exception: + con.rollback() + raise + finally: + con.close() + return stats + + +def _apply_row(con, t, spec, cols, c, force=False): + row = {k: v for k, v in c["row"].items() if k in cols} # columns this side doesn't have (yet) are left out + for col, ref in spec.get("refs", {}).items(): + if row.get(col) is None: + continue + local = _id_of(con, ref, row[col]) + if local is None and ref == t and not force: + return "wait" + row[col] = local + for col, prefix in spec.get("refs_in", {}).items(): # rows of the same table (a meal's ingredients) + if col in row: + row[col], missing = _refs_back(con, row[col], prefix, t) + if missing and not force: + return "wait" + r = con.execute(f"SELECT rowid AS rid, _hlc, _dev FROM {t} WHERE _uid = ?", (c["u"],)).fetchone() + tomb = con.execute("SELECT hlc, dev FROM _sync_tomb WHERE tbl = ? AND uid = ?", (t, c["u"])).fetchone() + if tomb and not _newer(c["h"], c["d"], tomb["hlc"], tomb["dev"]): + return "skipped" # deleted later somewhere + try: + if r and spec.get("fork"): + done = _fork(con, t, spec["fork"], cols, c, row, r["rid"]) + if done: + return done + if r: + if not _newer(c["h"], c["d"], r["_hlc"], r["_dev"]): + return "skipped" + sets = {**row, "_hlc": c["h"], "_dev": c["d"]} + con.execute(f"UPDATE {t} SET {', '.join(f'{k} = ?' for k in sets)} WHERE rowid = ?", (*sets.values(), r["rid"])) + else: + vals = {**row, "_uid": c["u"], "_hlc": c["h"], "_dev": c["d"]} + # a natural-key row both sides made before they had ids: take it over + con.execute(f"INSERT OR REPLACE INTO {t} ({', '.join(vals)}) VALUES ({', '.join('?' * len(vals))})", + tuple(vals.values())) + except sqlite3.Error as e: + print(f"sync: {t} {c['u']}: {e}", flush=True) + return "failed" + return "applied" + + +def _fork(con, t, content, cols, c, row, rid): + """A document row (spec "fork") meeting another version of itself → "applied" when settled + here, None = go on with the plain last-change-wins (after keeping a copy of the loser).""" + loc = dict(con.execute(f"SELECT * FROM {t} WHERE rowid = ?", (rid,)).fetchone()) + mine, theirs = loc.get("rev"), row.get("rev") + if not mine or not theirs or mine == theirs: + return None # the same text: only the rest differs + win = _newer(c["h"], c["d"], loc["_hlc"], loc["_dev"]) + text = (*content, "rev", "revs") + if mine in (row.get("revs") or "").split(): # written on top of ours: its text + if win: + return None + keep = {k: row[k] for k in text if k in row} + con.execute(f"UPDATE {t} SET {', '.join(f'{k} = ?' for k in keep)} WHERE rowid = ?", (*keep.values(), rid)) + return "applied" + if theirs in (loc.get("revs") or "").split(): # ours was written on top of it: our text + if not win: + return None + # a new state (our text + their pin / folder): stamped here, so it goes out to the others — + # with their stamp our text would never be sent + con.execute(BUMP) + rest = {k: v for k, v in row.items() if k not in text} + con.execute(f"UPDATE {t} SET {''.join(f'{k} = ?, ' for k in rest)}_hlc = {CLOCK}, _dev = {DEV} WHERE rowid = ?", + (*rest.values(), rid)) + return "applied" + # both written at the same time: the later one stays, the other becomes a copy + loser = loc if win else {**row, "_hlc": c["h"], "_dev": c["d"]} + uid = "copy:" + loser["rev"] + if not (con.execute(f"SELECT 1 FROM {t} WHERE _uid = ?", (uid,)).fetchone() + or con.execute("SELECT 1 FROM _sync_tomb WHERE tbl = ? AND uid = ?", (t, uid)).fetchone()): + alias = _alias(con, t) + vals = {**{k: v for k, v in loser.items() if k in cols and k not in (alias, "_uid")}, + "origin": loser["rev"], "_uid": uid} + con.execute(f"INSERT INTO {t} ({', '.join(vals)}) VALUES ({', '.join('?' * len(vals))})", tuple(vals.values())) + return None + + +def device_id(): + return uuid.uuid4().hex[:12] diff --git a/dashboard/system.py b/dashboard/system.py new file mode 100644 index 0000000..2626f24 --- /dev/null +++ b/dashboard/system.py @@ -0,0 +1,202 @@ +"""Settings ▸ General: the web pages' address, touch calibration, backup + restore — the things that +used to need SSH. web.py's /api/system… routes (admin only) call these. + +Backup = one .zip: dash_config.json + dash_data/ (every SQLite file copied with SQLite's own backup, +so a file in use is never caught half-written; the mirrored phone app is left out). It holds the +passwords and the sync key: keep it like a password. + +Restore = that .zip uploaded: checked, kept as restore.zip, applied by apply_pending() at the next +start before anything opens a database (dash.main, first thing). What was there moves to +dash_data.before-restore-
    + + + {% for r in v.cal.rows %} + + + + + + + + {% else %} + + {% endfor %} + +
    ShowCalendarPictogramEditingNew events
    +
    {{ r.name }}{% if r.failing %}⚠Not loading since {{ r.failing.since }}{{ r.failing.count }} failed attempt{{ "s" if r.failing.count != 1 }} · last {{ r.failing.last }}{{ r.failing.error }}The calendar's last good events are still shown.{% endif %}
    {% if r.note == "birthdays from your contacts" %}🎂 + + {% else %}{{ glyph_input("cal.rows." ~ loop.index0 ~ ".glyph", r.glyph, "Pictogram for " ~ r.name) }}{% endif %}{% if r.edit %}{{ EDIT[r.edit][0] }} + {% else %}read-only{{ r.note }}{% endif %}
    No calendars listed yet{% if not v.cal.enabled %} — add a feed or Nextcloud below and save{% else %} — try "Reload from Nextcloud"{% endif %}.
    + +
    Every calendar without its own pictogram: {{ glyph_input("cal.other_glyph", v.cal.other_glyph, "Pictogram for other calendars") }}
    + + +
    +
    +

    Nextcloud connection

    + + + + {{ secret("calendar_app_password", "App password (Nextcloud → Settings → Security)", v.secret["calendar.app_password"]) }} + + +

    Optional: without it, the dashboard's own Local calendar and the feeds still work.

    +
    + +
    +

    Calendar feeds

    +

    Any calendar with an ICS address, read-only: Google's "secret address in iCal format", + Outlook's published calendar, school or holiday calendars. One a line, Name = address or just + the address. Read every 5 minutes.

    + + +
    + +
    +

    Home cards & Local calendar

    +
    Next-event cards on Home (under the birthdays) +
    + {% for i in range(2) %} + + {% endfor %} +
    +
    Local calendar (events saved on the dashboard): name and colour +
    + + +
    +
    + +
    +

    Day view bands

    +

    Shaded behind the timeline on Home and in the week view.

    + {{ band("sleep", v.cal.sleep, "Sleep") }} + {{ band("lunch", v.cal.lunch, "Lunch break") }} +
    +
    + + +{# ======================= one tab per plugin (pluginhost.settings_view) ======================= #} +{% for p in v.plugins if not p.error and not p.core_tab %} + +{% endfor %} + +
    + + +
    + +{# Sync / System (sync.py, system.py): part of General; static/system.js fills them from /api/sync, /api/system #} +
    +
    + + +{# pictogram picker: glyphs the Symbola font has (drawn black-and-white, like on the screen) #} + + + +{% endblock %} +{% block scripts %} + +{% endblock %} diff --git a/dashboard/touch.py b/dashboard/touch.py new file mode 100644 index 0000000..b840790 --- /dev/null +++ b/dashboard/touch.py @@ -0,0 +1,88 @@ +"""Touch input. + +Wraps the evdev-based XPT2046 (ads7846) touchscreen. Optional: if +python3-evdev isn't installed, `HAVE_EVDEV = False` and the rest of the +app keeps running keyboard-only. `calibrate()` is the 5-point press-and- +solve routine that maps raw device units to screen pixels (absorbs the +270° rotation). +""" +import json +import time + +import numpy as np +from PIL import Image, ImageDraw + +from config import CALIB_FILE, THEME +from panel import text_c + +try: + from evdev import InputDevice, ecodes, list_devices + HAVE_EVDEV = True +except ImportError: + HAVE_EVDEV = False + ecodes = None + + +def find_touch_device(): + for path in list_devices(): + dev = InputDevice(path) + caps = dev.capabilities() + if ecodes.EV_ABS in caps and ecodes.EV_KEY in caps \ + and ecodes.BTN_TOUCH in caps[ecodes.EV_KEY]: + return dev + raise RuntimeError("no touchscreen found — is your user in the 'input' group?") + + +def read_tap_raw(dev): + """Block until one press->release; return median raw (x, y) seen while pressed.""" + import statistics + xs, ys, cx, cy, pressed = [], [], None, None, False + for ev in dev.read_loop(): + if ev.type == ecodes.EV_ABS: + if ev.code == ecodes.ABS_X: + cx = ev.value + elif ev.code == ecodes.ABS_Y: + cy = ev.value + if pressed and cx is not None and cy is not None: + xs.append(cx); ys.append(cy) + elif ev.type == ecodes.EV_KEY and ev.code == ecodes.BTN_TOUCH: + if ev.value == 1: + pressed, xs, ys = True, [], [] + elif ev.value == 0 and xs: + return statistics.median(xs), statistics.median(ys) + + +def calibrate(panel, dev): + """Tap 5 points; least-squares solve raw->screen (absorbs the 270° flip/swap).""" + m = 40 + targets = [(m, m), (panel.w - m, m), (panel.w - m, panel.h - m), + (m, panel.h - m), (panel.w // 2, panel.h // 2)] + raws = [] + for (sx, sy) in targets: + img = Image.new("RGB", (panel.w, panel.h), THEME["bg"]) + d = ImageDraw.Draw(img) + text_c(d, panel.w / 2, 16, "Calibration — tap each crosshair", + panel.f["sm"], THEME["fg"]) + d.line([(sx - 14, sy), (sx + 14, sy)], fill=THEME["highlight"], width=2) + d.line([(sx, sy - 14), (sx, sy + 14)], fill=THEME["highlight"], width=2) + d.ellipse([sx - 7, sy - 7, sx + 7, sy + 7], outline=THEME["highlight"], width=2) + panel.blit(img) + time.sleep(0.35) + try: + while dev.read_one() is not None: + pass + except Exception: + pass + raws.append(read_tap_raw(dev)) + A = np.array([[rx, ry, 1.0] for (rx, ry) in raws]) + mx, *_ = np.linalg.lstsq(A, np.array([t[0] for t in targets]), rcond=None) + my, *_ = np.linalg.lstsq(A, np.array([t[1] for t in targets]), rcond=None) + calib = {"mx": mx.tolist(), "my": my.tolist()} + with open(CALIB_FILE, "w") as f: + json.dump(calib, f) + return calib + + +def raw_to_screen(calib, rx, ry): + mx, my = calib["mx"], calib["my"] + return (mx[0] * rx + mx[1] * ry + mx[2], my[0] * rx + my[1] * ry + my[2]) diff --git a/dashboard/web.py b/dashboard/web.py new file mode 100644 index 0000000..6c22cf2 --- /dev/null +++ b/dashboard/web.py @@ -0,0 +1,477 @@ +"""The dashboard as a web page (Flask + Jinja templates). + +Runs inside the dashboard process on a background thread (`web_worker`, +started by `dash.main` when `web.enabled` is set), so it reads the same live +`Store` the workers fill — no extra calls to Nextcloud / OWM / termix. + + / Home: the clock + the plugins' regions (pluginhost.home_parts: weather, + stations, main temperature, birthdays + cards, Upcoming, day view) + /m old compact Home -> redirects to / (Home is responsive now) + /fonts/… DejaVu + Symbola from the Pi, so pictograms match the device + /settings edit dash_config.json (settings.py); /api/settings POST, /api/restart POST, + /api/status (worker states), /api/geocode?q= (place search) — admin only + /login log in (GET form / POST), logged in: who you are + log out; /logout POST + /api/users… Settings ▸ Users (auth.py): users, the household view — admin only + /app the phone app's newest build to install (mirrored from the sync server, sync.app_mirror) + /api/sync/kick POST from the phone app: "sync now" (sync.kick; proven by the data key, not a login) + the plugins' pages (plugins//, pluginhost.py): /week, /month, /api/reminders, /api/events … + (calendar), /weather, /icon/… (weather), /stations, /work, /health, /food … + +The pages are responsive: a wall layout that fills a landscape screen +(1080p TV / monitor) without scrolling, a scrolling stacked layout on +phones, tablets and portrait windows. They re-fetch themselves every minute +(and when the tab comes back into view); the analog clock ticks in the browser. +Who's looking (auth.py): admin (everything), a member (their plugins + calendars) or, +without a login, the household — read only (every write refused here). No accounts yet = +everyone is admin. Still meant for the LAN (plain HTTP). +""" +import base64 +import io +import ipaddress +import logging +import math +import os +import socket +from urllib.parse import urlparse, urlsplit + +from flask import Flask, abort, g, jsonify, redirect, render_template, request, send_file, url_for + +import auth +from config import FONT_DIR, THEME +from panel import EMOJI_FONTS +import pluginhost +import webview + +FONTS = { + "dejavu.ttf": os.path.join(FONT_DIR, "DejaVuSans.ttf"), + "dejavu-bold.ttf": os.path.join(FONT_DIR, "DejaVuSans-Bold.ttf"), + "emoji.ttf": next((p for p in EMOJI_FONTS if os.path.exists(p)), None), +} +STATIC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "static") +MAX_BODY = 2 * 1024 * 1024 # bytes a request may send (the biggest: a long note) + + +def build_id(): + """Changes whenever dash.css / dash.js change on disk (a deploy): pages compare + it on their minute refresh and reload in full, so they pick up the new files.""" + return "%x" % int(max(os.path.getmtime(os.path.join(STATIC, f)) for f in ("dash.css", "dash.js", "users.js", "system.js"))) + + +def host_ok(store): + """Against DNS rebinding: a page on another site can point its own name at this address, and + its requests then arrive with that name. So answer only to an IP address, localhost, this + machine's name (+ .local / .lan / .home) and the names in web.hosts (dash_config.json).""" + try: + h = (urlsplit("//" + (request.host or "")).hostname or "").rstrip(".").lower() + except ValueError: + return False + try: + ipaddress.ip_address(h) + return True + except ValueError: + pass + me = socket.gethostname().lower() + extra = {str(x).strip().lower() for x in ((store.cfg.get("web") or {}).get("hosts") or [])} + return h in {"localhost", me, me + ".local", me + ".lan", me + ".home"} | extra + + +def same_origin(): + """Writes only from our own pages: JSON bodies (a plain cross-site form can't + send those without a CORS preflight we never answer) and, when the browser + sends one, an Origin naming this host.""" + origin = request.headers.get("Origin") + return request.is_json and (not origin or urlparse(origin).netloc == request.host) + + +def _calendar_names(store, users, household): + """Every calendar name the dashboard knows, for Settings ▸ Users — not only what the last + sync found (empty right after a restart): Settings ▸ Calendar's names (hidden, cards, + pictograms, no new events), the Local calendar, and whatever someone is already given.""" + c = store.cfg.get("calendar") or {} + with store.lock: + names = {r["name"] for r in store.cal_collections} | {m.get("cal_name") for m, _, _ in store.cal_sources} + names |= set(c.get("hidden_calendars") or []) | set(c.get("card_calendars") or []) | set(c.get("no_create") or []) + names |= {k for k in (c.get("icons") or {}) if k != "*"} | {c.get("local_name") or "Local"} + for v in users + [household]: + names |= set(v.get("calendars") or []) + return sorted((n for n in names if n), key=str.lower) + + +def _set_cookie(resp, token): + resp.set_cookie(auth.COOKIE, token, max_age=auth.SESSION_DAYS * 86400, httponly=True, samesite="Lax") + + +def create_app(store): + app = Flask(__name__) + app.config["TEMPLATES_AUTO_RELOAD"] = True # a template-only deploy needs no restart + app.config["MAX_CONTENT_LENGTH"] = MAX_BODY + app.jinja_env.globals.update(THEME=THEME, cos=math.cos, sin=math.sin, LUNCH_BG=webview.LUNCH_BG, + build_id=build_id, SCALE=[], # the calendar plugin sets SCALE + plugin_nav=lambda: pluginhost.nav(store), + plugin_section=lambda name: pluginhost.section(store, name), + plugin_host=lambda name: pluginhost.host_of(store, name), + viewer=auth.viewer, auth_active=auth.active) + pluginhost.attach(app, store, same_origin) # plugins// (pluginhost.py) + + @app.before_request + def who(): + """Who's looking (auth.py); the household can't write anything, only admins reach + Settings. Only for our own names (host_ok).""" + if not host_ok(store) and not request.environ.get("dash.internal"): + print(f"web: refused a request for host {request.host!r} (add it to web.hosts if it's yours)", flush=True) + abort(400) + g.viewer = v = auth.from_request() + if request.path in ("/login", "/logout", "/api/sync/kick"): # the kick proves itself (sync.kick) + return None + if request.path.startswith(ADMIN_ONLY) and v["kind"] != "admin": + if request.method == "GET" and request.path == "/settings": + return redirect("/login?next=/settings") + abort(403) + if request.method not in ("GET", "HEAD", "OPTIONS") and v["kind"] == "household": + abort(403) + return None + + @app.route("/login", methods=["GET", "POST"]) + def login(): + nxt = request.values.get("next") or "/" + nxt = nxt if nxt.startswith("/") and not nxt.startswith("//") else "/" + err = None + if request.method == "POST": + origin = request.headers.get("Origin") + if origin and urlparse(origin).netloc != request.host: + abort(403) + addr = request.remote_addr or "?" + if auth.locked(addr): + err = "Too many wrong passwords — wait 10 minutes." + else: + tok = auth.login(request.form.get("name"), request.form.get("password"), addr, + request.headers.get("User-Agent", "")) + if tok: + resp = redirect(nxt) + _set_cookie(resp, tok) + return resp + err = "Wrong name or password." + return render_template("login.html", page="login", error=err, next=nxt, + name=request.form.get("name", "")), (401 if err else 200) + + @app.route("/logout", methods=["POST"]) + def logout(): + origin = request.headers.get("Origin") + if origin and urlparse(origin).netloc != request.host: + abort(403) + auth.logout(request.cookies.get(auth.COOKIE)) + resp = redirect("/") + resp.delete_cookie(auth.COOKIE) + return resp + + @app.route("/api/users") + def api_users(): + users, hh = auth.users(), auth.household() + return jsonify(users=users, household=hh, plugins=pluginhost.catalog(), + calendars=_calendar_names(store, users, hh), me=g.viewer["id"], active=auth.active()) + + @app.route("/api/users/", methods=["POST"]) + def api_users_change(what): + if not same_origin(): + abort(403) + d = request.get_json(silent=True) or {} + names = [p["name"] for p in pluginhost.catalog()] + me, first = g.viewer["id"], not auth.active() + if what == "save": + if first: # the first account is the admin, logged in at once + if not auth.setup_ok(d.get("setup"), request.remote_addr): + return jsonify(error="Wrong setup code — it's in the dashboard's log (journalctl -u dashboard).", + field="setup"), 403 + d["role"] = "admin" + uid, err = auth.save_user(d, names, me_id=me, keep_token=request.cookies.get(auth.COOKIE)) + if err: + return jsonify(error=err), 400 + resp = jsonify(ok=True, id=uid) + if first: + _set_cookie(resp, auth.login(d.get("name"), d.get("password"), request.remote_addr or "?")) + return resp + if what == "delete": + err = auth.delete_user(d.get("id"), me_id=me) + return (jsonify(error=err), 400) if err else jsonify(ok=True) + if what == "logout": + auth.logout_everywhere(d.get("id")) + return jsonify(ok=True) + if what == "household": + auth.save_household(d, names) + return jsonify(ok=True) + abort(404) + + @app.route("/favicon.ico") # browsers ask for it unprompted + def favicon(): + return redirect(url_for("static", filename="favicon.svg"), 301) + + @app.route("/") + def home(): + parts = pluginhost.home_parts(store) + off = [c for c, gone in (("off-wx", "weather" not in parts), ("off-st", not ({"stations", "main"} & set(parts))), + ("off-cal", "day" not in parts)) if gone] + return render_template("home.html", parts=parts, off=off, page="home") + + @app.route("/m") + def mini(): # old compact Home; / adapts to the window now + return redirect("/", 301) + + @app.route("/settings") + def settings_page(): + import settings + return render_template("settings.html", v=settings.view(store), page="settings") + + @app.route("/api/settings", methods=["POST"]) + def api_settings(): + if not same_origin(): + abort(403) + import settings + try: + return jsonify(settings.apply(store, request.get_json(silent=True) or {})) + except settings.Invalid as e: + return jsonify(error=str(e), field=e.field), 400 + except OSError as e: + return jsonify(error=f"Could not write the config ({e.strerror})."), 500 + + @app.route("/api/restart", methods=["POST"]) + def api_restart(): + if not same_origin(): + abort(403) + import settings + settings.restart(store) + return jsonify(ok=True) + + @app.route("/app") + def app_page(): # the phone app for the home network (sync.app_mirror) + import sync + return render_template("app.html", page="app", info=sync.app_info()) + + @app.route("/app/dash-app.apk") + def app_apk(): + import sync + info = sync.app_info() + if not info: + abort(404) + return send_file(info["file"], mimetype="application/vnd.android.package-archive", as_attachment=True, + download_name=f"dashPi-{info.get('version')}-{info.get('build')}.apk", max_age=0) + + @app.route("/api/sync/kick", methods=["POST"]) + def api_sync_kick(): + import sync + code, answer = sync.kick(request.get_data(cache=False)) + return jsonify(answer), code + + # ---- Settings ▸ General ▸ Sync (sync.py): set up / join from the browser, devices, the phone's QR code — admin only + def sync_answer(fn): + if not same_origin(): + abort(403) + try: + return jsonify(fn(request.get_json(silent=True) or {}) or {"ok": True}) + except (ValueError, RuntimeError, OSError) as e: + return jsonify(error=str(e)), 400 + + @app.route("/api/sync") + def api_sync(): + import sync + v = sync.view() + v["primary"] = (store.cfg.get("sync") or {}).get("primary", True) + v["devices"], v["manager"], v["devices_error"] = [], False, None + if v["configured"]: + try: + v["devices"], v["manager"] = sync.devices() + except Exception as e: + v["devices_error"] = str(e) + return jsonify(v) + + @app.route("/api/sync/", methods=["POST"]) + def api_sync_do(what): + import sync + import threading + import settings + + def connect(d): + res = sync.connect(str(d.get("server") or ""), str(d.get("token") or ""), + d.get("passphrase") or None, d.get("recovery") or None) + threading.Thread(target=_quietly, args=(sync.sync_now,), daemon=True, name="sync-first").start() + return res + + def add(d): + res = sync.add_device(str(d.get("name") or "").strip()) + res["link"] = sync.pair_link(res["server"], res["token"]) + png = sync.qr_png(res["link"]) + res["qr"] = None if png is None else "data:image/png;base64," + base64.b64encode(png).decode() + return res + + steps = { + "probe": lambda d: sync.probe(str(d.get("server") or ""), str(d.get("token") or "")), + "connect": connect, + "now": lambda d: sync.sync_now(), + "passphrase": lambda d: sync.new_passphrase(d.get("new"), old=d.get("old") or None, + recovery=d.get("recovery") or None), + "disconnect": lambda d: sync.disconnect(), + "add": add, + "revoke": lambda d: sync.revoke_device(str(d.get("name") or "")), + "primary": lambda d: settings.save_part(store, "sync", dict(store.cfg.get("sync") or {}, + primary=bool(d.get("on")))), + } + if what == "kick" or what not in steps: + abort(404) + return sync_answer(steps[what]) + + # ---- the 3.5" screen as a picture (?n = which screen, 0 = Home) — what the Pi shows, or would — admin only + @app.route("/api/screen.png") + def api_screen(): + import screens + from panel import Panel + if "panel" not in _preview: + _preview["panel"] = Panel(None) + names = [s["label"] for s in screens.screen_list(store)] + n = request.args.get("n", "0") + n = names.index(n) if n in names else int(n) if n.isdigit() and int(n) < len(names) else 0 + img = screens.render(_preview["panel"], _OwnScreen(store, n)) + buf = io.BytesIO() + img.save(buf, "PNG") + resp = app.response_class(buf.getvalue(), mimetype="image/png") + resp.headers["X-Screens"] = ", ".join(names) + return resp + + # ---- Settings ▸ General (system.py): web address, touch calibration, backup / restore — admin only + @app.route("/api/system") + def api_system(): + import system + return jsonify(system.view(store, getattr(store, "headless", False))) + + @app.route("/api/system/backup") + def api_backup(): + import system + data, name = system.backup() + return send_file(io.BytesIO(data), mimetype="application/zip", as_attachment=True, download_name=name, max_age=0) + + @app.route("/api/system/restore", methods=["POST"]) + def api_restore(): + """The backup as the raw body (not a form: it's bigger than MAX_BODY, read straight to disk).""" + import system + origin = request.headers.get("Origin") + if origin and urlparse(origin).netloc != request.host: + abort(403) + if request.headers.get("Content-Type") != "application/zip": + return jsonify(error="Send the backup .zip."), 400 + try: + info = system.receive(request.environ["wsgi.input"], request.content_length or 0) + except system.Invalid as e: + return jsonify(error=str(e)), 400 + return jsonify(ok=True, backup=info) + + @app.route("/api/system/", methods=["POST"]) + def api_system_do(what): + import settings + import system + if not same_origin(): + abort(403) + d = request.get_json(silent=True) or {} + try: + if what == "web": + new, restart = system.web_settings(store, d) + settings.save_part(store, "web", new) + if restart: + store.restart_needed = True + return jsonify(ok=True, restart=restart) + if what == "screen": + settings.save_part(store, "screen", system.screen_settings(store, d)) + store.restart_needed = True + return jsonify(ok=True, restart=True) + if what == "calibrate": + system.recalibrate() + settings.restart(store) + return jsonify(ok=True) + if what == "cancel-restore": + system.cancel() + return jsonify(ok=True) + if what == "apply-restore": + settings.restart(store) + return jsonify(ok=True) + except system.Invalid as e: + return jsonify(error=str(e)), 400 + abort(404) + + @app.route("/api/status") + def api_status(): + import settings + return jsonify({**settings.status(store), "restart": store.restart_needed}) + + @app.route("/api/geocode") + def api_geocode(): + import settings + q = (request.args.get("q") or "").strip()[:80] + if len(q) < 2: + return jsonify([]) + try: + return jsonify(settings.geocode(q)) + except Exception as e: + return jsonify(error=type(e).__name__), 502 + + @app.route("/fonts/") + def fonts(name): + path = FONTS.get(name) + if not path or not os.path.exists(path): + abort(404) + return send_file(path, mimetype="font/ttf", max_age=7 * 86400) + + return app + + +ADMIN_ONLY = ("/settings", "/api/settings", "/api/restart", "/api/status", "/api/geocode", "/api/users", + "/api/sync", "/api/system", "/api/screen") +_preview = {} # the off-screen panel of /api/screen.png, made on first use + + +class _OwnScreen: + """The store as a preview sees it: the same data, its own screen index (and taps, sub-tabs) — the real + panel's stay as they are.""" + def __init__(self, store, n): + object.__setattr__(self, "_store", store) + self.screen, self.hits, self.temp_tab, self.cal_page = n, [], -1, 0 + + def __getattr__(self, k): + return getattr(self._store, k) # (/api/sync/kick is let through before this: it proves itself) +WARM = ("/", "/settings") # the plugins keep their own pages warm + + +def _quietly(fn): + try: + fn() + except Exception as e: + print(f"web: {fn.__name__}: {e}", flush=True) + + +def _warm(app): + """Open the core pages once after start-up, so the first real visit doesn't pay for + compiling the templates (≈ 0.5–1 s each on the Pi 3). Plugins keep their own pages + warm (pluginhost.warm).""" + import time + time.sleep(15) # the workers' first fetches come first + client = app.test_client() + for path in WARM: + try: + client.get(path, environ_base={"dash.internal": True}) # as admin (auth) + except Exception as e: + print(f"web: warm {path}: {type(e).__name__}: {e}", flush=True) + + +def web_worker(store): + """Serve the web view on web.host:web.port (default 0.0.0.0:8080).""" + from werkzeug.serving import make_server + wc = store.cfg.get("web") or {} + logging.getLogger("werkzeug").setLevel(logging.WARNING) # no per-request log lines + import threading + app = create_app(store) + try: + srv = make_server(wc.get("host", "0.0.0.0"), int(wc.get("port", 8080)), app, threaded=True) + except OSError as e: + print("web: cannot start:", e, flush=True) + return + print(f"web: serving on http://{srv.host}:{srv.port}/", flush=True) + if not auth.active(): + print(f"web: no admin account yet — Settings ▸ Users asks for this setup code: {auth.setup_code()}", flush=True) + threading.Thread(target=_warm, args=(app,), daemon=True, name="web-warm").start() + srv.serve_forever() diff --git a/dashboard/webview.py b/dashboard/webview.py new file mode 100644 index 0000000..6fb4664 --- /dev/null +++ b/dashboard/webview.py @@ -0,0 +1,30 @@ +"""Shared view helpers of the core: the sleep / lunch bands set in Settings ▸ Calendar +(`_band`; the calendar plugin's day view and week, and ctx.day_bands for the plugins). +Everything else that used to live here moved into the plugins it belongs to (calendar, +weather, stations: their views.py). +""" + +LUNCH_BG = "#1b202b" # tinted bands behind events (see BANDS), half-way to the card grey +BANDS = (("sleep", "Sleep"), ("lunch_break", "Lunch")) # calendar. -> label + + +def _hhmm(s): + """'13:30' -> 13.5 (hours), or None if it doesn't parse.""" + try: + h, m = (int(x) for x in str(s).split(":")) + return h + m / 60 + except ValueError: + return None + + +def _band(cfg, key, today): + """calendar. {"start": "13:00", "end": "14:00", "weekdays": [1..7]} + -> [(start_h, end_h), …] for today (two spans when it crosses midnight, + e.g. 23:00–07:00), or []. weekdays (ISO, 1 = Monday) is optional.""" + b = (cfg.get("calendar") or {}).get(key) or {} + a, z = _hhmm(b.get("start", "")), _hhmm(b.get("end", "")) + if a is None or z is None or a == z: + return [] + if b.get("weekdays") and today.isoweekday() not in b["weekdays"]: + return [] + return [(a, z)] if z > a else [(0, z), (a, 24)] diff --git a/docs/app.md b/docs/app.md new file mode 100644 index 0000000..c50cc1a --- /dev/null +++ b/docs/app.md @@ -0,0 +1,76 @@ +# The phone app + +Flutter, Android. It keeps its own copy of the data, works offline and syncs through your server +([server.md](server.md)) about every 5 minutes while open and about hourly in the background. + +## Build + +You need Flutter with Dart 3.12 or newer (the app is built with Flutter 3.44) and the Android SDK. + +```bash +cd app +flutter pub get +flutter test +flutter build apk --release +``` + +Install `build/app/outputs/flutter-apk/app-release.apk` on the phone. + +### Signing + +A release build without a key is signed with the debug key. That APK installs, but your later builds can't +update it, and it can't update a properly signed install. Make a key once and keep it safe, outside the +repo: + +```bash +keytool -genkey -v -keystore ~/keys/dashpi-upload.jks -keyalg RSA -keysize 4096 -validity 10000 -alias dashpi +``` + +`app/android/key.properties` (git ignores it): + +``` +storeFile=/home/you/keys/dashpi-upload.jks +storePassword=… +keyAlias=dashpi +keyPassword=… +``` + +### Your own defaults (optional) + +These can be built in with `--dart-define` so the app starts with them; all of them can also be set in the app: + +| Define | What | In the app | +|---|---|---| +| `DEV_SERVER` | The server the connect screen suggests, e.g. `https://sync.example.com` | Connect screen | +| `PI_URL` | The dashboard on your home network, e.g. `http://192.168.1.50:8080`, for "sync now" | Sync page ▸ Dashboard on the home network | +| `HOME_PLACES` | Weather places, home first: `Home, XX\|47.17\|24.06;Town, XX\|46.77\|23.60` | Weather ▸ Add a place | + +## Connect + +1. Set up sync on the dashboard first (Settings ▸ General ▸ Sync, [dashboard.md](dashboard.md)). +2. There: **Devices ▸ Add a device** → a QR code. +3. In the app: **Scan the code from the dashboard**, then type the passphrase (or use the recovery key). + Without a camera, type the server and token shown under the code. + +The token and the data key are kept in Android's keystore-backed secure storage. The app's database is +excluded from Android backups; the dashboard keeps the data anyway. + +**Sync now:** with the dashboard's address set (Sync page), the app asks the dashboard on the home network +to process new band data right away. The request is sealed with the data key. Away from home nothing happens. + +**Gadgetbridge:** Sync page ▸ Band (Gadgetbridge): pick Gadgetbridge's database export (Gadgetbridge ▸ Settings ▸ Auto +export). The app relays new rows to the dashboard, which works out the sleep, heart and activity summaries. + +## Updates over the air (optional) + +The app can update itself from your sync server. `tool/publish.sh` builds the next build number, signs it +and uploads `app.json` + the APK to the server's `app/` folder over SSH. Phones then offer it on the Sync page. + +```bash +cp tool/publish.env.example tool/publish.env # your server, SSH login, defines +# write a "## x.y.z — date" entry in CHANGELOG.md for the pubspec version +tool/publish.sh +``` + +The primary dashboard mirrors the newest build at `http://:8080/app` for a first install on the +home network. diff --git a/docs/architecture.md b/docs/architecture.md new file mode 100644 index 0000000..3cad5ba --- /dev/null +++ b/docs/architecture.md @@ -0,0 +1,58 @@ +# How it fits together + +``` + 3.5" SPI screen ◄── dash.py (Pillow → RGB565 → /dev/fb0) ──┐ + touch (evdev) ──► │ one Python process: + │ workers fill a shared Store, + browser / TV ◄── web.py (Flask, :8080) ─────────────────┤ the screen and the web pages + │ read it + plugins// (pages, workers, data in dash_data//*.db) + │ + syncdb.py stamps every change; sync.py sends / receives + │ XChaCha20-Poly1305, key never leaves the devices + ▼ + server/ (PHP + SQLite): encrypted batches, in order + ▲ + app/ (Flutter): its own SQLite copy, same merge rules +``` + +## The dashboard (`dashboard/`) + +- **No X, no Wayland.** Each tick `screens.render()` draws a 480×320 PIL image, `panel.to_rgb565()` packs it, + and it's written to the panel's framebuffer + (found by itself: `panel.find_screen`; none = web pages only). Redraws about once a second and on touch. +- **Store** (`store.py`): the shared state the workers fill (weather, calendar, sensors) and the screen and + pages read. +- **Plugins** (`pluginhost.py`): every feature beyond the clock is a package in `plugins//` with a `META` + and `register(ctx)`. `ctx` is the whole API: a blueprint for pages, Home regions, 3.5" screens, + workers, settings fields, cached pages, sync specs. A plugin keeps its data in `dash_data//`. + Turning one on or off needs no restart. +- **Web** (`web.py`): Jinja pages that fill a landscape screen without scrolling and stack on phones. They + refresh every minute and reload after a deploy. +- **Users** (`auth.py`): admin, members (a subset of sections), and the household (no login, read only; + also what the 3.5" screen shows). +- **Settings** (`settings.py`): `dash_config.json`, validated, applied live where possible. + +Import direction is one way: `config` ← `store` ← `panel` ← screen modules ← `dash`. The plugins only use `ctx` +(the built-in weather, calendar and stations plugins also use the Store and the drawing helpers). + +## Sync + +Every device keeps a full copy. Changes go through the server, which only stores encrypted batches. + +- `syncdb.py` adds `_uid`, `_hlc` (hybrid logical clock, ms) and `_dev` to every synced table, and triggers that + stamp each insert/update and turn deletes into tombstones. Plugin code doesn't change. +- Which tables sync is each plugin's `META["sync"]`. Foreign keys travel as the target's `_uid`. +- Merge: the last change wins by (`_hlc`, `_dev`); a tombstone beats older changes. Notes are documents with + revisions, and two edits made at the same time keep both, as a conflicted copy. +- Keys: one random data key, wrapped on the server with Argon2id(passphrase). The recovery key is the data key + in base32. + +The full protocol, which the app follows to the letter: [server/PROTOCOL.md](../server/PROTOCOL.md). + +## The app (`app/`) + +Flutter, Android. `lib/sync/` is the protocol (store, crypto, client). `lib/health`, `lib/work`, `lib/notes` +and `lib/weather` are the pages. They are ports of the dashboard's views, and their numbers must match. +Health summaries from the band (sleep, heart rate, energy) are worked out on the primary dashboard and +synced to the app one way. diff --git a/docs/dashboard.md b/docs/dashboard.md new file mode 100644 index 0000000..2b18926 --- /dev/null +++ b/docs/dashboard.md @@ -0,0 +1,139 @@ +# The dashboard + +## What you need + +- **With the screen:** a Raspberry Pi (a Pi 3 is enough) on Raspberry Pi OS Bookworm or newer, and a 3.5" + 480×320 SPI TFT on the GPIO header. The common ILI9486 + XPT2046 "piscreen" boards work. +- **Without a screen:** any Linux machine (Debian/Ubuntu for the install script). With no small screen found it runs + the web pages and background workers only; `--headless` forces that. + +## The screen (skip for headless) + +In `/boot/firmware/config.txt`: + +``` +dtparam=spi=on +dtoverlay=piscreen,speed=16000000,rotate=270 +``` + +Reboot. The panel should appear as `/dev/fb0` (RGB565, 480×320) and touch as an `ads7846` input device. +To keep the console from blanking the panel, add ` consoleblank=0` to the single line in +`/boot/firmware/cmdline.txt`. The first start runs a 5-point touch calibration; `dash.py --calibrate` +redoes it. + +## Install + +```bash +git clone https://git.hackman.club/HackmanClub/dashboard.git dashpi +cd dashpi +sudo ./dashboard/install.sh # with the screen, runs as you +sudo ./dashboard/install.sh --headless # without +``` + +The script installs the apt packages, copies `dashboard/` to `/opt/dashboard` and writes +`/opt/dashboard/dash_config.json` from the example if there isn't one. It then installs and starts the +`dashboard` systemd service. Options: `--dir`, `--user ` (creates a system user if missing), +`--no-apt`, `--no-service`. + +**Update:** `git pull`, then run the same command again. Your `dash_config.json`, `dash_data/` and the +other state files in `/opt/dashboard` are never touched. + +Without the script (another distro, a virtualenv): install the packages from +[`dashboard/requirements.txt`](../dashboard/requirements.txt) plus the DejaVu fonts (and Symbola for emoji +on the screen). Copy `dash_config.example.json` to `dash_config.json` and run `python3 dash.py [--headless]`. + +## First start (everything else is in the browser) + +1. Open `http://:8080/settings`. +2. **Settings ▸ Users:** create the admin account. It asks for the **setup code** printed in the log: + `journalctl -u dashboard | grep 'setup code'`. From the machine itself (`localhost`) no code is needed. +3. **Settings ▸ Users ▸ Household view:** choose what people see without a login (the 3.5" screen too). + By default that's weather and sensors, with no calendars. +4. **Weather:** search your town; add more places for the weather page. The phone app gets the same places. + **Calendar:** any ICS feeds (Google's "secret address in iCal format", Outlook, holidays), and if you have + one, Nextcloud / CalDAV (URL, user name, an app password: Nextcloud ▸ Settings ▸ Security). The dashboard's + own Local calendar works with neither. +5. **Sensors:** **+ Add sensor source**, pick the kind, **Test** it, then **+ Add** the readings you want (below). +6. **Plugins:** switch on the ones you want. Each has its own settings tab. + +## Configuration + +Everything is in the Settings page and stored in `dash_config.json` (chmod 600, it holds the passwords). The only +key without a page is `web.enabled` (`false` by default, `true` in the example the installer copies). + +**Settings ▸ General** (besides units, the plugins and Sync): +- **Web pages:** who can open them (everyone on the network / only this computer), the port, and extra host + names it answers to. IP addresses, `localhost` and this machine's name (+ `.local` / `.lan` / `.home`) always work. +- **Screen:** where to draw. "Find it" uses a small SPI panel and never a desktop's own display; or pick one, or none. + It also recalibrates the touch screen. +- **Backup:** download one, or restore one (also to move to a new machine). + +For the command-line tools only: `FOOD_COUNTRIES` (`plugins/food/off.py`: whose shop products go into the +food database, e.g. `romania,slovakia`) and `DASH_TZ` (the Health time zone for `plugins/health/mi.py`; on +the dashboard it's Settings ▸ Health; left empty, the phone app's time zone, sent with the band's data, else the +machine's). + +## Plugins + +| Plugin | On by default | Needs | +|---|---|---| +| Weather | yes | Nothing (Open-Meteo, no key) | +| Calendar | yes | A CalDAV server and/or ICS links | +| Measurement stations | yes | A sensor source (below); hidden until configured | +| Workload tracker | no | | +| Health | no | Optional: a Gadgetbridge database export folder (e.g. synced with Syncthing) | +| Food diary | no | Optional: an Ollama-style model URL for the "describe what you ate" box | +| Cycle tracker | no | | +| Notes | no | | +| Activity | no | [ActivityWatch](https://activitywatch.net) on each computer, listening on the LAN (`aw-server.toml`: `host = "0.0.0.0"`) | + +Each plugin is a folder in `dashboard/plugins//` with a `META` and a `register(ctx)`. See the docstring +of `dashboard/pluginhost.py` for writing your own. + +### Sensors (Measurement stations) + +**Settings ▸ Sensors**: **+ Add sensor source** and pick the kind (the table below), press **Test** to see what it +has, and **+ Add** the readings to show. +Name them, put each indoor / outdoor / hidden, order them, and tick **Main** on the one shown as the big temperature +on Home (any indoor or outdoor one; by default the first indoor one). Up to 3 outdoor ones sit next to the weather. +Saving applies at once. + +| Source | What to give it | What a sensor reads | +|---|---|---| +| **Home Assistant** | Its URL + a long-lived access token (your profile ▸ Security) | An entity (`sensor.kitchen_temperature`); humidity from a second entity | +| **MQTT** | Broker, port, optional login / TLS (needs `python3-paho-mqtt`) | A topic (`tasmota/attic/temp`) or a JSON field of one (`zigbee2mqtt/garage\|temperature`) | +| **JSON URL** | Any URL that answers JSON (ESPHome's web server, Tasmota, your own script), an optional header | A path in the answer (`sensors.0.temp`) | +| **DS18B20 (1-wire)** | Nothing: wire it to GPIO 4 and add `dtoverlay=w1-gpio` to `/boot/firmware/config.txt` | The sensor's id (`28-…`) | +| **termix** | The `stm32.php` URL, API key and device ids | A device id (temperature + humidity) | + +Temperatures can be in °F (a tick per source); they're kept in °C. Readings are kept as 5-minute rows forever, for +the graphs on `/stations` and in the app. + +## Sync, the phone app, more dashboards + +Set up the server first ([server.md](server.md)); it prints this dashboard's token. Then **Settings ▸ General ▸ Sync**: + +1. Server address + token → **Next**. The account's first device chooses the **sync passphrase** and is shown + the **recovery key** once. Write it down: without the passphrase or the recovery key, the synced data + can't be read. +2. **Devices ▸ Add a device** ("phone") shows a QR code. In the app: **Scan the code from the dashboard**, + then type the passphrase. Another dashboard: add a device for it, paste its token into that dashboard's + Settings ▸ General ▸ Sync, and join with the passphrase. Untick **Primary dashboard** there. +3. The same tab: sync now, revoke a lost device, change the passphrase, disconnect. + +The command line does the same: `python3 sync.py setup|join|now|status|passphrase`. + +## Files + +| Path (in `/opt/dashboard`) | What | +|---|---| +| `dash_config.json` | Settings + secrets (600) | +| `dash_data//` | Each plugin's SQLite data (600); `dash_data/auth/users.db` the users, `dash_data/sync/state.json` the sync key | +| `dash_calib.json`, `dash_history.json`, `dash_weather.json` | Touch calibration, 24 h sensor history, last weather | + +**Back up** with Settings ▸ General ▸ Backup (or copy `dash_data/` + `dash_config.json`). Everything +else comes from git. **Move to a new machine:** install there, create an admin, Settings ▸ General ▸ Restore, +then switch the old one off. + +Logs: `journalctl -u dashboard -f`. Don't run `dash.py` by hand while the service runs: both would write +the screen. diff --git a/docs/screenshots/activity.png b/docs/screenshots/activity.png new file mode 100644 index 0000000..c188edc Binary files /dev/null and b/docs/screenshots/activity.png differ diff --git a/docs/screenshots/app-body.png b/docs/screenshots/app-body.png new file mode 100644 index 0000000..022437e Binary files /dev/null and b/docs/screenshots/app-body.png differ diff --git a/docs/screenshots/app-connect.png b/docs/screenshots/app-connect.png new file mode 100644 index 0000000..d14e73e Binary files /dev/null and b/docs/screenshots/app-connect.png differ diff --git a/docs/screenshots/app-cycle.png b/docs/screenshots/app-cycle.png new file mode 100644 index 0000000..f503fe3 Binary files /dev/null and b/docs/screenshots/app-cycle.png differ diff --git a/docs/screenshots/app-food.png b/docs/screenshots/app-food.png new file mode 100644 index 0000000..0634fb9 Binary files /dev/null and b/docs/screenshots/app-food.png differ diff --git a/docs/screenshots/app-health.png b/docs/screenshots/app-health.png new file mode 100644 index 0000000..1495f55 Binary files /dev/null and b/docs/screenshots/app-health.png differ diff --git a/docs/screenshots/app-notes.png b/docs/screenshots/app-notes.png new file mode 100644 index 0000000..fe16cca Binary files /dev/null and b/docs/screenshots/app-notes.png differ diff --git a/docs/screenshots/app-sleep.png b/docs/screenshots/app-sleep.png new file mode 100644 index 0000000..6fa9067 Binary files /dev/null and b/docs/screenshots/app-sleep.png differ diff --git a/docs/screenshots/app-weather.png b/docs/screenshots/app-weather.png new file mode 100644 index 0000000..3cb22e7 Binary files /dev/null and b/docs/screenshots/app-weather.png differ diff --git a/docs/screenshots/app-work.png b/docs/screenshots/app-work.png new file mode 100644 index 0000000..6f2a460 Binary files /dev/null and b/docs/screenshots/app-work.png differ diff --git a/docs/screenshots/app.py b/docs/screenshots/app.py new file mode 100644 index 0000000..70d34e0 --- /dev/null +++ b/docs/screenshots/app.py @@ -0,0 +1,164 @@ +#!/usr/bin/env python3 +"""The phone app's screenshots, from the demo dashboard's made-up data, on an Android emulator. + + tests/server-setup.sh --keep a sync server on :18080 (prints its token) + python3 docs/screenshots/make.py --keep & the demo dashboard on :8199 + e.g. emulator -avd -no-window + python3 docs/screenshots/app.py --token → docs/screenshots/app-*.png + +It connects the demo dashboard to the server (passphrase "correct horse battery"), adds a phone, installs +a debug build of the app (a debug build accepts the test server's plain http), connects it the way a phone +without a camera does (server + token typed in), lets it sync, and photographs each section. Buttons are +found by their labels (uiautomator), not by position. The status bar is put in Android's demo mode. +""" +import argparse +import http.cookiejar +import json +import os +import re +import shutil +import subprocess +import time +import urllib.parse +import urllib.request +from datetime import date, timedelta + +HERE = os.path.dirname(os.path.abspath(__file__)) +APP = os.path.join(os.path.dirname(os.path.dirname(HERE)), "app") +DEMO = "http://127.0.0.1:8199" +PASSPHRASE = "correct horse battery" +PACKAGE = "dev.bashynx.dash_app" + + +def adb_path(): + for d in (os.environ.get("ANDROID_HOME"), os.environ.get("ANDROID_SDK_ROOT")): + if d and os.path.exists(os.path.join(d, "platform-tools", "adb")): + return os.path.join(d, "platform-tools", "adb") + return shutil.which("adb") or "adb" + + +class Phone: + def __init__(self, adb): + self.adb = adb + + def sh(self, *args, out=False): + r = subprocess.run([self.adb, *args], capture_output=True, check=True) + return r.stdout if out else None + + def nodes(self): + """What's on screen: [(label, (x, y) of its centre)] — text or content-desc.""" + self.sh("shell", "uiautomator", "dump", "/sdcard/ui.xml") + xml = self.sh("exec-out", "cat", "/sdcard/ui.xml", out=True).decode() + out = [] + for n in re.findall(r"]*>", xml): + label = (re.search(r'text="([^"]*)"', n).group(1) or re.search(r'content-desc="([^"]*)"', n).group(1)) + x1, y1, x2, y2 = map(int, re.search(r'bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"', n).groups()) + cls = re.search(r'class="([^"]*)"', n).group(1) + out.append((label.replace(" ", "\n"), ((x1 + x2) // 2, (y1 + y2) // 2), cls)) + return out + + def find(self, start, wait=20, exact=False): + """The centre of the first thing whose label starts with `start` (or is it: exact); waits for it.""" + t = time.time() + while time.time() - t < wait: + nodes = self.nodes() + if any("isn't responding" in label for label, _, _ in nodes): # a just-booted emulator's System UI + self.sh("shell", "input", "tap", *map(str, next(xy for label, xy, _ in nodes if label == "Wait"))) + time.sleep(2) + continue + for label, xy, _ in nodes: + if label == start if exact else label.startswith(start): + return xy + time.sleep(1) + raise SystemExit(f"not on screen: {start!r}") + + def tap(self, start, wait=20, exact=False): + x, y = self.find(start, wait, exact) + self.sh("shell", "input", "tap", str(x), str(y)) + + def shot(self, path, settle=3): + time.sleep(settle) + with open(path, "wb") as f: + f.write(self.sh("exec-out", "screencap", "-p", out=True)) + print(" ", os.path.basename(path)) + + +def demo_phone_token(server, token): + """Connect the demo dashboard to the server, push its data, add the device "phone" → its token.""" + op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) + op.open(urllib.request.Request(DEMO + "/login", data=urllib.parse.urlencode( + {"name": "demo", "password": "demo-password-1", "next": "/"}).encode(), headers={"Origin": DEMO})) + def post(path, body): + req = urllib.request.Request(DEMO + path, data=json.dumps(body).encode(), + headers={"Content-Type": "application/json", "Origin": DEMO}) + try: + return json.loads(op.open(req, timeout=120).read()) + except urllib.error.HTTPError as e: + raise SystemExit(f"{path}: {e.code} {e.read()[:300]!r}") + if not json.loads(op.open(DEMO + "/api/sync").read()).get("account"): # not connected yet + post("/api/sync/connect", {"server": server, "token": token, "passphrase": PASSPHRASE}) + try: # a rerun: the old "phone" makes way + post("/api/sync/revoke", {"name": "phone"}) + except SystemExit: + pass # there was none + phone = post("/api/sync/add", {"name": "phone"}) + print("demo dashboard:", post("/api/sync/now", {})) + return phone["token"] + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--token", required=True, help="the sync server's token for the device 'dashboard'") + ap.add_argument("--server", default="http://127.0.0.1:18080", help="the server, as this computer reaches it") + ap.add_argument("--from-phone", default="http://10.0.2.2:18080", help="the server, as the emulator reaches it") + ap.add_argument("--apk", help="an APK to install (default: build a debug one)") + ap.add_argument("--out", default=HERE) + a = ap.parse_args() + phone_token = demo_phone_token(a.server, a.token) + apk = a.apk + if not apk: + flutter = shutil.which("flutter") or "flutter" + subprocess.run([flutter, "build", "apk", "--debug"], cwd=APP, check=True) + apk = os.path.join(APP, "build", "app", "outputs", "flutter-apk", "app-debug.apk") + p = Phone(adb_path()) + p.sh("install", "-r", apk) + p.sh("shell", "pm", "clear", PACKAGE) # a phone that has never connected + p.sh("shell", "settings", "put", "global", "sysui_demo_allowed", "1") + for cmd in (["enter"], ["clock", "-e", "hhmm", "0930"], ["battery", "-e", "level", "100", "-e", "plugged", "false"], + ["network", "-e", "wifi", "show", "-e", "level", "4", "-e", "fully", "true", "-e", "mobile", "hide"], + ["notifications", "-e", "visible", "false"]): + p.sh("shell", "am", "broadcast", "-a", "com.android.systemui.demo", "-e", "command", *cmd) + p.sh("shell", "monkey", "-p", PACKAGE, "-c", "android.intent.category.LAUNCHER", "1") + p.find("Connect to your dashboard", wait=60) + out = lambda n: os.path.join(a.out, f"app-{n}.png") + p.shot(out("connect")) + fields = [xy for _, xy, cls in p.nodes() if cls.endswith("EditText")] + for xy, text in zip(fields, (a.from_phone, phone_token, PASSPHRASE)): + p.sh("shell", "input", "tap", *map(str, xy)) + time.sleep(1) # the field has the focus before typing + p.sh("shell", "input", "text", text.replace(" ", "%s")) + p.sh("shell", "input", "keyevent", "4") # the keyboard away + time.sleep(1) + p.tap("Connect", exact=True) # the button, not "Connect to your dashboard" + p.find("Health\nTab 1", wait=180) # connected; the first sync runs + time.sleep(20) + p.shot(out("health")) + for tab in ("Sleep", "Body", "Cycle"): + p.tap(tab) + p.shot(out(tab.lower())) + p.tap("Food\nTab 2") + p.shot(out("food"), 4) + p.tap("Work\nTab 3") + last_weekday = date.today() - timedelta(days=max(0, date.today().weekday() - 4)) + p.tap(last_weekday.strftime("%a")[:2] + f" {last_weekday.day}") # the day bar: a weekday has entries + p.shot(out("work"), 4) + p.tap("Notes\nTab 4") + p.shot(out("notes"), 4) + p.tap("Weather\nTab 5") + p.shot(out("weather"), 8) + p.sh("shell", "am", "broadcast", "-a", "com.android.systemui.demo", "-e", "command", "exit") + print("pictures in", a.out) + + +if __name__ == "__main__": + main() diff --git a/docs/screenshots/food.png b/docs/screenshots/food.png new file mode 100644 index 0000000..8e49c2f Binary files /dev/null and b/docs/screenshots/food.png differ diff --git a/docs/screenshots/health.png b/docs/screenshots/health.png new file mode 100644 index 0000000..3b81cba Binary files /dev/null and b/docs/screenshots/health.png differ diff --git a/docs/screenshots/home.png b/docs/screenshots/home.png new file mode 100644 index 0000000..bfc1be2 Binary files /dev/null and b/docs/screenshots/home.png differ diff --git a/docs/screenshots/make.py b/docs/screenshots/make.py new file mode 100644 index 0000000..f872997 --- /dev/null +++ b/docs/screenshots/make.py @@ -0,0 +1,435 @@ +#!/usr/bin/env python3 +"""The README's screenshots, made from a demo dashboard full of made-up data (never anyone's real data). + + python3 docs/screenshots/make.py → docs/screenshots/*.png + python3 docs/screenshots/make.py --keep … and leave the demo running at http://127.0.0.1:8199 (Ctrl+C) + +What it does: copies dashboard/ into a temporary folder; writes a demo config (Vienna, every plugin on, four +room sensors from a small fake JSON source served here); fills it the way real data arrives — the pages' own +API (calendar, measurements, food, cycle, work, notes), a generated Gadgetbridge export through the real +import (sleep, heart rate, steps, workouts), sensor history and ActivityWatch-style events through the +plugins' storage; then photographs the web pages with Playwright and the 3.5" screens with /api/screen.png. + +Needs: the dashboard's packages (dashboard/requirements.txt), and for the web pages Playwright +(pip install playwright && playwright install chromium). The weather is live (Open-Meteo), so it changes. +""" +import argparse +import http.cookiejar +import http.server +import json +import math +import os +import random +import shutil +import sqlite3 +import subprocess +import sys +import tempfile +import threading +import time +import urllib.request +from datetime import date, datetime, timedelta + +HERE = os.path.dirname(os.path.abspath(__file__)) +REPO = os.path.dirname(os.path.dirname(HERE)) +PORT = 8199 +BASE = f"http://127.0.0.1:{PORT}" +ADMIN = ("demo", "demo-password-1") +random.seed(7) # the same "random" data every run +TODAY = date.today() +NOW = datetime.now() + + +# ---- the fake sensors: a JSON source like an ESPHome / own-script one ------------------------------------ + +def sensor_values(): + h = NOW.hour + NOW.minute / 60 + out = 9 + 5 * math.sin((h - 9) / 24 * 2 * math.pi) + return {"living": {"temperature": 21.8, "humidity": 46}, "bedroom": {"temperature": 19.6, "humidity": 52}, + "office": {"temperature": 22.9, "humidity": 41}, "garden": {"temperature": round(out, 1), "humidity": 78}} + + +class SensorJSON(http.server.BaseHTTPRequestHandler): + def do_GET(self): + body = json.dumps(sensor_values()).encode() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(body) + + def log_message(self, *a): + pass + + +SENSORS = [ # id, name, place, JSON path → the history below and the config + (1000, "Living room", "indoor", "living"), (1001, "Bedroom", "indoor", "bedroom"), + (1002, "Office", "indoor", "office"), (1003, "Garden", "outdoor", "garden"), +] + + +def config(sensor_port, gb_file): + with open(os.path.join(REPO, "dashboard", "dash_config.example.json")) as f: + c = json.load(f) + c.update(location_name="Vienna, AT", lat=48.2082, lon=16.3738, units="metric", + weather_locations=[{"name": "Lisbon, PT", "lat": 38.7223, "lon": -9.1393}, + {"name": "Oslo, NO", "lat": 59.9139, "lon": 10.7522}]) + c["web"] = dict(c.get("web") or {}, enabled=True, host="127.0.0.1", port=PORT) + c.pop("termix", None) + c["calendar"] = dict(c.get("calendar") or {}, enabled=False, caldav_url="", card_calendars=["Local"], + sleep={"on": True, "start": "23:00", "end": "07:00"}, + lunch_break={"on": True, "start": "12:30", "end": "13:15"}) + c["sensors"] = {"sources": [{"id": "s1", "type": "json", "label": "Room sensors", + "url": f"http://127.0.0.1:{sensor_port}/sensors.json"}], + "list": [{"id": i, "source": "s1", "temp": f"{p}.temperature", "hum": f"{p}.humidity", + "name": n, "place": place} for i, n, place, p in SENSORS], + "main": 1000} + plugins = c.setdefault("plugins", {}) + for name in ("calendar", "weather", "stations", "health", "food", "cycle", "workload", "activity", "notes"): + plugins.setdefault(name, {})["enabled"] = True + plugins["health"].update(sex="male", birth_date="1988-04-12", height=181, sleep_goal=8, gb_export=gb_file) + plugins["workload"].update(currency="EUR", default_rate=60, week_target=40) + return c + + +# ---- data that comes in through imports / workers ---------------------------------------------------------- + +def sensor_history(d): + """35 days of 5-minute rows for the four sensors (the Stations graphs).""" + sys.path.insert(0, d) + from plugins.stations import db as sdb + path = os.path.join(d, "dash_data", "stations", "readings.db") + os.makedirs(os.path.dirname(path), exist_ok=True) + con = sdb.connect(path) + rows, end = [], int(time.time()) // 300 * 300 + days = 36 + swing = [random.uniform(2, 8) for _ in range(days + 1)] # how much each day warms up + front = [random.uniform(-4, 4) for _ in range(days + 1)] # colder / warmer spells + for did, _, place, p in SENSORS: + base, walk = sensor_values()[p]["temperature"], 0.0 + for t in range(end - 35 * 86400, end, 300): + h = datetime.fromtimestamp(t).hour + datetime.fromtimestamp(t).minute / 60 + k = (t - (end - 35 * 86400)) / 86400 + mood = front[int(k)] + (front[int(k) + 1] - front[int(k)]) * (k % 1) + if place == "outdoor": + walk = max(-1.5, min(1.5, walk + random.uniform(-.08, .08))) + v = 7 + mood + swing[int(k)] * math.sin((h - 9) / 24 * 2 * math.pi) + walk + hum = 92 - 3.5 * (v - 2) + random.uniform(-2, 2) + else: + heating = 0.0 if 6 <= h < 22 else -1.1 # cooler at night + walk = max(-.4, min(.4, walk + random.uniform(-.03, .03))) + v = base + heating + 0.12 * mood + 0.5 * math.sin((h - 16) / 24 * 2 * math.pi) + walk + hum = sensor_values()[p]["humidity"] + 4 * math.sin(k / 3) + random.uniform(-1, 1) + rows.append((did, t, round(v, 2), round(v - .15, 2), round(v + .15, 2), round(max(20, min(98, hum)), 1), 5)) + sdb.store_buckets(con, rows) + con.commit() + con.close() + + +def activity_events(d): + """Two weeks of a working computer in ActivityWatch's shape (window, AFK and browser buckets).""" + from plugins.activity import db as adb + path = os.path.join(d, "dash_data", "activity", "activity.db") + os.makedirs(os.path.dirname(path), exist_ok=True) + con = adb.connect(path) + adb.source_seen(con, "laptop", "http://127.0.0.1:5600", hostname="laptop", last_ok=int(time.time())) + win = adb.bucket_row(con, "laptop", "aw-watcher-window_laptop", {"type": "currentwindow", "hostname": "laptop"})["id"] + afk = adb.bucket_row(con, "laptop", "aw-watcher-afk_laptop", {"type": "afkstatus", "hostname": "laptop"})["id"] + web = adb.bucket_row(con, "laptop", "aw-watcher-web-firefox", {"type": "web.tab.current", "hostname": "laptop"})["id"] + apps = [("code", "dashboard — web.py — Visual Studio Code", 30), ("code", "sync.py — Visual Studio Code", 20), + ("gnome-terminal-server", "pytest — Terminal", 10), ("firefox", "Pull request #42 — GitHub — Firefox", 10), + ("thunderbird", "Inbox — Thunderbird", 7), ("slack", "Slack — #team", 8), + ("libreoffice-writer", "Quarterly report.odt — LibreOffice Writer", 8), + ("firefox", "YouTube — Firefox", 4), ("firefox", "Hacker News — Firefox", 3)] + pages = {"Pull request #42 — GitHub — Firefox": "https://github.com/example/dashboard/pull/42", + "YouTube — Firefox": "https://www.youtube.com/", "Hacker News — Firefox": "https://news.ycombinator.com/"} + w_ev, a_ev, b_ev = [], [], [] + for back in range(14, -1, -1): + day = TODAY - timedelta(days=back) + if day.weekday() >= 5: + continue + t = datetime.combine(day, datetime.min.time()).replace(hour=8, minute=random.randint(30, 59)) + stop = t.replace(hour=17, minute=random.randint(0, 40)) + if back == 0: + stop = min(stop, NOW) + while t < stop: + if t.hour == 12 and t.minute < 40: # lunch away + a_ev.append((int(t.timestamp() * 1000), 45 * 60, {"status": "afk"})) + t += timedelta(minutes=45) + continue + app, title, weight = random.choices(apps, weights=[a[2] for a in apps])[0] + dur = random.randint(3, 25) * 60 + ms = int(t.timestamp() * 1000) + w_ev.append((ms, dur, {"app": app, "title": title})) + a_ev.append((ms, dur, {"status": "not-afk"})) + if title in pages: + b_ev.append((ms, dur, {"url": pages[title], "title": title.rsplit(" — ", 1)[0]})) + t += timedelta(seconds=dur) + adb.store_events(con, win, w_ev) + adb.store_events(con, afk, a_ev) + adb.store_events(con, web, b_ev) + con.commit() + con.close() + + +def gadgetbridge_export(path): + """A Gadgetbridge database export (the tables the import reads): 30 days of a band.""" + from plugins.health import gb + con = sqlite3.connect(path) + con.executescript(gb.RELAY_SCHEMA) + ms = lambda dt: int(dt.timestamp() * 1000) + samples = [] + for back in range(30, -1, -1): + day = TODAY - timedelta(days=back) + mid = datetime.combine(day, datetime.min.time()) + bed = mid - timedelta(hours=1, minutes=random.randint(-20, 50)) # around 23:00 the evening before + wake = mid + timedelta(hours=6, minutes=random.randint(35, 80)) + if wake > NOW: + wake = None + rest = random.randint(54, 59) + walk = mid + timedelta(hours=random.choice([7, 12, 18]), minutes=random.randint(0, 40)) + run = mid + timedelta(hours=18, minutes=30) if day.weekday() in (1, 3, 6) else None + end = min(mid + timedelta(days=1), NOW) + t = mid + while t < end: + asleep = t < (wake or NOW) or t >= mid + timedelta(hours=23) + moving = walk <= t < walk + timedelta(minutes=35) or (run and run <= t < run + timedelta(minutes=40)) + if moving: + hr, st = (random.randint(135, 160), random.randint(150, 170)) if run and run <= t else (random.randint(95, 112), random.randint(95, 115)) + elif asleep: + hr, st = rest + random.randint(-3, 4), 0 + else: + hr, st = random.randint(66, 84), random.choice([0, 0, 0, 3, 12, 25]) + samples.append((int(t.timestamp()), hr if t.minute % 2 == 0 else 0, st, st * 70)) + t += timedelta(minutes=1) + con.execute("INSERT INTO XIAOMI_DAILY_SUMMARY_SAMPLE VALUES (?, ?)", (ms(mid), rest)) + if wake: + con.execute("INSERT INTO XIAOMI_SLEEP_TIME_SAMPLE VALUES (?, ?)", (ms(bed), ms(wake))) + t, i = bed, 0 + cycle = [(3, 20), (2, 35), (3, 25), (4, 20)] # (stage, minutes) — 2 deep, 3 light, 4 REM + while t < wake: + stage, mins = cycle[i % 4] + if i and i % 9 == 0: + stage, mins = 5, 6 # awake a moment + con.execute("INSERT OR REPLACE INTO XIAOMI_SLEEP_STAGE_SAMPLE VALUES (?, ?)", (ms(t), stage)) + t += timedelta(minutes=mins + random.randint(-6, 8)) + i += 1 + if walk + timedelta(minutes=35) < NOW: + con.execute("INSERT INTO BASE_ACTIVITY_SUMMARY VALUES (?, ?, ?, NULL)", + (ms(walk), ms(walk + timedelta(minutes=35)), 0x20)) + if run and run + timedelta(minutes=40) < NOW: + con.execute("INSERT INTO BASE_ACTIVITY_SUMMARY VALUES (?, ?, ?, NULL)", (ms(run), ms(run + timedelta(minutes=40)), 0x10)) + con.execute("INSERT OR REPLACE INTO XIAOMI_MANUAL_SAMPLE VALUES (?, 18, ?)", + (ms(mid + timedelta(hours=9)), random.randint(96, 99))) + con.executemany("INSERT OR REPLACE INTO XIAOMI_ACTIVITY_SAMPLE VALUES (?, ?, ?, ?)", samples) + con.commit() + con.close() + + +# ---- data typed in: through the dashboard's own API ------------------------------------------------------- + +class Client: + def __init__(self): + self.op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(http.cookiejar.CookieJar())) + + def call(self, path, body=None, ok=(200,)): + req = urllib.request.Request(BASE + path, data=None if body is None else json.dumps(body).encode(), + headers={"Content-Type": "application/json", "Origin": BASE}) + try: + with self.op.open(req, timeout=60) as r: + raw = r.read() + return json.loads(raw) if r.headers.get_content_type() == "application/json" else raw + except urllib.error.HTTPError as e: + if e.code in ok: + return json.loads(e.read() or b"{}") + raise SystemExit(f"{path}: {e.code} {e.read()[:300]!r}") + + +def fill(c): + day = lambda n: (TODAY + timedelta(days=n)).isoformat() + # calendar (the dashboard's own Local calendar) + for _ in range(60): # the calendar worker's first round lists it + cals = c.call("/api/calendars") + cal = next((t["id"] for t in cals if t["name"] == "Local"), None) + if cal: + break + time.sleep(1) + else: + raise SystemExit(f"no Local calendar to write to: {cals}") + monday = -TODAY.weekday() + week = [(0, "09:30", "09:45", "Stand-up", ""), (0, "11:00", "12:00", "Design review", "Room 2"), + (1, "10:00", "11:30", "Sprint planning", ""), (1, "19:00", "21:00", "Climbing", "Boulder hall"), + (2, "13:00", "14:00", "Lunch talk: SQLite", ""), (3, "14:00", "15:00", "1:1 with Sam", ""), + (4, "15:00", "16:00", "Retro", ""), (4, "18:30", "22:00", "Dinner at Marta's", "")] + events = [(monday + 7 * w + n, a, b, t, p) for w in (0, 1) for n, a, b, t, p in week] + events += [(0, "08:15", "08:45", "Call with Ana", ""), (0, "16:00", "16:45", "Dentist", "Main St 14")] + for n, a, b, title, where in events: + c.call("/api/events", {"cal": cal, "date": day(n), "start": a, "end": b, "title": title, "location": where}) + for n, title in ((5, "Mia's birthday"), (9, "Trip to Lisbon"), (16, "Concert")): + c.call("/api/events", {"cal": cal, "date": day(n), "all_day": True, "title": title}) + # body measurements: a slow trend, a tape measure now and then, blood pressure + for back in range(90, -1, -1): + if back % 3 and back > 7: + continue + w = 84.2 - (90 - back) * 0.035 + random.uniform(-.35, .35) + m = {"day": day(-back), "weight": round(w, 1)} + if back % 14 == 0: + m.update(waist=round(92 - (90 - back) * 0.03, 1), neck=39, hip=99) + c.call("/health/api/measure", m) + for back in (20, 13, 6, 1): + c.call("/health/api/vital", {"kind": "bp", "day": day(-back), "time": "08:10", + "sys": random.randint(116, 124), "dia": random.randint(74, 80)}) + # food: three days of meals from the food database + def food(q): + r = c.call("/food/api/foods?q=" + urllib.request.quote(q))["db"] + return f"usda:{r[0]['id']}" if r else None + menu = [("breakfast", "07:30", [("oatmeal", 250), ("banana", 120), ("coffee brewed", 250)]), + ("lunch", "12:45", [("chicken breast", 150), ("rice cooked", 200), ("broccoli", 120)]), + ("snack", "16:00", [("apple", 180), ("almonds", 25)]), + ("dinner", "19:15", [("salmon", 140), ("boiled potatoes", 220), ("mixed salad greens", 100)])] + for back in (2, 1, 0): + for meal, at, items in menu: + if back == 0 and meal == "dinner": + continue + for q, g in items: + ref = food(q) + if ref: + c.call("/food/api/entry", {"day": day(-back), "time": at, "meal": meal, "food": ref, + "amount": round(g * random.uniform(.9, 1.1)), "unit": "g", "note": ""}) + # cycle: three periods + for start in (-58, -30, -2): + for i in range(5): + if start + i <= 0: + c.call("/cycle/api/day", {"day": day(start + i), "period": True, "flow": [3, 4, 3, 2, 1][i]}) + # work: two customers, projects, a week of entries + node = lambda d: c.call("/work/api/node", d)["id"] + acme = node({"kind": "client", "name": "Acme Corp", "billable": True, "currency": "EUR"}) + shop = node({"kind": "project", "name": "Web shop", "parent_id": acme}) + api = node({"kind": "project", "name": "Mobile API", "parent_id": acme}) + north = node({"kind": "client", "name": "Northwind", "billable": True}) + audit = node({"kind": "project", "name": "Security audit", "parent_id": north}) + own = node({"kind": "client", "name": "Internal", "billable": False}) + for n in range(monday, 1): + if n < 0 or n == 0: + plan = [(shop, "08:30", "12:00"), (api, "13:00", "15:30"), (audit, "15:45", "17:30")] if n % 2 else \ + [(audit, "09:00", "11:30"), (own, "11:30", "12:15"), (shop, "13:00", "17:00")] + for nid, a, b in plan: + if n == 0 and int(b[:2]) > NOW.hour: + continue + c.call("/work/api/entry", {"node_id": nid, "date": day(n), "start": a, "end": b, + "billable": nid != own, "note": ""}) + # notes + for folder, text, pinned in [ + ("", "# Shopping\n- [x] milk\n- [ ] coffee beans\n- [ ] olive oil\n- [ ] #home light bulbs", True), + ("Work", "# Sprint 14 ideas\nSync the weather places to the app. Faster cold start. #ideas", False), + ("Work", "# Release checklist\n1. Tests green\n2. Changelog\n3. Tag + publish the APK #release", False), + ("Home", "# Wi-Fi for guests\nNetwork: *guests* — the password is on the fridge.", False), + ("", "# Books to read\n- The Pragmatic Programmer\n- Designing Data-Intensive Applications #books", False)]: + c.call("/notes/api/save", {"body": text, "folder": folder, "pinned": pinned}) + + +# ---- the pictures --------------------------------------------------------------------------------------- + +PAGES = [ # file, path, width, height, what to click first (a selector) or None, full page? + ("home", "/", 1920, 1080, None, False), + ("week", "/week", 1600, 1000, None, False), + ("weather", "/weather", 1440, 1000, None, True), + ("stations", "/stations?r=7d", 1440, 900, None, True), + ("health", "/health", 1440, 1000, None, True), + ("sleep", "/health/sleep", 1440, 1000, None, True), + ("food", "/food", 1440, 1000, None, True), + ("work", "/work", 1600, 1000, None, False), + ("activity", "/activity?d=" + (TODAY - timedelta(days=max(0, TODAY.weekday() - 4))).isoformat(), 1440, 1000, None, True), + ("notes", "/notes", 1440, 900, "text=Release checklist", False), + ("settings", "/settings#general", 1440, 1000, None, False), + ("settings-sensors", "/settings#sensors", 1440, 900, None, False), + ("phone-home", "/", 390, 844, None, False), + ("phone-food", "/food", 390, 844, None, False), +] +SCREENS = ["Home", "Temp", "Weather", "Cal"] + + +def shoot(c, out): + for name in SCREENS: # the 3.5" panel: no browser needed + with open(os.path.join(out, f"screen-{name.lower()}.png"), "wb") as f: + f.write(c.call(f"/api/screen.png?n={name}")) + try: + from playwright.sync_api import sync_playwright + except ImportError: + print("Playwright isn't installed: only the 3.5\" screens were made " + "(pip install playwright && playwright install chromium)") + return + with sync_playwright() as p: + b = p.chromium.launch() + ctx = b.new_context(device_scale_factor=1) + page = ctx.new_page() + page.goto(BASE + "/login") + page.locator("input[name=name]").fill(ADMIN[0]) + page.locator("input[type=password]").fill(ADMIN[1]) + page.keyboard.press("Enter") + page.wait_for_url(lambda u: "/login" not in u) + for name, path, w, h, click, full in PAGES: + page.set_viewport_size({"width": w, "height": h}) + page.goto(BASE + path) + page.wait_for_load_state("networkidle") + if click: + page.click(click) + page.wait_for_timeout(1500) + page.add_style_tag(content=".sound-off { display: none !important; }") + page.screenshot(path=os.path.join(out, f"{name}.png"), full_page=full) + print(" ", name) + b.close() + + +def main(): + ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + ap.add_argument("--keep", action="store_true", help="leave the demo running afterwards") + ap.add_argument("--out", default=HERE, help="where the pictures go (default: next to this script)") + a = ap.parse_args() + tmp = tempfile.mkdtemp(prefix="dash-demo-") + d = os.path.join(tmp, "dashboard") + shutil.copytree(os.path.join(REPO, "dashboard"), d, ignore=shutil.ignore_patterns("__pycache__", "dash_data", + "dash_config.json", "dash_*.json")) + os.makedirs(os.path.join(d, "dash_data", "food")) + shutil.copyfile(os.path.join(REPO, "app", "assets", "foods.db"), os.path.join(d, "dash_data", "food", "foods.db")) + srv = http.server.ThreadingHTTPServer(("127.0.0.1", 0), SensorJSON) + threading.Thread(target=srv.serve_forever, daemon=True).start() + gb_file = os.path.join(tmp, "Gadgetbridge.db") + with open(os.path.join(d, "dash_config.json"), "w") as f: + json.dump(config(srv.server_address[1], gb_file), f, indent=1) + os.chdir(d) + sensor_history(d) + activity_events(d) + gadgetbridge_export(gb_file) + print(f"demo dashboard: {d}") + log = open(os.path.join(tmp, "dash.log"), "w") + proc = subprocess.Popen([sys.executable, "dash.py", "--headless"], cwd=d, stdout=log, stderr=subprocess.STDOUT) + try: + c = Client() + for _ in range(60): + try: + urllib.request.urlopen(BASE + "/login", timeout=2) + break + except OSError: + time.sleep(0.5) + c.call("/api/users/save", {"name": ADMIN[0], "password": ADMIN[1], "role": "admin"}) # the first: logged in + fill(c) + print("band import:", c.call("/health/api/gb/import", {}).get("result")) + time.sleep(35) # the sensors' first poll, the weather, the summaries + os.makedirs(a.out, exist_ok=True) + shoot(c, a.out) + print(f"pictures in {a.out}") + if a.keep: + print(f"the demo runs at {BASE} — log in as {ADMIN[0]} / {ADMIN[1]}; Ctrl+C stops it") + proc.wait() + except KeyboardInterrupt: + pass + finally: + proc.terminate() + proc.wait() + srv.shutdown() + if not a.keep: + shutil.rmtree(tmp, ignore_errors=True) + + +if __name__ == "__main__": + main() diff --git a/docs/screenshots/notes.png b/docs/screenshots/notes.png new file mode 100644 index 0000000..9fe5269 Binary files /dev/null and b/docs/screenshots/notes.png differ diff --git a/docs/screenshots/phone-food.png b/docs/screenshots/phone-food.png new file mode 100644 index 0000000..d9d0075 Binary files /dev/null and b/docs/screenshots/phone-food.png differ diff --git a/docs/screenshots/phone-home.png b/docs/screenshots/phone-home.png new file mode 100644 index 0000000..9c6b333 Binary files /dev/null and b/docs/screenshots/phone-home.png differ diff --git a/docs/screenshots/screen-cal.png b/docs/screenshots/screen-cal.png new file mode 100644 index 0000000..9fc003f Binary files /dev/null and b/docs/screenshots/screen-cal.png differ diff --git a/docs/screenshots/screen-home.png b/docs/screenshots/screen-home.png new file mode 100644 index 0000000..507bcaf Binary files /dev/null and b/docs/screenshots/screen-home.png differ diff --git a/docs/screenshots/screen-temp.png b/docs/screenshots/screen-temp.png new file mode 100644 index 0000000..2396a30 Binary files /dev/null and b/docs/screenshots/screen-temp.png differ diff --git a/docs/screenshots/screen-weather.png b/docs/screenshots/screen-weather.png new file mode 100644 index 0000000..b436f51 Binary files /dev/null and b/docs/screenshots/screen-weather.png differ diff --git a/docs/screenshots/settings-sensors.png b/docs/screenshots/settings-sensors.png new file mode 100644 index 0000000..2fc0da8 Binary files /dev/null and b/docs/screenshots/settings-sensors.png differ diff --git a/docs/screenshots/settings.png b/docs/screenshots/settings.png new file mode 100644 index 0000000..57d5dad Binary files /dev/null and b/docs/screenshots/settings.png differ diff --git a/docs/screenshots/sleep.png b/docs/screenshots/sleep.png new file mode 100644 index 0000000..e7e8af9 Binary files /dev/null and b/docs/screenshots/sleep.png differ diff --git a/docs/screenshots/stations.png b/docs/screenshots/stations.png new file mode 100644 index 0000000..3f1d824 Binary files /dev/null and b/docs/screenshots/stations.png differ diff --git a/docs/screenshots/weather.png b/docs/screenshots/weather.png new file mode 100644 index 0000000..5d1098b Binary files /dev/null and b/docs/screenshots/weather.png differ diff --git a/docs/screenshots/week.png b/docs/screenshots/week.png new file mode 100644 index 0000000..e449528 Binary files /dev/null and b/docs/screenshots/week.png differ diff --git a/docs/screenshots/work.png b/docs/screenshots/work.png new file mode 100644 index 0000000..60dedd8 Binary files /dev/null and b/docs/screenshots/work.png differ diff --git a/docs/server.md b/docs/server.md new file mode 100644 index 0000000..0252e47 --- /dev/null +++ b/docs/server.md @@ -0,0 +1,101 @@ +# The sync server + +A mailbox: devices send it encrypted batches of changes and read each other's. It stores them in order and +can't read them, because the key never leaves the devices. Plain PHP + SQLite, no daemon. The protocol is +in [server/PROTOCOL.md](../server/PROTOCOL.md). + +``` +server/public/index.php the API (the only thing the web server serves) +server/public/.htaccess Apache rewrite +server/src/db.php storage (one SQLite file) +server/src/food.php the optional food search +server/bin/admin.php accounts + device tokens (command line) +server/bin/setup-server.sh one-time setup for Apache + certbot +server/config.example.php → config.php +``` + +**Needs:** PHP 8.1+ with `pdo_sqlite` (Debian: `php-sqlite3`), HTTPS, and its own (sub)domain, which is +simplest. + +## Quick setup (Debian/Ubuntu + Apache + certbot) + +```bash +sudo apt install apache2 libapache2-mod-php php-sqlite3 certbot python3-certbot-apache rsync +sudo rsync -a server/ /srv/dash-sync/ # anywhere, but NOT inside another site's folder +sudo bash /srv/dash-sync/bin/setup-server.sh sync.example.com me +``` + +It creates `data/` (owned by the web server, mode 700), turns on Apache's `mod_rewrite`, an Apache site for `sync.example.com` with +`DocumentRoot /srv/dash-sync/public`, and a Let's Encrypt certificate. Then it creates the account `me` and +its first device, `dashboard`, and prints that device's **token once**. Paste it into the dashboard's +Settings ▸ General ▸ Sync. That's all the server needs: phones and other dashboards get their tokens from the +dashboard (Settings ▸ General ▸ Devices ▸ Add a device, as a QR code). Running the script again is safe. + +> Keep the folder out of other sites' document roots. Only `public/` may be reachable from the web. +> `data/sync.db` holds the token hashes and the wrapped key. + +## By hand (nginx, another layout) + +1. Copy `server/` anywhere, e.g. `/srv/dash-sync`. +2. `cp config.example.php config.php`, then `mkdir data && sudo chown www-data: data && chmod 700 data`. +3. Web server, with the document root at `public/`: + ```nginx + server { + server_name sync.example.com; + root /srv/dash-sync/public; + client_max_body_size 9m; + location / { try_files $uri /index.php$is_args$args; } + location = /index.php { + include snippets/fastcgi-php.conf; + fastcgi_pass unix:/run/php/php8.2-fpm.sock; # your PHP version + } + # + the TLS lines certbot adds + } + ``` + Under a path instead of a subdomain: set `'base_path' => '/dash-sync'` in `config.php`. +4. The account and its first device (as the web server's user, so it owns the database): + ```bash + sudo -u www-data php bin/admin.php add-account me + sudo -u www-data php bin/admin.php add-device me dashboard # prints its token once + ``` + The rest come from the dashboard's Settings ▸ General ▸ Devices. +5. Check: `curl -H "Authorization: Bearer " https://sync.example.com/v1/hello`. + +## config.php + +| Key | Default | What | +|---|---|---| +| `db` | `data/sync.db` | The database | +| `base_path` | `''` | URL prefix when not at the root | +| `max_batch_bytes` | 8 MB | One batch (also mind PHP's `post_max_size`) | +| `max_account_bytes` | 1 GB | All of an account's batches (`0` = no limit) → `507` when full | +| `max_answer_bytes` | 32 MB | Batches per download answer; clients just ask again | +| `key_replace_any` | `false` | `true`: any device may change the passphrase, not only the one that set the key | +| `app_dir` | `app/` | The phone app's published builds ([app.md](app.md)) | +| `food_db` | `food/off-archive.db` | The food search archive (below) | +| `food_home` | `[]` | Food search: these countries' products rank first, e.g. `['germany', 'austria']` | + +## Day to day + +- Devices: the dashboard that set up the key manages them in Settings ▸ General ▸ Devices (add, revoke). The + same on the server: `php bin/admin.php list`, `revoke me phone`. For a stolen, unlocked phone, also change + the passphrase (Settings ▸ General ▸ Sync on that dashboard). +- `php bin/admin.php stats`: batches and size per account. +- **Back up** `data/sync.db`. It's useless without the key, and every device has all the data anyway. +- Batches aren't pruned yet. Normal use stays in the tens of MB a year. + +## Optional: the food search archive + +`GET /v1/food/search` searches every Open Food Facts product. Build the archive on any computer from +[the OFF export](https://static.openfoodfacts.org/data/en.openfoodfacts.org.products.csv.gz) (~1 GB, ~10 min) +and upload it: + +```bash +cd dashboard +FOOD_COUNTRIES=germany python3 plugins/food/off.py --archive en.openfoodfacts.org.products.csv.gz /tmp/off-archive.db +rsync -t /tmp/off-archive.db you@host:/srv/dash-sync/food/off-archive.db.new +ssh you@host 'mv /srv/dash-sync/food/off-archive.db.new /srv/dash-sync/food/off-archive.db' +``` + +The data is under the ODbL ([NOTICE.md](../NOTICE.md)). Serving it to your own devices is fine. If you open +the search to others, credit Open Food Facts. diff --git a/docs/testing.md b/docs/testing.md new file mode 100644 index 0000000..2657e50 --- /dev/null +++ b/docs/testing.md @@ -0,0 +1,31 @@ +# Testing + +What there is, and what to run before a release. The dashboard has no unit tests yet (see the issues); +these are end-to-end checks against clean machines, plus the app's tests. + +| Check | Command | Needs | Takes | +|---|---|---|---| +| Dashboard from scratch on Debian 12 and 13: `install.sh`, every plugin on, every page answers, the food search works, a foreign `Host` is refused, no tracebacks | `tests/clean-install.sh` | Docker | ~3 min | +| Sync server from scratch: `bin/setup-server.sh` with Apache, the printed token works, no token → 401, `data/` not reachable; 88 requests at once (uploads, new devices, reads) all succeed and are all kept | `tests/server-setup.sh` (`--keep` leaves it running on :18080) | Docker | ~1 min | +| The phone app: unit and widget tests, static analysis | `cd app && flutter test && flutter analyze` | Flutter 3.44 | ~1 min | +| Python, PHP and JS at least parse | `python3 -m compileall -q dashboard && php -l server/public/index.php && for f in dashboard/static/*.js dashboard/plugins/*/static/*.js; do node --check "$f"; done` | PHP, Node | seconds | +| The README's screenshots, from a demo dashboard full of made-up data: a quick look at every page | `python3 docs/screenshots/make.py` (`--keep` leaves the demo running on :8199) | Playwright | ~2 min | +| The app's screenshots, which also exercise the whole chain: demo dashboard → server → a fresh app connecting, syncing and showing every section | `tests/server-setup.sh --keep`, `make.py --keep`, then `python3 docs/screenshots/app.py --token ` | an Android emulator (a Pixel-sized AVD), Flutter | ~5 min | + +## By hand, before a release + +- **Sync end to end:** `tests/server-setup.sh --keep`, then a dashboard (e.g. `make.py --keep`, or one + started from `dashboard/`) ▸ Settings ▸ General ▸ Sync: server `http://127.0.0.1:18080`, the printed + token, a passphrase. Note the recovery key, then Devices ▸ Add a device ▸ a phone. A second dashboard + joins with another device token and the passphrase; a change on one shows on the other after "Sync now". +- **The 3.5" screen:** on a Pi with the panel, the service log's `screen:` line names it + (`journalctl -u dashboard | grep screen`). Without one, Settings ▸ General ▸ Screen shows what it would + draw (`/api/screen.png?n=Home`). +- **The app:** a release APK on a phone. Connect by QR, sync, weather with and without places. + +## Not covered + +- The dashboard's Python logic in isolation (the sync merge, auth, settings validation): no unit tests. +- ARM: the checks run on x86-64 Debian. The Pi's Raspberry Pi OS is the same Debian with the same + packages, but it isn't run here. +- iOS: the app is Android only. diff --git a/server/.gitignore b/server/.gitignore new file mode 100644 index 0000000..b31f47c --- /dev/null +++ b/server/.gitignore @@ -0,0 +1,8 @@ +config.php +data/ +app/ + +# Syncthing, if you sync the source between computers +.stignore +.stfolder +food/ diff --git a/server/PROTOCOL.md b/server/PROTOCOL.md new file mode 100644 index 0000000..9bba712 --- /dev/null +++ b/server/PROTOCOL.md @@ -0,0 +1,109 @@ +# dash-sync protocol, version 1 + +How the dashboard and the app keep their own copies of the data in step through this +server. The server is a mailbox: it stores encrypted batches in order and hands them out; it can't +read them and never merges anything. Every device does the merging itself, the same way. + +Reference implementation: `dashboard/sync.py` (client) + `dashboard/syncdb.py` (stamps and merging). + +## Devices, accounts, tokens + +- An **account** is one person's data (e.g. `me`). A **device** belongs to one account and has a + name (`dashboard`, `phone`) and a secret **token** (`php bin/admin.php add-device me phone`). +- Every request: `Authorization: Bearer `, over HTTPS. +- Each device also makes itself a random **device id** (12 hex characters) when it first starts. + It goes into every change it makes (`d`) and every batch (`dev`); it is not the server's device name. + +## HTTP + +| Request | Answer | +|---|---| +| `GET /v1/hello` | `{"account", "device", "latest", "server": "dash-sync/1"}` — `device` = the server's name for you | +| `GET /v1/key` | the wrapped data key (JSON below); `404` until the first device sets it | +| `PUT /v1/key` | store it; `409` if there is one — `PUT /v1/key?replace=1` to change the passphrase (only the device that set it: `403` otherwise; the old one is kept on the server) | +| `POST /v1/batches` | body = one encrypted batch (`application/octet-stream`, ≤ 8 MB) → `{"seq"}`; `507` when the account is full | +| `GET /v1/batches?after=N&limit=50` | `{"batches": [{"seq", "device", "at", "size", "blob"}], "latest"}`, oldest first, `blob` base64; fewer than `limit` when they're big (≤ 32 MB an answer): ask again until empty | +| `GET /v1/devices` | `{"devices": [{"name", "created", "last_seen", "revoked", "you", "manager"}], "manager"}` — `manager` = the device that set the key (it may manage the others) | +| `POST /v1/devices` | `{"name"}` → `{"name", "token"}`, the new device's token, shown once; the managing device only (`403`), `409` = name taken (a revoked one is reused) | +| `POST /v1/devices/revoke` | `{"name"}` → its token stops working; the managing device only, not itself | +| `GET /v1/app` | the newest phone app build `{"version", "build", "size", "sha256", "published", "notes"}`, 404 = none | +| `GET /v1/app/apk` | that APK (`application/vnd.android.package-archive`); uploaded over SSH by `app/tool/publish.sh` | +| `GET /v1/food/search?q=…` | `{"items": [food]}` from the Open Food Facts archive — `q` (every word a prefix of the name / brand / category, ≥ 3 letters unless a filter is given), `brand`, `country` (a name or `ro` / `sk` / `de` …), `category`, `nutriscore` (`a`, `ab` …), `barcode` (exact; merged duplicates' barcodes too), `limit` ≤ 50. A food = the dashboard's shape (`ref` "usda:ID", `kind` "off", `per100`, `portions` [{label, grams}], brand, barcode, countries, nutriscore, nova, allergens, labels, ingredients) + the added-sugar facts `sugars_in`, `dairy`, `added_sugar` (the clients' sugar.py / sugar.dart decide). Not account data: any device may search | +| `GET /v1/food/info` | `{"products", "built", "source"}`; 404 = no archive uploaded (`food/off-archive.db`, built by the dashboard's `plugins/food/off.py --archive`) | + +Errors: `{"error": "…"}` with 400 / 401 / 403 / 404 / 409 / 413 / 500 / 507. + +## Keys + +- **Data key**: 32 random bytes, made once by the first device. Everything is encrypted with it. + Devices keep it locally (the Pi: `dash_data/sync/state.json`, chmod 600; the app: the platform's + secure storage). +- **Wrapped key** (on the server, so a new device can join with the passphrase): + + ```json + {"v": 1, "kdf": "argon2id13", "ops": 3, "mem": 67108864, + "salt": "<16 bytes, base64>", "nonce": "<24 bytes, base64>", "box": ""} + ``` + `kek = Argon2id(passphrase UTF-8, salt, opslimit=ops, memlimit=mem, 32 bytes)` (libsodium + `crypto_pwhash`, ALG_ARGON2ID13); `box = XChaCha20-Poly1305-IETF(kek, nonce, data key, ad = "dash-sync/key/1")`. + Optional `"check"`: a sealed batch-format blob (`"DS1\0"` + nonce + ciphertext) of the bytes `ok` under the data key with + ad = `"dash-sync/key-check/1"` (base64) — lets a device test a recovery key without the passphrase. Wrapped keys + made before it have none; a device writing the key adds it. +- **Recovery key**: the data key itself in base32 (RFC 4648, no padding), in groups of 4 with + dashes. With it a device can wrap the key again under a new passphrase. + +## A batch + +On the wire: `"DS1\0"` (4 bytes) + nonce (24 random bytes) + +`XChaCha20-Poly1305-IETF(data key, nonce, plaintext, ad = "dash-sync/1/")`. + +Plaintext = zlib (deflate, RFC 1950) of UTF-8 JSON: + +```json +{"v": 1, "dev": "aa5403e5376a", "made": 1792482314874, "changes": [ + {"t": "food.entry", "u": "91019d2e…", "h": 1792482314899, "d": "aa5403e5376a", + "row": {"day": "2026-10-20", "meal": "snack", "name": "Apple", "kcal": 60, "my_food_id": "0aef8cce…", …}}, + {"t": "food.entry", "u": "91019d2e…", "h": 1792482314917, "d": "aa5403e5376a", "del": true} +]} +``` + +- `t` = `.`; `u` = the row's id (`_uid`); `h` = its change stamp (`_hlc`); `d` = the device that made the change. +- `row` = every column but the local integer id; foreign keys (`refs`) and ids inside text + (`refs_in`, e.g. `"my:~"` in a meal's recipe) are already ids — see each plugin's + `META["sync"]` for which columns. Columns a device doesn't know are ignored. +- At most 2000 changes a batch; a device sends its changes since its last send, in stamp order. + +## Merging (every device, the same rules) + +- **Stamps** (`h`): milliseconds since 1970, but each new local stamp = max(now, last stamp + 1), + and on receiving, the local clock moves up to the highest stamp seen. So stamps keep their order + even if a device's clock is off. +- **Last change wins**, per row: apply a change only if `(h, d)` is greater than the local row's + `(_hlc, _dev)` (compare `h` first, then `d` as text). Otherwise skip it. +- **Deletes** (`del`): keep a marker (table, id, h, d). Delete the local row if the marker wins over + it. A row change that doesn't win over a marker for its id is skipped (it was deleted later + elsewhere); a newer one brings the row back. +- **Order inside a batch**: tables in the order the plugin lists them; rows whose reference (a + parent node, a meal's ingredient) isn't there yet wait for another round; then the deletes. +- **Natural ids**: some rows have an id made from what they are (`day:2026-10-07`, + `measure:2026-10-17`, `src:`, `:` for rates) so two devices making + "the same" row agree on it. +- **Reading**: page through `GET /v1/batches?after=` until it's empty; skip + batches your own device sent (`dev`); remember the last `seq` only after a batch is applied + (applying again is harmless). + +## What syncs (dashboard v1) + +| Table | Id | +|---|---| +| `food.food` (My foods + meals) | random | +| `food.entry` (the diary) | `src:` for imports, else random | +| `cycle.day` | `day:` | +| `health.measure` | `measure:` | +| `health.vital` | `vital: