diff --git a/filcnaplo_desktop_ui/LICENSE b/filcnaplo_desktop_ui/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/filcnaplo_desktop_ui/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/filcnaplo_desktop_ui/README.md b/filcnaplo_desktop_ui/README.md new file mode 100644 index 0000000..e69de29 diff --git a/filcnaplo_desktop_ui/analysis_options.yaml b/filcnaplo_desktop_ui/analysis_options.yaml new file mode 100644 index 0000000..fd16f92 --- /dev/null +++ b/filcnaplo_desktop_ui/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-lang.github.io/linter/lints/index.html. + # + # 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/filcnaplo_desktop_ui/lib/common/filter_bar.dart b/filcnaplo_desktop_ui/lib/common/filter_bar.dart new file mode 100644 index 0000000..c9ed6d9 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/common/filter_bar.dart @@ -0,0 +1,85 @@ +import 'package:filcnaplo/theme/colors/colors.dart'; +import 'package:flutter/material.dart'; + +class FilterBar extends StatelessWidget implements PreferredSizeWidget { + const FilterBar({ + Key? key, + required this.items, + required this.controller, + this.onTap, + this.padding = const EdgeInsets.symmetric(horizontal: 24.0), + this.disableFading = false, + this.scrollable = true, + }) : assert(items.length == controller.length), + super(key: key); + + final List items; + final TabController controller; + final EdgeInsetsGeometry padding; + final Function(int)? onTap; + @override + final Size preferredSize = const Size.fromHeight(42.0); + final bool disableFading; + final bool scrollable; + + @override + Widget build(BuildContext context) { + final tabbar = TabBar( + controller: controller, + isScrollable: scrollable, + physics: const BouncingScrollPhysics(), + // Label + labelStyle: Theme.of(context).textTheme.titleMedium!.copyWith( + fontWeight: FontWeight.w600, + fontSize: 15.0, + ), + labelPadding: const EdgeInsets.symmetric(horizontal: 12, vertical: 3), + labelColor: Theme.of(context).colorScheme.secondary, + unselectedLabelColor: AppColors.of(context).text.withOpacity(0.65), + // Indicator + indicatorPadding: const EdgeInsets.symmetric(vertical: 8), + indicator: BoxDecoration( + color: Theme.of(context).colorScheme.secondary.withOpacity(0.25), + borderRadius: BorderRadius.circular(45.0), + ), + overlayColor: MaterialStateProperty.all(const Color(0x00000000)), + // Tabs + padding: EdgeInsets.zero, + tabs: items, + onTap: onTap, + ); + + return Container( + width: MediaQuery.of(context).size.width, + height: 48.0, + padding: padding, + child: disableFading + ? tabbar + : AnimatedBuilder( + animation: controller.animation!, + builder: (ctx, child) { + // avoid fading over selected tab + return ShaderMask( + shaderCallback: (Rect bounds) { + final Color bg = Theme.of(context).scaffoldBackgroundColor; + final double index = controller.animation!.value; + return LinearGradient(begin: Alignment.topLeft, end: Alignment.bottomRight, colors: [ + index < 0.2 ? Colors.transparent : bg, + Colors.transparent, + Colors.transparent, + index > controller.length - 1.2 ? Colors.transparent : bg + ], stops: const [ + 0, + 0.1, + 0.9, + 1 + ]).createShader(bounds); + }, + blendMode: BlendMode.dstOut, + child: child); + }, + child: tabbar, + ), + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/common/panel_button.dart b/filcnaplo_desktop_ui/lib/common/panel_button.dart new file mode 100644 index 0000000..6cc664e --- /dev/null +++ b/filcnaplo_desktop_ui/lib/common/panel_button.dart @@ -0,0 +1,66 @@ +import 'package:filcnaplo/theme/colors/colors.dart'; +import 'package:flutter/material.dart'; + +class PanelButton extends StatelessWidget { + const PanelButton({ + Key? key, + this.onPressed, + this.padding = const EdgeInsets.symmetric(horizontal: 14.0), + this.leading, + this.title, + this.trailing, + this.trailingDivider = false, + }) : super(key: key); + + final void Function()? onPressed; + final EdgeInsetsGeometry padding; + final Widget? leading; + final Widget? title; + final Widget? trailing; + final bool trailingDivider; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0), + child: RawMaterialButton( + onPressed: onPressed, + padding: padding, + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)), + child: ListTile( + leading: leading != null + ? Theme( + data: Theme.of(context).copyWith(iconTheme: IconThemeData(color: Theme.of(context).colorScheme.secondary)), + child: leading!, + ) + : null, + trailing: trailingDivider + ? Row( + mainAxisSize: MainAxisSize.min, + children: [ + Container( + margin: const EdgeInsets.only(right: 6.0), + width: 2.0, + height: 32.0, + decoration: BoxDecoration( + color: AppColors.of(context).text.withOpacity(.15), + borderRadius: BorderRadius.circular(45.0), + ), + ), + if (trailing != null) trailing!, + ], + ) + : trailing, + title: title != null + ? DefaultTextStyle( + style: Theme.of(context).textTheme.titleMedium!.copyWith(fontWeight: FontWeight.w600, fontSize: 14.0), + child: title!, + ) + : null, + contentPadding: EdgeInsets.zero, + visualDensity: VisualDensity.compact, + ), + ), + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/common/profile_image.dart b/filcnaplo_desktop_ui/lib/common/profile_image.dart new file mode 100644 index 0000000..cb1dbf9 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/common/profile_image.dart @@ -0,0 +1,75 @@ +import 'package:filcnaplo/models/user.dart'; +import 'package:filcnaplo/utils/color.dart'; +import 'package:flutter/material.dart'; +import 'package:filcnaplo/theme/colors/colors.dart'; + +class ProfileImage extends StatelessWidget { + const ProfileImage({ + Key? key, + this.name, + this.radius = 20.0, + this.role = Role.student, + this.backgroundColor, + }) : super(key: key); + + final String? name; + final double radius; + final Role? role; + final Color? backgroundColor; + + @override + Widget build(BuildContext context) { + Color color = ColorUtils.foregroundColor(backgroundColor ?? Theme.of(context).scaffoldBackgroundColor); + Color roleColor; + + if (Theme.of(context).brightness == Brightness.light) { + roleColor = const Color(0xFF444444); + } else { + roleColor = const Color(0xFF555555); + } + + return Stack( + alignment: Alignment.center, + children: [ + Material( + clipBehavior: Clip.hardEdge, + shape: const CircleBorder(), + color: backgroundColor ?? AppColors.of(context).text.withOpacity(.15), + child: InkWell( + child: AnimatedContainer( + duration: const Duration(milliseconds: 200), + height: radius * 2, + width: radius * 2, + decoration: const BoxDecoration( + shape: BoxShape.circle, + ), + child: name != null && (name?.trim().length ?? 0) > 0 + ? Center( + child: Text( + (name?.trim().length ?? 0) > 0 ? (name ?? "?").trim()[0] : "?", + style: TextStyle( + color: color, + fontWeight: FontWeight.w600, + fontSize: 18.0 * (radius / 20.0), + ), + ), + ) + : Container(), + ), + ), + ), + + // Role indicator + if (role == Role.parent) + SizedBox( + height: radius * 2, + width: radius * 2, + child: Container( + alignment: Alignment.bottomRight, + child: Icon(Icons.shield, color: roleColor, size: radius / 1.3), + ), + ), + ], + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/common/widgets/grade/grade_viewable.dart b/filcnaplo_desktop_ui/lib/common/widgets/grade/grade_viewable.dart new file mode 100644 index 0000000..7b5b603 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/common/widgets/grade/grade_viewable.dart @@ -0,0 +1,14 @@ +import 'package:flutter/material.dart'; +import 'package:filcnaplo_kreta_api/models/grade.dart'; +import 'package:filcnaplo/ui/widgets/grade/grade_tile.dart'; + +class GradeViewable extends StatelessWidget { + const GradeViewable(this.grade, {Key? key}) : super(key: key); + + final Grade grade; + + @override + Widget build(BuildContext context) { + return GradeTile(grade); + } +} \ No newline at end of file diff --git a/filcnaplo_desktop_ui/lib/common/widgets/lesson/lesson_viewable.dart b/filcnaplo_desktop_ui/lib/common/widgets/lesson/lesson_viewable.dart new file mode 100644 index 0000000..540cd9e --- /dev/null +++ b/filcnaplo_desktop_ui/lib/common/widgets/lesson/lesson_viewable.dart @@ -0,0 +1,19 @@ +import 'package:filcnaplo_kreta_api/models/lesson.dart'; +import 'package:filcnaplo/ui/widgets/lesson/lesson_tile.dart'; +import 'package:flutter/material.dart'; + +class LessonViewable extends StatelessWidget { + const LessonViewable(this.lesson, {Key? key, this.swapDesc = false}) : super(key: key); + + final Lesson lesson; + final bool swapDesc; + + @override + Widget build(BuildContext context) { + final tile = LessonTile(lesson, swapDesc: swapDesc); + + if (lesson.subject.id == '' || tile.lesson.isEmpty) return tile; + + return tile; + } +} diff --git a/filcnaplo_desktop_ui/lib/pages/absences/absences_page.dart b/filcnaplo_desktop_ui/lib/pages/absences/absences_page.dart new file mode 100644 index 0000000..fb02250 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/absences/absences_page.dart @@ -0,0 +1,362 @@ +import 'dart:math'; + +import 'package:animations/animations.dart'; +import 'package:auto_size_text/auto_size_text.dart'; +import 'package:filcnaplo/api/providers/update_provider.dart'; +import 'package:filcnaplo/ui/date_widget.dart'; +import 'package:filcnaplo_kreta_api/models/absence.dart'; +import 'package:filcnaplo_kreta_api/models/lesson.dart'; +import 'package:filcnaplo_kreta_api/models/subject.dart'; +import 'package:filcnaplo_kreta_api/models/week.dart'; +import 'package:filcnaplo_kreta_api/providers/absence_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/note_provider.dart'; +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/theme/colors/colors.dart'; +import 'package:filcnaplo_kreta_api/providers/timetable_provider.dart'; +import 'package:filcnaplo_mobile_ui/common/action_button.dart'; +import 'package:filcnaplo_mobile_ui/common/empty.dart'; +import 'package:filcnaplo_mobile_ui/common/filter_bar.dart'; +import 'package:filcnaplo_mobile_ui/common/panel/panel.dart'; +import 'package:filcnaplo_mobile_ui/common/widgets/absence/absence_subject_tile.dart'; +import 'package:filcnaplo_mobile_ui/common/widgets/absence/absence_viewable.dart'; +import 'package:filcnaplo_mobile_ui/common/widgets/statistics_tile.dart'; +import 'package:filcnaplo_mobile_ui/common/widgets/miss_tile.dart'; +import 'package:filcnaplo_mobile_ui/pages/absences/absence_subject_view.dart'; +import 'package:filcnaplo/ui/filter/sort.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_feather_icons/flutter_feather_icons.dart'; +import 'package:provider/provider.dart'; +import 'absences_page.i18n.dart'; + +enum AbsenceFilter { absences, delays, misses } + +class SubjectAbsence { + Subject subject; + List absences; + double percentage; + + SubjectAbsence({required this.subject, this.absences = const [], this.percentage = 0.0}); +} + +class AbsencesPage extends StatefulWidget { + const AbsencesPage({Key? key}) : super(key: key); + + @override + _AbsencesPageState createState() => _AbsencesPageState(); +} + +class _AbsencesPageState extends State with TickerProviderStateMixin { + late UserProvider user; + late AbsenceProvider absenceProvider; + late TimetableProvider timetableProvider; + late NoteProvider noteProvider; + late UpdateProvider updateProvider; + late String firstName; + late TabController _tabController; + late List absences = []; + final Map _lessonCount = {}; + + @override + void initState() { + super.initState(); + + _tabController = TabController(length: 3, vsync: this); + timetableProvider = Provider.of(context, listen: false); + + WidgetsBinding.instance.addPostFrameCallback((timeStamp) async { + for (final lesson in timetableProvider.getWeek(Week.current()) ?? []) { + if (!lesson.isEmpty && lesson.subject.id != '' && lesson.lessonYearIndex != null) { + _lessonCount.update( + lesson.subject, + (value) { + if (lesson.lessonYearIndex! > value.lessonYearIndex!) { + return lesson; + } else { + return value; + } + }, + ifAbsent: () => lesson, + ); + } + } + }); + } + + void buildSubjectAbsences() { + Map _absences = {}; + + for (final absence in absenceProvider.absences) { + if (absence.delay != 0) continue; + + if (!_absences.containsKey(absence.subject)) { + _absences[absence.subject] = SubjectAbsence(subject: absence.subject, absences: [absence]); + } else { + _absences[absence.subject]?.absences.add(absence); + } + } + + _absences.forEach((subject, absence) { + final absentLessonsOfSubject = absenceProvider.absences.where((e) => e.subject == subject && e.delay == 0).length; + final totalLessonsOfSubject = _lessonCount[subject]?.lessonYearIndex ?? 0; + + double absentLessonsOfSubjectPercentage; + + if (absentLessonsOfSubject <= totalLessonsOfSubject) { + absentLessonsOfSubjectPercentage = absentLessonsOfSubject / totalLessonsOfSubject * 100; + } else { + absentLessonsOfSubjectPercentage = -1; + } + + _absences[subject]?.percentage = absentLessonsOfSubjectPercentage.clamp(-1, 100.0); + }); + + absences = _absences.values.toList(); + absences.sort((a, b) => -a.percentage.compareTo(b.percentage)); + } + + @override + Widget build(BuildContext context) { + user = Provider.of(context); + absenceProvider = Provider.of(context); + noteProvider = Provider.of(context); + updateProvider = Provider.of(context); + timetableProvider = Provider.of(context); + + List nameParts = user.displayName?.split(" ") ?? ["?"]; + firstName = nameParts.length > 1 ? nameParts[1] : nameParts[0]; + + buildSubjectAbsences(); + + return Scaffold( + body: Padding( + padding: const EdgeInsets.only(top: 12.0), + child: NestedScrollView( + physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()), + headerSliverBuilder: (context, _) => [ + SliverAppBar( + pinned: true, + floating: false, + snap: false, + centerTitle: false, + automaticallyImplyLeading: false, + shadowColor: Theme.of(context).shadowColor, + surfaceTintColor: Theme.of(context).scaffoldBackgroundColor, + title: Padding( + padding: const EdgeInsets.only(left: 8.0), + child: Text( + "Absences".i18n, + style: TextStyle(color: AppColors.of(context).text, fontSize: 32.0, fontWeight: FontWeight.bold), + ), + ), + bottom: FilterBar(items: [ + Tab(text: "Absences".i18n), + Tab(text: "Delays".i18n), + Tab(text: "Misses".i18n), + ], controller: _tabController, disableFading: true), + ), + ], + body: TabBarView( + physics: const BouncingScrollPhysics(), + controller: _tabController, + children: List.generate(3, (index) => filterViewBuilder(context, index))), + ), + ), + ); + } + + List getFilterWidgets(AbsenceFilter activeData) { + List items = []; + switch (activeData) { + case AbsenceFilter.absences: + for (var a in absences) { + items.add(DateWidget( + date: DateTime.fromMillisecondsSinceEpoch(0), + widget: AbsenceSubjectTile( + a.subject, + percentage: a.percentage, + excused: a.absences.where((a) => a.state == Justification.excused).length, + unexcused: a.absences.where((a) => a.state == Justification.unexcused).length, + pending: a.absences.where((a) => a.state == Justification.pending).length, + onTap: () => AbsenceSubjectView.show(a.subject, a.absences, context: context), + ), + )); + } + break; + case AbsenceFilter.delays: + for (var absence in absenceProvider.absences) { + if (absence.delay != 0) { + items.add(DateWidget( + date: absence.date, + widget: AbsenceViewable(absence, padding: EdgeInsets.zero), + )); + } + } + break; + case AbsenceFilter.misses: + for (var note in noteProvider.notes) { + if (note.type?.name == "HaziFeladatHiany" || note.type?.name == "Felszereleshiany") { + items.add(DateWidget( + date: note.date, + widget: MissTile(note), + )); + } + } + break; + } + return items; + } + + Widget filterViewBuilder(context, int activeData) { + List filterWidgets = []; + + if (activeData > 0) { + filterWidgets = sortDateWidgets( + context, + dateWidgets: getFilterWidgets(AbsenceFilter.values[activeData]), + padding: EdgeInsets.zero, + hasShadow: true, + ); + } else { + filterWidgets = [ + Padding( + padding: const EdgeInsets.only(bottom: 24.0), + child: Panel( + title: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("Subjects".i18n), + Padding( + padding: const EdgeInsets.only(right: 4.0), + child: IconButton( + onPressed: () { + showDialog( + context: context, + builder: (context) => AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)), + title: Text("attention".i18n), + content: Text("attention_body".i18n), + actions: [ActionButton(label: "Ok", onTap: () => Navigator.of(context).pop())], + ), + ); + }, + padding: EdgeInsets.zero, + splashRadius: 24.0, + visualDensity: VisualDensity.compact, + constraints: BoxConstraints.tight(const Size(42.0, 42.0)), + icon: const Icon(FeatherIcons.info), + ), + ), + ], + ), + child: PageTransitionSwitcher( + transitionBuilder: ( + Widget child, + Animation primaryAnimation, + Animation secondaryAnimation, + ) { + return FadeThroughTransition( + child: child, + animation: primaryAnimation, + secondaryAnimation: secondaryAnimation, + fillColor: Theme.of(context).colorScheme.background, + ); + }, + child: Column( + children: getFilterWidgets(AbsenceFilter.values[activeData]).map((e) => e.widget).cast().toList(), + ), + ), + ), + ) + ]; + } + + return Padding( + padding: const EdgeInsets.only(top: 12.0), + child: RefreshIndicator( + color: Theme.of(context).colorScheme.secondary, + onRefresh: () async { + await absenceProvider.fetch(); + await noteProvider.fetch(); + }, + child: ListView.builder( + padding: EdgeInsets.zero, + physics: const BouncingScrollPhysics(), + itemCount: max(filterWidgets.length + (activeData <= 1 ? 1 : 0), 1), + itemBuilder: (context, index) { + if (filterWidgets.isNotEmpty) { + if ((index == 0 && activeData == 1) || (index == 0 && activeData == 0)) { + int value1 = 0; + int value2 = 0; + String title1 = ""; + String title2 = ""; + String suffix = ""; + + if (activeData == AbsenceFilter.absences.index) { + value1 = absenceProvider.absences.where((e) => e.delay == 0 && e.state == Justification.excused).length; + value2 = absenceProvider.absences.where((e) => e.delay == 0 && e.state == Justification.unexcused).length; + title1 = "stat_1".i18n; + title2 = "stat_2".i18n; + suffix = " " + "hr".i18n; + } else if (activeData == AbsenceFilter.delays.index) { + value1 = absenceProvider.absences + .where((e) => e.delay != 0 && e.state == Justification.excused) + .map((e) => e.delay) + .fold(0, (a, b) => a + b); + value2 = absenceProvider.absences + .where((e) => e.delay != 0 && e.state == Justification.unexcused) + .map((e) => e.delay) + .fold(0, (a, b) => a + b); + title1 = "stat_3".i18n; + title2 = "stat_4".i18n; + suffix = " " + "min".i18n; + } + + return Padding( + padding: const EdgeInsets.only(bottom: 24.0, left: 24.0, right: 24.0), + child: Row(children: [ + Expanded( + child: StatisticsTile( + title: AutoSizeText( + title1, + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + valueSuffix: suffix, + value: value1.toDouble(), + decimal: false, + color: AppColors.of(context).green, + ), + ), + const SizedBox(width: 24.0), + Expanded( + child: StatisticsTile( + title: AutoSizeText( + title2, + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + valueSuffix: suffix, + value: value2.toDouble(), + decimal: false, + color: AppColors.of(context).red, + ), + ), + ]), + ); + } + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 6.0), + child: filterWidgets[index - (activeData <= 1 ? 1 : 0)], + ); + } else { + return Empty(subtitle: "empty".i18n); + } + }, + ), + ), + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/pages/absences/absences_page.i18n.dart b/filcnaplo_desktop_ui/lib/pages/absences/absences_page.i18n.dart new file mode 100644 index 0000000..2b37c00 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/absences/absences_page.i18n.dart @@ -0,0 +1,57 @@ +import 'package:i18n_extension/i18n_extension.dart'; + +extension ScreensLocalization on String { + static final _t = Translations.byLocale("hu_hu") + + { + "en_en": { + "Absences": "Absences", + "Delays": "Delays", + "Misses": "Misses", + "empty": "You have no absences.", + "stat_1": "Excused Absences", + "stat_2": "Unexcused Absences", + "stat_3": "Excused Delay", + "stat_4": "Unexcused Delay", + "min": "min", + "hr": "hrs", + "Subjects": "Subjects", + "attention": "Attention!", + "attention_body": "Percentage calculations are only an approximation so they may not be accurate.", + }, + "hu_hu": { + "Absences": "Hiányzások", + "Delays": "Késések", + "Misses": "Hiányok", + "empty": "Nincsenek hiányaid.", + "stat_1": "Igazolt hiányzások", + "stat_2": "Igazolatlan hiányzások", + "stat_3": "Igazolt Késés", + "stat_4": "Igazolatlan Késés", + "min": "perc", + "hr": "óra", + "Subjects": "Tantárgyak", + "attention": "Figyelem!", + "attention_body": "A százalékos számítások csak közelítések, ezért előfordulhat, hogy nem pontosak.", + }, + "de_de": { + "Absences": "Fehlen", + "Delays": "Verspätung", + "Misses": "Fehlt", + "empty": "Sie haben keine Fehlen.", + "stat_1": "Entschuldigte Fehlen", + "stat_2": "Unentschuldigte Fehlen", + "stat_3": "Entschuldigte Verspätung", + "stat_4": "Unentschuldigte Verspätung", + "min": "min", + "hr": "hrs", + "Subjects": "Fächer", + "attention": "Achtung!", + "attention_body": "Prozentberechnungen sind nur eine Annäherung und können daher ungenau sein.", + }, + }; + + String get i18n => localize(this, _t); + String fill(List params) => localizeFill(this, params); + String plural(int value) => localizePlural(value, this, _t); + String version(Object modifier) => localizeVersion(modifier, this, _t); +} diff --git a/filcnaplo_desktop_ui/lib/pages/grades/grade_subject_view.dart b/filcnaplo_desktop_ui/lib/pages/grades/grade_subject_view.dart new file mode 100644 index 0000000..872c0ce --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/grades/grade_subject_view.dart @@ -0,0 +1,268 @@ +import 'dart:math'; + +import 'package:animations/animations.dart'; +import 'package:filcnaplo/utils/format.dart'; +import 'package:filcnaplo_kreta_api/providers/grade_provider.dart'; +import 'package:filcnaplo/helpers/average_helper.dart'; +import 'package:filcnaplo/helpers/subject.dart'; +import 'package:filcnaplo_kreta_api/models/grade.dart'; +import 'package:filcnaplo_kreta_api/models/subject.dart'; +import 'package:filcnaplo_mobile_ui/common/average_display.dart'; +import 'package:filcnaplo_mobile_ui/common/bottom_sheet_menu/rounded_bottom_sheet.dart'; +import 'package:filcnaplo_mobile_ui/common/panel/panel.dart'; +import 'package:filcnaplo_mobile_ui/common/trend_display.dart'; +import 'package:filcnaplo_mobile_ui/common/widgets/cretification/certification_tile.dart'; +import 'package:filcnaplo/ui/widgets/grade/grade_tile.dart'; +import 'package:filcnaplo_mobile_ui/common/widgets/grade/grade_viewable.dart'; +import 'package:filcnaplo_mobile_ui/common/hero_scrollview.dart'; +import 'package:filcnaplo_mobile_ui/pages/grades/calculator/grade_calculator.dart'; +import 'package:filcnaplo_mobile_ui/pages/grades/calculator/grade_calculator_provider.dart'; +import 'package:filcnaplo_desktop_ui/pages/grades/grades_count.dart'; +import 'package:filcnaplo_mobile_ui/pages/grades/graph.dart'; +import 'package:filcnaplo_mobile_ui/pages/grades/subject_grades_container.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_expandable_fab/flutter_expandable_fab.dart'; +import 'package:flutter_feather_icons/flutter_feather_icons.dart'; +import 'package:provider/provider.dart'; +import 'grades_page.i18n.dart'; +// import 'package:filcnaplo_premium/ui/mobile/goalplanner/new_goal.dart'; + +class GradeSubjectView extends StatefulWidget { + const GradeSubjectView(this.subject, {Key? key, this.groupAverage = 0.0}) : super(key: key); + + final Subject subject; + final double groupAverage; + + void push(BuildContext context, {bool root = false}) { + Navigator.of(context, rootNavigator: root).push(CupertinoPageRoute(builder: (context) => this)); + } + + @override + State createState() => _GradeSubjectViewState(); +} + +class _GradeSubjectViewState extends State { + final GlobalKey _scaffoldKey = GlobalKey(); + + // Controllers + PersistentBottomSheetController? _sheetController; + final ScrollController _scrollController = ScrollController(); + + List gradeTiles = []; + + // Providers + late GradeProvider gradeProvider; + late GradeCalculatorProvider calculatorProvider; + + late double average; + late Widget gradeGraph; + + bool gradeCalcMode = false; + + List getSubjectGrades(Subject subject) => !gradeCalcMode + ? gradeProvider.grades.where((e) => e.subject == subject).toList() + : calculatorProvider.grades.where((e) => e.subject == subject).toList(); + + bool showGraph(List subjectGrades) { + if (gradeCalcMode) return true; + + final gradeDates = subjectGrades.map((e) => e.date.millisecondsSinceEpoch); + final maxGradeDate = gradeDates.fold(0, max); + final minGradeDate = gradeDates.fold(0, min); + if (maxGradeDate - minGradeDate < const Duration(days: 5).inMilliseconds) return false; // naplo/#78 + + return subjectGrades.where((e) => e.type == GradeType.midYear).length > 1; + } + + void buildTiles(List subjectGrades) { + List tiles = []; + + if (showGraph(subjectGrades)) { + tiles.add(gradeGraph); + } else { + tiles.add(Container(height: 24.0)); + } + + List _gradeTiles = []; + + if (!gradeCalcMode) { + subjectGrades.sort((a, b) => -a.date.compareTo(b.date)); + for (var grade in subjectGrades) { + if (grade.type == GradeType.midYear) { + _gradeTiles.add(GradeViewable(grade)); + } else { + _gradeTiles.add(CertificationTile(grade, padding: EdgeInsets.zero)); + } + } + } else if (subjectGrades.isNotEmpty) { + subjectGrades.sort((a, b) => -a.date.compareTo(b.date)); + for (var grade in subjectGrades) { + _gradeTiles.add(GradeTile(grade)); + } + } + tiles.add( + PageTransitionSwitcher( + transitionBuilder: ( + Widget child, + Animation primaryAnimation, + Animation secondaryAnimation, + ) { + return SharedAxisTransition( + animation: primaryAnimation, + secondaryAnimation: secondaryAnimation, + transitionType: SharedAxisTransitionType.vertical, + child: child, + fillColor: Colors.transparent, + ); + }, + child: _gradeTiles.isNotEmpty + ? Panel( + key: ValueKey(gradeCalcMode), + title: Text( + gradeCalcMode ? "Ghost Grades".i18n : "Grades".i18n, + ), + child: Column( + children: _gradeTiles, + )) + : const SizedBox(), + ), + ); + + tiles.add(Padding(padding: EdgeInsets.only(bottom: !gradeCalcMode ? 24.0 : 250.0))); + gradeTiles = List.castFrom(tiles); + } + + @override + Widget build(BuildContext context) { + gradeProvider = Provider.of(context); + calculatorProvider = Provider.of(context); + + List subjectGrades = getSubjectGrades(widget.subject).toList(); + average = AverageHelper.averageEvals(subjectGrades); + final prevAvg = subjectGrades.isNotEmpty + ? AverageHelper.averageEvals(subjectGrades + .where((e) => e.date.isBefore(subjectGrades.reduce((v, e) => e.date.isAfter(v.date) ? e : v).date.subtract(const Duration(days: 30)))) + .toList()) + : 0.0; + + gradeGraph = Padding( + padding: const EdgeInsets.only(top: 16.0, bottom: 8.0), + child: Panel( + title: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text("annual_average".i18n), + if (average != prevAvg) TrendDisplay(current: average, previous: prevAvg), + ], + ), + child: Container( + padding: const EdgeInsets.only(top: 12.0, right: 12.0), + child: Row( + children: [ + Expanded(child: GradeGraph(subjectGrades, dayThreshold: 5, classAvg: widget.groupAverage)), + Padding( + padding: const EdgeInsets.only(bottom: 24.0), + child: GradesCount(grades: subjectGrades), + ), + ], + ), + ), + ), + ); + + if (!gradeCalcMode) { + buildTiles(subjectGrades); + } else { + List ghostGrades = calculatorProvider.ghosts.where((e) => e.subject == widget.subject).toList(); + buildTiles(ghostGrades); + } + + return Scaffold( + key: _scaffoldKey, + floatingActionButtonLocation: ExpandableFab.location, + floatingActionButton: Visibility( + visible: !gradeCalcMode && subjectGrades.where((e) => e.type == GradeType.midYear).isNotEmpty, + child: ExpandableFab( + type: ExpandableFabType.up, + distance: 50, + children: [ + FloatingActionButton.small( + child: const Icon(FeatherIcons.plus), + onPressed: () { + gradeCalc(context); + }, + ), + // FloatingActionButton.small( + // child: const Icon(FeatherIcons.flag, size: 20.0), + // onPressed: () { + // Navigator.of(context).push(CupertinoPageRoute(builder: (context) => PremiumGoalplannerNewGoalScreen(subject: widget.subject))); + // }, + // ), + ], + ), + ), + body: RefreshIndicator( + onRefresh: () async {}, + color: Theme.of(context).colorScheme.secondary, + child: HeroScrollView( + onClose: () { + if (_sheetController != null && gradeCalcMode) { + _sheetController!.close(); + } else { + Navigator.of(context).pop(); + } + }, + navBarItems: [ + const SizedBox(width: 6.0), + if (widget.groupAverage != 0) Center(child: AverageDisplay(average: widget.groupAverage, border: true)), + const SizedBox(width: 6.0), + if (average != 0) Center(child: AverageDisplay(average: average)), + const SizedBox(width: 12.0), + ], + icon: SubjectIcon.resolveVariant(subject: widget.subject, context: context), + scrollController: _scrollController, + title: widget.subject.renamedTo ?? widget.subject.name.capital(), + italic: widget.subject.isRenamed, + child: SubjectGradesContainer( + child: CupertinoScrollbar( + child: ListView.builder( + physics: const BouncingScrollPhysics(), + padding: const EdgeInsets.symmetric(horizontal: 24.0), + shrinkWrap: true, + itemBuilder: (context, index) => gradeTiles[index], + itemCount: gradeTiles.length, + ), + ), + )), + )); + } + + void gradeCalc(BuildContext context) { + // Scroll to the top of the page + _scrollController.animateTo(75, duration: const Duration(milliseconds: 500), curve: Curves.ease); + + calculatorProvider.clear(); + calculatorProvider.addAllGrades(gradeProvider.grades); + + _sheetController = _scaffoldKey.currentState?.showBottomSheet( + (context) => RoundedBottomSheet(child: GradeCalculator(widget.subject), borderRadius: 14.0), + backgroundColor: const Color(0x00000000), + elevation: 12.0, + ); + + // Hide the fab and grades + setState(() { + gradeCalcMode = true; + }); + + _sheetController!.closed.then((value) { + // Show fab and grades + if (mounted) { + setState(() { + gradeCalcMode = false; + }); + } + }); + } +} diff --git a/filcnaplo_desktop_ui/lib/pages/grades/grades_count.dart b/filcnaplo_desktop_ui/lib/pages/grades/grades_count.dart new file mode 100644 index 0000000..a060013 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/grades/grades_count.dart @@ -0,0 +1,25 @@ +import 'package:flutter/material.dart'; +import 'package:filcnaplo_kreta_api/models/grade.dart'; +import 'package:filcnaplo_desktop_ui/pages/grades/grades_count_item.dart'; +import 'package:collection/collection.dart'; + +class GradesCount extends StatelessWidget { + const GradesCount({Key? key, required this.grades}) : super(key: key); + + final List grades; + + @override + Widget build(BuildContext context) { + List gradesCount = List.generate(5, (int index) => grades.where((e) => e.value.value == index + 1).length); + + return Container( + width: 75, + padding: const EdgeInsets.only(bottom: 6.0, top: 6.0, left: 12.0, right: 0.0), + margin: const EdgeInsets.symmetric(horizontal: 12.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.spaceAround, + children: gradesCount.mapIndexed((index, e) => GradesCountItem(count: e, value: index + 1)).toList(), + ), + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/pages/grades/grades_count_item.dart b/filcnaplo_desktop_ui/lib/pages/grades/grades_count_item.dart new file mode 100644 index 0000000..722a46e --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/grades/grades_count_item.dart @@ -0,0 +1,37 @@ +import 'package:filcnaplo/ui/widgets/grade/grade_tile.dart'; +import 'package:filcnaplo_kreta_api/models/grade.dart'; +import 'package:flutter/material.dart'; + +class GradesCountItem extends StatelessWidget { + const GradesCountItem({Key? key, required this.count, required this.value}) : super(key: key); + + final int count; + final int value; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text.rich( + TextSpan(children: [ + TextSpan( + text: count.toString(), + style: const TextStyle(fontWeight: FontWeight.w600), + ), + const TextSpan( + text: "x", + style: TextStyle(fontSize: 13.0), + ), + ]), + style: const TextStyle(fontSize: 15.0), + ), + const SizedBox(width: 5.0), + GradeValueWidget(GradeValue(value, "Value", "Value", 100), size: 19.0, fill: true, shadow: false), + ], + ), + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/pages/grades/grades_page.dart b/filcnaplo_desktop_ui/lib/pages/grades/grades_page.dart new file mode 100644 index 0000000..b1fc920 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/grades/grades_page.dart @@ -0,0 +1,263 @@ +import 'dart:math'; + +import 'package:auto_size_text/auto_size_text.dart'; +import 'package:filcnaplo/api/providers/update_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/grade_provider.dart'; +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/theme/colors/colors.dart'; +import 'package:filcnaplo_kreta_api/models/grade.dart'; +import 'package:filcnaplo_kreta_api/models/subject.dart'; +import 'package:filcnaplo_kreta_api/models/group_average.dart'; +import 'package:filcnaplo_mobile_ui/common/average_display.dart'; +import 'package:filcnaplo_mobile_ui/common/empty.dart'; +import 'package:filcnaplo_mobile_ui/common/panel/panel.dart'; +import 'package:filcnaplo_mobile_ui/common/widgets/statistics_tile.dart'; +import 'package:filcnaplo_mobile_ui/common/widgets/grade/grade_subject_tile.dart'; +import 'package:filcnaplo_mobile_ui/common/trend_display.dart'; +import 'package:filcnaplo_mobile_ui/pages/grades/fail_warning.dart'; +import 'package:filcnaplo_desktop_ui/pages/grades/grades_count.dart'; +import 'package:filcnaplo_mobile_ui/pages/grades/graph.dart'; +import 'package:filcnaplo_desktop_ui/pages/grades/grade_subject_view.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'package:filcnaplo/helpers/average_helper.dart'; +import 'package:filcnaplo_premium/ui/mobile/grades/average_selector.dart'; +import 'grades_page.i18n.dart'; + +class GradesPage extends StatefulWidget { + const GradesPage({Key? key}) : super(key: key); + + @override + _GradesPageState createState() => _GradesPageState(); +} + +class _GradesPageState extends State { + late UserProvider user; + late GradeProvider gradeProvider; + late UpdateProvider updateProvider; + late String firstName; + late Widget yearlyGraph; + List subjectTiles = []; + + int avgDropValue = 0; + + List getSubjectGrades(Subject subject, {int days = 0}) => gradeProvider.grades + .where( + (e) => e.subject == subject && e.type == GradeType.midYear && (days == 0 || e.date.isBefore(DateTime.now().subtract(Duration(days: days))))) + .toList(); + + void generateTiles() { + List subjects = gradeProvider.grades.map((e) => e.subject).toSet().toList()..sort((a, b) => a.name.compareTo(b.name)); + List tiles = []; + + Map subjectAvgs = {}; + + tiles.addAll(subjects.map((subject) { + List subjectGrades = getSubjectGrades(subject); + + double avg = AverageHelper.averageEvals(subjectGrades); + double averageBefore = 0.0; + + if (avgDropValue != 0) { + List gradesBefore = getSubjectGrades(subject, days: avgDropValue); + averageBefore = avgDropValue == 0 ? 0.0 : AverageHelper.averageEvals(gradesBefore); + } + var nullavg = GroupAverage(average: 0.0, subject: subject, uid: "0"); + double groupAverage = gradeProvider.groupAverages.firstWhere((e) => e.subject == subject, orElse: () => nullavg).average; + + if (avg != 0) subjectAvgs[subject] = avg; + + return GradeSubjectTile( + subject, + averageBefore: averageBefore, + average: avg, + groupAverage: avgDropValue == 0 ? groupAverage : 0.0, + onTap: () { + GradeSubjectView(subject, groupAverage: groupAverage).push(context, root: true); + }, + ); + })); + + if (tiles.isNotEmpty) { + tiles.insert(0, yearlyGraph); + tiles.insert(1, FailWarning(subjectAvgs: subjectAvgs)); + tiles.insert(2, PanelTitle(title: Text(avgDropValue == 0 ? "Subjects".i18n : "Subjects_changes".i18n))); + tiles.insert(3, const PanelHeader(padding: EdgeInsets.only(top: 12.0))); + tiles.add(const PanelFooter(padding: EdgeInsets.only(bottom: 12.0))); + tiles.add(const Padding(padding: EdgeInsets.only(bottom: 24.0))); + } else { + tiles.insert( + 0, + Padding( + padding: const EdgeInsets.only(top: 24.0), + child: Empty(subtitle: "empty".i18n), + ), + ); + } + + double subjectAvg = subjectAvgs.isNotEmpty ? subjectAvgs.values.fold(0.0, (double a, double b) => a + b) / subjectAvgs.length : 0.0; + final double classAvg = gradeProvider.groupAverages.isNotEmpty + ? gradeProvider.groupAverages.map((e) => e.average).fold(0.0, (double a, double b) => a + b) / gradeProvider.groupAverages.length + : 0.0; + + if (subjectAvg > 0) { + tiles.add(Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: StatisticsTile( + fill: true, + title: AutoSizeText( + "subjectavg".i18n, + textAlign: TextAlign.center, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + value: subjectAvg, + ), + ), + const SizedBox(width: 24.0), + Expanded( + child: StatisticsTile( + outline: true, + title: AutoSizeText( + "classavg".i18n, + textAlign: TextAlign.center, + maxLines: 2, + wrapWords: false, + overflow: TextOverflow.ellipsis, + ), + value: classAvg, + ), + ), + ], + )); + } + + // padding + tiles.add(const SizedBox(height: 32.0)); + + subjectTiles = List.castFrom(tiles); + } + + @override + Widget build(BuildContext context) { + user = Provider.of(context); + gradeProvider = Provider.of(context); + updateProvider = Provider.of(context); + + List nameParts = user.displayName?.split(" ") ?? ["?"]; + firstName = nameParts.length > 1 ? nameParts[1] : nameParts[0]; + + final double totalClassAvg = gradeProvider.groupAverages.isEmpty + ? 0.0 + : gradeProvider.groupAverages.map((e) => e.average).fold(0.0, (double a, double b) => a + b) / gradeProvider.groupAverages.length; + + final now = gradeProvider.grades.isNotEmpty ? gradeProvider.grades.reduce((v, e) => e.date.isAfter(v.date) ? e : v).date : DateTime.now(); + + final currentStudentAvg = AverageHelper.averageEvals(gradeProvider.grades.where((e) => e.type == GradeType.midYear).toList()); + final prevStudentAvg = AverageHelper.averageEvals(gradeProvider.grades + .where((e) => e.type == GradeType.midYear) + .where((e) => e.date.isBefore(now.subtract(const Duration(days: 30)))) + .toList()); + + List graphGrades = gradeProvider.grades + .where((e) => e.type == GradeType.midYear && (avgDropValue == 0 || e.date.isAfter(DateTime.now().subtract(Duration(days: avgDropValue))))) + .toList(); + + yearlyGraph = Padding( + padding: const EdgeInsets.only(top: 12.0, bottom: 8.0), + child: Panel( + title: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + PremiumAverageSelector( + value: avgDropValue, + onChanged: (value) { + setState(() { + avgDropValue = value!; + }); + }, + ), + Row( + children: [ + // if (totalClassAvg >= 1.0) AverageDisplay(average: totalClassAvg, border: true), + // const SizedBox(width: 4.0), + TrendDisplay(previous: prevStudentAvg, current: currentStudentAvg), + if (gradeProvider.grades.where((e) => e.type == GradeType.midYear).isNotEmpty) AverageDisplay(average: currentStudentAvg), + ], + ) + ], + ), + child: Container( + padding: const EdgeInsets.only(top: 12.0, right: 12.0), + child: Row( + children: [ + Expanded(child: GradeGraph(graphGrades, dayThreshold: 2, classAvg: totalClassAvg)), + Padding( + padding: const EdgeInsets.only(bottom: 24.0), + child: GradesCount(grades: graphGrades), + ), + ], + ), + ), + ), + ); + + generateTiles(); + + return Scaffold( + body: Padding( + padding: const EdgeInsets.only(top: 9.0), + child: NestedScrollView( + physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()), + headerSliverBuilder: (context, _) => [ + SliverAppBar( + centerTitle: false, + pinned: true, + floating: false, + snap: false, + automaticallyImplyLeading: false, + surfaceTintColor: Theme.of(context).scaffoldBackgroundColor, + title: Padding( + padding: const EdgeInsets.only(left: 8.0), + child: Text( + "Grades".i18n, + style: TextStyle(color: AppColors.of(context).text, fontSize: 32.0, fontWeight: FontWeight.bold), + ), + ), + shadowColor: Theme.of(context).shadowColor, + ), + ], + body: RefreshIndicator( + onRefresh: () => gradeProvider.fetch(), + color: Theme.of(context).colorScheme.secondary, + child: ListView.builder( + padding: EdgeInsets.zero, + physics: const BouncingScrollPhysics(), + itemCount: max(subjectTiles.length, 1), + itemBuilder: (context, index) { + if (subjectTiles.isNotEmpty) { + EdgeInsetsGeometry panelPadding = const EdgeInsets.symmetric(horizontal: 24.0); + + if (subjectTiles[index].runtimeType == GradeSubjectTile) { + return Padding( + padding: panelPadding, + child: PanelBody( + child: subjectTiles[index], + padding: const EdgeInsets.symmetric(horizontal: 8.0), + )); + } else { + return Padding(padding: panelPadding, child: subjectTiles[index]); + } + } else { + return Container(); + } + }, + ), + ), + ), + ), + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/pages/grades/grades_page.i18n.dart b/filcnaplo_desktop_ui/lib/pages/grades/grades_page.i18n.dart new file mode 100644 index 0000000..41d0d03 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/grades/grades_page.i18n.dart @@ -0,0 +1,60 @@ +import 'package:i18n_extension/i18n_extension.dart'; + +extension Localization on String { + static final _t = Translations.byLocale("hu_hu") + + { + "en_en": { + "Grades": "Grades", + "Ghost Grades": "Grades", + "Subjects": "Subjects", + "Subjects_changes": "Subject Differences", + "empty": "You don't have any subjects.", + "annual_average": "Annual average", + "3_months_average": "3 Monthly Average", + "30_days_average": "Monthly Average", + "14_days_average": "2 Weekly Average", + "7_days_average": "Weekly Average", + "subjectavg": "Subject Average", + "classavg": "Class Average", + "fail_warning": "Faliure warning", + "fail_warning_description": "You are failing %d subject(s)", + }, + "hu_hu": { + "Grades": "Jegyek", + "Ghost Grades": "Szellem jegyek", + "Subjects": "Tantárgyak", + "Subjects_changes": "Tantárgyi változások", + "empty": "Még nincs egy tárgyad sem.", + "annual_average": "Éves átlag", + "3_months_average": "Háromhavi átlag", + "30_days_average": "Havi átlag", + "14_days_average": "Kétheti átlag", + "7_days_average": "Heti átlag", + "subjectavg": "Tantárgyi átlag", + "classavg": "Osztályátlag", + "fail_warning": "Bukás figyelmeztető", + "fail_warning_description": "Bukásra állsz %d tantárgyból", + }, + "de_de": { + "Grades": "Noten", + "Ghost Grades": "Geist Noten", + "Subjects": "Fächer", + "Subjects_changes": "Betreff Änderungen", + "empty": "Sie haben keine Fächer.", + "annual_average": "Jahresdurchschnitt", + "3_months_average": "Drei-Monats-Durchschnitt", + "30_days_average": "Monatsdurchschnitt", + "14_days_average": "Vierzehntägiger Durchschnitt", + "7_days_average": "Wöchentlicher Durchschnitt", + "subjectavg": "Fächer Durchschnitt", + "classavg": "Klassendurchschnitt", + "fail_warning": "Ausfallwarnung", + "fail_warning_description": "Sie werden in %d des Fachs durchfallen", + }, + }; + + String get i18n => localize(this, _t); + String fill(List params) => localizeFill(this, params); + String plural(int value) => localizePlural(value, this, _t); + String version(Object modifier) => localizeVersion(modifier, this, _t); +} diff --git a/filcnaplo_desktop_ui/lib/pages/home/home_page.dart b/filcnaplo_desktop_ui/lib/pages/home/home_page.dart new file mode 100644 index 0000000..d8919e3 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/home/home_page.dart @@ -0,0 +1,165 @@ +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/models/settings.dart'; +import 'package:filcnaplo/ui/date_widget.dart'; +import 'package:filcnaplo_desktop_ui/common/filter_bar.dart'; +import 'package:flutter/material.dart'; +import 'package:animated_list_plus/animated_list_plus.dart'; +import 'package:provider/provider.dart'; +import 'package:filcnaplo/ui/filter/widgets.dart'; +import 'package:filcnaplo/ui/filter/sort.dart'; +import 'home_page.i18n.dart'; + +class HomePage extends StatefulWidget { + const HomePage({Key? key}) : super(key: key); + + @override + State createState() => _HomePageState(); +} + +class _HomePageState extends State with SingleTickerProviderStateMixin { + late UserProvider user; + late SettingsProvider settings; + + late TabController _tabController; + late PageController _pageController; + + late String greeting; + late String firstName; + + late List listOrder; + static const pageCount = 4; + + @override + void initState() { + super.initState(); + + _tabController = TabController(length: pageCount, vsync: this); + _pageController = PageController(); + + listOrder = List.generate(pageCount, (index) => "$index"); + + user = Provider.of(context, listen: false); + + DateTime now = DateTime.now(); + if (now.isBefore(DateTime(now.year, DateTime.august, 31)) && now.isAfter(DateTime(now.year, DateTime.june, 14))) { + greeting = "goodrest"; + } else if (now.month == user.student?.birth.month && now.day == user.student?.birth.day) { + greeting = "happybirthday"; + } else if (now.month == DateTime.december && now.day >= 24 && now.day <= 26) { + greeting = "merryxmas"; + } else if (now.month == DateTime.january && now.day == 1) { + greeting = "happynewyear"; + } else if (now.hour >= 18) { + greeting = "goodevening"; + } else if (now.hour >= 10) { + greeting = "goodafternoon"; + } else if (now.hour >= 4) { + greeting = "goodmorning"; + } else { + greeting = "goodevening"; + } + } + + @override + Widget build(BuildContext context) { + user = Provider.of(context); + settings = Provider.of(context); + + List nameParts = user.name?.split(" ") ?? ["?"]; + if (!settings.presentationMode) { + firstName = nameParts.length > 1 ? nameParts[1] : nameParts[0]; + } else { + firstName = "Béla"; + } + + return SafeArea( + child: Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Greeting + Padding( + padding: const EdgeInsets.only(left: 32.0, top: 24.0, bottom: 12.0), + child: Text( + greeting.i18n.fill([firstName]), + overflow: TextOverflow.fade, + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 24.0, + color: Theme.of(context).textTheme.bodyMedium?.color, + ), + ), + ), + + Padding( + padding: const EdgeInsets.only(bottom: 12.0), + child: FilterBar( + items: [ + Tab(text: "All".i18n), + Tab(text: "Grades".i18n), + Tab(text: "Messages".i18n), + Tab(text: "Absences".i18n), + ], + controller: _tabController, + onTap: (i) async { + int selectedPage = _pageController.page!.round(); + + if (i == selectedPage) return; + if (_pageController.page?.roundToDouble() != _pageController.page) { + _pageController.animateToPage(i, curve: Curves.easeIn, duration: kTabScrollDuration); + return; + } + + // swap current page with target page + setState(() { + _pageController.jumpToPage(i); + String currentList = listOrder[selectedPage]; + listOrder[selectedPage] = listOrder[i]; + listOrder[i] = currentList; + }); + }, + disableFading: true, + ), + ), + + // Data filters + Expanded( + child: PageView.custom( + controller: _pageController, + childrenDelegate: SliverChildBuilderDelegate( + (BuildContext context, int index) { + return FutureBuilder>( + key: ValueKey(listOrder[index]), + future: getFilterWidgets(homeFilters[index], context: context), + builder: (context, dateWidgets) => dateWidgets.data != null + ? ImplicitlyAnimatedList( + items: sortDateWidgets(context, dateWidgets: dateWidgets.data!), + itemBuilder: filterItemBuilder, + spawnIsolate: false, + areItemsTheSame: (a, b) => a.key == b.key, + physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()), + padding: const EdgeInsets.symmetric(horizontal: 24.0), + ) + : Container(), + ); + }, + childCount: 4, + findChildIndexCallback: (Key key) { + final ValueKey valueKey = key as ValueKey; + final String data = valueKey.value; + return listOrder.indexOf(data); + }, + ), + physics: const PageScrollPhysics().applyTo(const BouncingScrollPhysics()), + ), + ), + ], + ), + ), + ], + ), + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/pages/home/home_page.i18n.dart b/filcnaplo_desktop_ui/lib/pages/home/home_page.i18n.dart new file mode 100644 index 0000000..2362b96 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/home/home_page.i18n.dart @@ -0,0 +1,63 @@ +import 'package:i18n_extension/i18n_extension.dart'; + +extension Localization on String { + static final _t = Translations.byLocale("hu_hu") + + { + "en_en": { + "goodmorning": "Good morning, %s!", + "goodafternoon": "Good afternoon, %s!", + "goodevening": "Good evening, %s!", + "goodrest": "⛱️ Have a nice holiday, %s!", + "happybirthday": "🎂 Happy birthday, %s!", + "merryxmas": "🎄 Merry Christmas, %s!", + "happynewyear": "🎉 Happy New Year, %s!", + "empty": "Nothing to see here.", + "All": "All", + "Grades": "Grades", + "Messages": "Messages", + "Absences": "Absences", + "update_available": "Update Available", + "missed_exams": "You missed %s exams this week.".one("You missed an exam this week."), + "missed_exam_contact": "Contact %s, to resolve it!", + }, + "hu_hu": { + "goodmorning": "Jó reggelt, %s!", + "goodafternoon": "Szép napot, %s!", + "goodevening": "Szép estét, %s!", + "goodrest": "⛱️ Jó szünetet, %s!", + "happybirthday": "🎂 Boldog születésnapot, %s!", + "merryxmas": "🎄 Boldog Karácsonyt, %s!", + "happynewyear": "🎉 Boldog új évet, %s!", + "empty": "Nincs itt semmi látnivaló.", + "All": "Összes", + "Grades": "Jegyek", + "Messages": "Üzenetek", + "Absences": "Hiányok", + "update_available": "Frissítés elérhető", + "missed_exams": "Ezen a héten hiányoztál %s dolgozatról.".one("Ezen a héten hiányoztál egy dolgozatról."), + "missed_exam_contact": "Keresd %s-t, ha pótolni szeretnéd!", + }, + "de_de": { + "goodmorning": "Guten morgen, %s!", + "goodafternoon": "Guten Tag, %s!", + "goodevening": "Guten Abend, %s!", + "goodrest": "⛱️ Schöne Ferien, %s!", + "happybirthday": "🎂 Alles Gute zum Geburtstag, %s!", + "merryxmas": "🎄 Frohe Weihnachten, %s!", + "happynewyear": "🎉 Frohes neues Jahr, %s!", + "empty": "Hier gibt es nichts zu sehen.", + "All": "Alles", + "Grades": "Noten", + "Messages": "Nachrichten", + "Absences": "Fehlen", + "update_available": "Update verfügbar", + "missed_exams": "Diese Woche haben Sie %s Prüfungen verpasst.".one("Diese Woche haben Sie eine Prüfung verpasst."), + "missed_exam_contact": "Wenden Sie sich an %s, um sie zu erneuern!", + }, + }; + + String get i18n => localize(this, _t); + String fill(List params) => localizeFill(this, params); + String plural(int value) => localizePlural(value, this, _t); + String version(Object modifier) => localizeVersion(modifier, this, _t); +} diff --git a/filcnaplo_desktop_ui/lib/pages/messages/messages_page.dart b/filcnaplo_desktop_ui/lib/pages/messages/messages_page.dart new file mode 100644 index 0000000..1348983 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/messages/messages_page.dart @@ -0,0 +1,164 @@ +import 'dart:math'; + +import 'package:filcnaplo/api/providers/update_provider.dart'; +import 'package:filcnaplo/ui/date_widget.dart'; +import 'package:filcnaplo_kreta_api/providers/message_provider.dart'; +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/theme/colors/colors.dart'; +import 'package:filcnaplo_kreta_api/models/message.dart'; +import 'package:filcnaplo_mobile_ui/common/empty.dart'; +import 'package:filcnaplo_mobile_ui/common/filter_bar.dart'; +import 'package:filcnaplo/ui/filter/sort.dart'; +import 'package:filcnaplo_mobile_ui/common/widgets/message/message_viewable.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; +import 'messages_page.i18n.dart'; + +class MessagesPage extends StatefulWidget { + const MessagesPage({Key? key}) : super(key: key); + + @override + _MessagesPageState createState() => _MessagesPageState(); +} + +class _MessagesPageState extends State with TickerProviderStateMixin { + late UserProvider user; + late MessageProvider messageProvider; + late UpdateProvider updateProvider; + late String firstName; + late TabController tabController; + + @override + void initState() { + super.initState(); + + tabController = TabController(length: 4, vsync: this); + } + + @override + Widget build(BuildContext context) { + user = Provider.of(context); + messageProvider = Provider.of(context); + updateProvider = Provider.of(context); + + List nameParts = user.displayName?.split(" ") ?? ["?"]; + firstName = nameParts.length > 1 ? nameParts[1] : nameParts[0]; + + return Scaffold( + body: Padding( + padding: const EdgeInsets.only(top: 12.0), + child: NestedScrollView( + physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()), + headerSliverBuilder: (context, _) => [ + SliverAppBar( + pinned: true, + floating: false, + snap: false, + centerTitle: false, + automaticallyImplyLeading: false, + shadowColor: Theme.of(context).shadowColor, + surfaceTintColor: Theme.of(context).scaffoldBackgroundColor, + title: Padding( + padding: const EdgeInsets.only(left: 8.0), + child: Text( + "Messages".i18n, + style: TextStyle(color: AppColors.of(context).text, fontSize: 32.0, fontWeight: FontWeight.bold), + ), + ), + bottom: FilterBar( + items: [ + Tab(text: "Inbox".i18n), + Tab(text: "Sent".i18n), + Tab(text: "Trash".i18n), + Tab(text: "Draft".i18n), + ], + controller: tabController, + disableFading: true, + ), + ), + ], + body: TabBarView( + physics: const BouncingScrollPhysics(), + controller: tabController, + children: List.generate(4, (index) => filterViewBuilder(context, index))), + ), + ), + ); + } + + List getFilterWidgets(MessageType activeData) { + List items = []; + switch (activeData) { + case MessageType.inbox: + for (var message in messageProvider.messages) { + if (message.type == MessageType.inbox) { + items.add(DateWidget( + date: message.date, + widget: MessageViewable(message), + )); + } + } + break; + case MessageType.sent: + for (var message in messageProvider.messages) { + if (message.type == MessageType.sent) { + items.add(DateWidget( + date: message.date, + widget: MessageViewable(message), + )); + } + } + break; + case MessageType.trash: + for (var message in messageProvider.messages) { + if (message.type == MessageType.trash) { + items.add(DateWidget( + date: message.date, + widget: MessageViewable(message), + )); + } + } + break; + case MessageType.draft: + for (var message in messageProvider.messages) { + if (message.type == MessageType.draft) { + items.add(DateWidget( + date: message.date, + widget: MessageViewable(message), + )); + } + } + break; + } + return items; + } + + Widget filterViewBuilder(context, int activeData) { + List filterWidgets = sortDateWidgets(context, dateWidgets: getFilterWidgets(MessageType.values[activeData]), hasShadow: true); + + return Padding( + padding: const EdgeInsets.only(top: 12.0), + child: RefreshIndicator( + color: Theme.of(context).colorScheme.secondary, + onRefresh: () { + return Future.wait([ + messageProvider.fetch(type: MessageType.inbox), + messageProvider.fetch(type: MessageType.sent), + messageProvider.fetch(type: MessageType.trash), + ]); + }, + child: ListView.builder( + padding: EdgeInsets.zero, + physics: const BouncingScrollPhysics(), + itemBuilder: (context, index) => filterWidgets.isNotEmpty + ? Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 6.0), + child: filterWidgets[index], + ) + : Empty(subtitle: "empty".i18n), + itemCount: max(filterWidgets.length, 1), + ), + ), + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/pages/messages/messages_page.i18n.dart b/filcnaplo_desktop_ui/lib/pages/messages/messages_page.i18n.dart new file mode 100644 index 0000000..b1665e1 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/messages/messages_page.i18n.dart @@ -0,0 +1,36 @@ +import 'package:i18n_extension/i18n_extension.dart'; + +extension Localization on String { + static final _t = Translations.byLocale("hu_hu") + + { + "en_en": { + "Messages": "Messages", + "Inbox": "Inbox", + "Sent": "Sent", + "Trash": "Trash", + "Draft": "Draft", + "empty": "You have no messages.", + }, + "hu_hu": { + "Messages": "Üzenetek", + "Inbox": "Beérkezett", + "Sent": "Elküldött", + "Trash": "Kuka", + "Draft": "Piszkozat", + "empty": "Nincsenek üzeneteid.", + }, + "de_de": { + "Messages": "Nachrichten", + "Inbox": "Posteingang", + "Sent": "Gesendet", + "Trash": "Müll", + "Draft": "Entwurf", + "empty": "Sie haben keine Nachrichten.", + }, + }; + + String get i18n => localize(this, _t); + String fill(List params) => localizeFill(this, params); + String plural(int value) => localizePlural(value, this, _t); + String version(Object modifier) => localizeVersion(modifier, this, _t); +} diff --git a/filcnaplo_desktop_ui/lib/pages/timetable/timetable_page.dart b/filcnaplo_desktop_ui/lib/pages/timetable/timetable_page.dart new file mode 100644 index 0000000..61cb6eb --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/timetable/timetable_page.dart @@ -0,0 +1,333 @@ +import 'dart:math'; +import 'package:animations/animations.dart'; +import 'package:filcnaplo/api/providers/update_provider.dart'; +import 'package:filcnaplo/theme/colors/colors.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; +import 'package:filcnaplo_kreta_api/models/week.dart'; +import 'package:filcnaplo_kreta_api/providers/timetable_provider.dart'; +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo_kreta_api/models/lesson.dart'; +import 'package:filcnaplo_mobile_ui/common/empty.dart'; +import 'package:filcnaplo_mobile_ui/common/panel/panel.dart'; +import 'package:filcnaplo_kreta_api/controllers/timetable_controller.dart'; +import 'package:filcnaplo_desktop_ui/common/widgets/lesson/lesson_viewable.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_feather_icons/flutter_feather_icons.dart'; +import 'package:provider/provider.dart'; +import 'package:filcnaplo/utils/format.dart'; +import 'package:intl/intl.dart'; +import 'package:i18n_extension/i18n_widget.dart'; +import 'timetable_page.i18n.dart'; + +// todo: "fix" overflow (priority: -1) + +class TimetablePage extends StatefulWidget { + const TimetablePage({Key? key, this.initialDay, this.initialWeek}) : super(key: key); + + final DateTime? initialDay; + final Week? initialWeek; + + static void jump(BuildContext context, {Week? week, DateTime? day, Lesson? lesson}) { + // Go to timetable page with arguments + // NavigationScreen.of(context)?.customRoute(navigationPageRoute((context) => TimetablePage( + // initialDay: lesson?.date ?? day, + // initialWeek: lesson?.date != null + // ? Week.fromDate(lesson!.date) + // : day != null + // ? Week.fromDate(day) + // : week, + // ))); + + // NavigationScreen.of(context)?.setPage("timetable"); + + // Show initial Lesson + // if (lesson != null) LessonView.show(lesson, context: context); + } + + @override + _TimetablePageState createState() => _TimetablePageState(); +} + +class _TimetablePageState extends State with TickerProviderStateMixin { + late UserProvider user; + late TimetableProvider timetableProvider; + late UpdateProvider updateProvider; + late String firstName; + late TimetableController _controller; + late TabController _tabController; + late Widget empty; + + int _getDayIndex(DateTime date) { + int index = 0; + if (_controller.days == null || (_controller.days?.isEmpty ?? true)) return index; + + // find the first day with upcoming lessons + index = _controller.days!.indexWhere((day) => day.last.end.isAfter(date)); + if (index == -1) index = 0; // fallback + + return index; + } + + // Update timetable on user change + Future _userListener() async { + await Provider.of(context, listen: false).refreshLogin(); + if (mounted) _controller.jump(_controller.currentWeek, context: context); + } + + @override + void initState() { + super.initState(); + + // Initalize controllers + _controller = TimetableController(); + _tabController = TabController(length: 0, vsync: this, initialIndex: 0); + + empty = Empty(subtitle: "empty".i18n); + + bool initial = true; + + // Only update the TabController on week changes + _controller.addListener(() { + if (_controller.days == null) return; + setState(() { + _tabController = TabController( + length: _controller.days!.length, + vsync: this, + initialIndex: min(_tabController.index, max(_controller.days!.length - 1, 0)), + ); + + if (initial || _controller.previousWeekId != _controller.currentWeekId) { + _tabController.animateTo(_getDayIndex(widget.initialDay ?? DateTime.now())); + } + initial = false; + + // Empty is updated once every week change + empty = Empty(subtitle: "empty".i18n); + }); + }); + + if (mounted) { + if (widget.initialWeek != null) { + _controller.jump(widget.initialWeek!, context: context, initial: true); + } else { + _controller.jump(_controller.currentWeek, context: context, initial: true, skip: true); + } + } + // Listen for user changes + user = Provider.of(context, listen: false); + user.addListener(_userListener); + } + + @override + void dispose() { + _tabController.dispose(); + _controller.dispose(); + user.removeListener(_userListener); + super.dispose(); + } + + String dayTitle(int index) { + // Sometimes when changing weeks really fast, + // controller.days might be null or won't include index + try { + return DateFormat("EEEE", I18n.of(context).locale.languageCode).format(_controller.days![index].first.date); + } catch (e) { + return "timetable".i18n; + } + } + + @override + Widget build(BuildContext context) { + user = Provider.of(context); + timetableProvider = Provider.of(context); + updateProvider = Provider.of(context); + + // First name + List nameParts = user.name?.split(" ") ?? ["?"]; + firstName = nameParts.length > 1 ? nameParts[1] : nameParts[0]; + + return Scaffold( + body: Padding( + padding: const EdgeInsets.only(top: 18.0), + child: Column( + children: [ + Expanded( + child: PageTransitionSwitcher( + transitionBuilder: ( + Widget child, + Animation primaryAnimation, + Animation secondaryAnimation, + ) { + return FadeThroughTransition( + child: child, + animation: primaryAnimation, + secondaryAnimation: secondaryAnimation, + fillColor: Theme.of(context).scaffoldBackgroundColor, + ); + }, + child: _controller.days != null + ? + // Week view + _tabController.length > 0 + ? CupertinoScrollbar( + child: ListView.builder( + scrollDirection: Axis.horizontal, + itemCount: _controller.days!.length, + itemBuilder: (context, tab) => SizedBox( + width: 400, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Day Title + Padding( + padding: const EdgeInsets.only(left: 24.0, right: 28.0, top: 18.0, bottom: 8.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + dayTitle(tab).capital(), + style: const TextStyle( + fontSize: 32.0, + fontWeight: FontWeight.w600, + ), + ), + Text( + "${_controller.days![tab].first.date.day}".padLeft(2, '0') + ".", + style: TextStyle( + color: AppColors.of(context).text.withOpacity(.5), + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + + // Lessons + Expanded( + child: ListView.builder( + padding: EdgeInsets.zero, + physics: const BouncingScrollPhysics(), + itemCount: _controller.days![tab].length + 2, + itemBuilder: (context, index) { + if (_controller.days == null) return Container(); + + // Header + if (index == 0) { + return const Padding( + padding: EdgeInsets.only(top: 8.0, left: 24.0, right: 24.0), + child: PanelHeader(padding: EdgeInsets.only(top: 12.0)), + ); + } + + // Footer + if (index == _controller.days![tab].length + 1) { + return const Padding( + padding: EdgeInsets.only(bottom: 8.0, left: 24.0, right: 24.0), + child: PanelFooter(padding: EdgeInsets.only(top: 12.0)), + ); + } + + // Body + final Lesson lesson = _controller.days![tab][index - 1]; + final bool swapDescDay = _controller.days![tab].map((l) => l.swapDesc ? 1 : 0).reduce((a, b) => a + b) >= + _controller.days![tab].length * .5; + + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 24.0), + child: PanelBody( + padding: const EdgeInsets.symmetric(horizontal: 10.0), + child: LessonViewable( + lesson, + swapDesc: swapDescDay, + ), + ), + ); + }, + ), + ), + ], + ), + ), + ), + ) + + // Empty week + : Expanded( + child: Center(child: empty), + ) + : Center( + child: CircularProgressIndicator( + color: Theme.of(context).colorScheme.secondary, + ), + ), + ), + ), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0, vertical: 8.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + // Previous week + IconButton( + onPressed: _controller.currentWeekId == 0 + ? null + : () => setState(() { + _controller.previous(context); + }), + splashRadius: 24.0, + icon: const Icon(FeatherIcons.chevronLeft), + color: Theme.of(context).colorScheme.secondary), + + // Week selector + InkWell( + borderRadius: BorderRadius.circular(6.0), + onTap: () => setState(() { + _controller.current(); + if (mounted) { + _controller.jump(_controller.currentWeek, context: context, loader: _controller.currentWeekId != _controller.previousWeekId); + } + }), + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Text( + "${_controller.currentWeekId + 1}. " + + "week".i18n + + " (" + + // Week start + DateFormat((_controller.currentWeek.start.year != DateTime.now().year ? "yy. " : "") + "MMM d.", + I18n.of(context).locale.languageCode) + .format(_controller.currentWeek.start) + + " - " + + // Week end + DateFormat((_controller.currentWeek.start.year != DateTime.now().year ? "yy. " : "") + "MMM d.", + I18n.of(context).locale.languageCode) + .format(_controller.currentWeek.end) + + ")", + style: const TextStyle( + fontWeight: FontWeight.w500, + fontSize: 14.0, + ), + ), + ), + ), + + // Next week + IconButton( + onPressed: _controller.currentWeekId == 51 + ? null + : () => setState(() { + _controller.next(context); + }), + splashRadius: 24.0, + icon: const Icon(FeatherIcons.chevronRight), + color: Theme.of(context).colorScheme.secondary), + ], + ), + ), + ], + ), + ), + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/pages/timetable/timetable_page.i18n.dart b/filcnaplo_desktop_ui/lib/pages/timetable/timetable_page.i18n.dart new file mode 100644 index 0000000..75d3bd0 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/pages/timetable/timetable_page.i18n.dart @@ -0,0 +1,30 @@ +import 'package:i18n_extension/i18n_extension.dart'; + +extension Localization on String { + static final _t = Translations.byLocale("hu_hu") + + { + "en_en": { + "timetable": "Timetable", + "empty": "No school this week!", + "week": "Week", + "error": "Failed to fetch timetable!", + }, + "hu_hu": { + "timetable": "Órarend", + "empty": "Ezen a héten nincs iskola.", + "week": "Hét", + "error": "Nem sikerült lekérni az órarendet!", + }, + "de_de": { + "timetable": "Zeitplan", + "empty": "Keine Schule diese Woche.", + "week": "Woche", + "error": "Der Fahrplan konnte nicht abgerufen werden!", + }, + }; + + String get i18n => localize(this, _t); + String fill(List params) => localizeFill(this, params); + String plural(int value) => localizePlural(value, this, _t); + String version(Object modifier) => localizeVersion(modifier, this, _t); +} diff --git a/filcnaplo_desktop_ui/lib/screens/login/login_route.dart b/filcnaplo_desktop_ui/lib/screens/login/login_route.dart new file mode 100644 index 0000000..f6f5452 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/screens/login/login_route.dart @@ -0,0 +1,17 @@ +import 'package:animations/animations.dart'; +import 'package:flutter/material.dart'; + +Route loginRoute(Widget widget) { + return PageRouteBuilder( + pageBuilder: (context, animation, secondaryAnimation) => widget, + transitionDuration: const Duration(milliseconds: 650), + transitionsBuilder: (context, animation, secondaryAnimation, child) { + return FadeThroughTransition( + fillColor: Colors.transparent, + animation: animation, + secondaryAnimation: secondaryAnimation, + child: child, + ); + }, + ); +} diff --git a/filcnaplo_desktop_ui/lib/screens/login/login_screen.dart b/filcnaplo_desktop_ui/lib/screens/login/login_screen.dart new file mode 100644 index 0000000..e7fd193 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/screens/login/login_screen.dart @@ -0,0 +1,319 @@ +import 'dart:io'; +import 'dart:ui'; + +import 'package:elegant_notification/elegant_notification.dart'; +import 'package:elegant_notification/resources/arrays.dart'; +import 'package:filcnaplo/api/client.dart'; +import 'package:filcnaplo/api/login.dart'; +import 'package:filcnaplo/theme/colors/colors.dart'; +import 'package:filcnaplo_mobile_ui/screens/login/login_button.dart'; +import 'package:filcnaplo_mobile_ui/screens/login/login_input.dart'; +import 'package:filcnaplo_mobile_ui/screens/login/school_input/school_input.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_acrylic/flutter_acrylic.dart'; +import 'login_screen.i18n.dart'; + +class LoginScreen extends StatefulWidget { + const LoginScreen({Key? key, this.back = false}) : super(key: key); + + final bool back; + + @override + _LoginScreenState createState() => _LoginScreenState(); +} + +class _LoginScreenState extends State { + final usernameController = TextEditingController(); + final passwordController = TextEditingController(); + final schoolController = SchoolInputController(); + final _scrollController = ScrollController(); + + LoginState _loginState = LoginState.normal; + bool showBack = false; + double topInset = 12.0; + + @override + void initState() { + super.initState(); + showBack = widget.back; + + SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle( + statusBarColor: Colors.transparent, + statusBarIconBrightness: Brightness.light, + systemNavigationBarColor: Colors.white, + systemNavigationBarIconBrightness: Brightness.dark, + )); + + FilcAPI.getSchools().then((schools) { + if (schools != null) { + schoolController.update(() { + schoolController.schools = schools; + }); + } else { + ElegantNotification.error( + background: Colors.white, + description: Text( + "schools_error".i18n, + overflow: TextOverflow.ellipsis, + style: const TextStyle(color: Colors.red), + ), + onActionPressed: () {}, + onCloseButtonPressed: () {}, + onDismiss: () {}, + onProgressFinished: () {}, + displayCloseButton: false, + showProgressIndicator: false, + autoDismiss: true, + animation: AnimationType.fromTop, + ).show(context); + } + }); + + if (Platform.isMacOS) Window.getTitlebarHeight().then((value) => setState(() => topInset = value)); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: AppColors.of(context).filc, + body: SafeArea( + child: Stack( + children: [ + Row( + children: [ + Expanded( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + // App logo + Padding( + padding: const EdgeInsets.only(bottom: 24.0), + child: ClipRect( + child: Padding( + padding: const EdgeInsets.only(left: 12.0, right: 12.0, bottom: 32.0), + child: SizedBox( + width: 82.0, + height: 82.0, + // Png shadow *hack* + child: Stack( + children: [ + Padding( + padding: const EdgeInsets.only(top: 8.0), + child: Opacity(child: Image.asset("assets/icons/ic_splash.png", color: Colors.black), opacity: 0.3), + ), + BackdropFilter( + filter: ImageFilter.blur(sigmaX: 6.0, sigmaY: 6.0), + child: Image.asset("assets/icons/ic_splash.png"), + ) + ], + ), + ), + ), + ), + ), + + // Inputs + SizedBox( + width: 400.0, + child: AutofillGroup( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Username + Padding( + padding: const EdgeInsets.only(bottom: 6.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Text( + "username".i18n, + maxLines: 1, + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.w600, + fontSize: 14.0, + ), + ), + ), + Expanded( + child: Text( + "usernameHint".i18n, + maxLines: 1, + textAlign: TextAlign.right, + style: const TextStyle( + color: Colors.white54, + fontWeight: FontWeight.w500, + fontSize: 12.0, + ), + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.only(bottom: 12.0), + child: LoginInput( + style: LoginInputStyle.username, + controller: usernameController, + ), + ), + + // Password + Padding( + padding: const EdgeInsets.only(bottom: 6.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Expanded( + child: Text( + "password".i18n, + maxLines: 1, + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.w600, + fontSize: 14.0, + ), + ), + ), + Expanded( + child: Text( + "passwordHint".i18n, + maxLines: 1, + textAlign: TextAlign.right, + style: const TextStyle( + color: Colors.white54, + fontWeight: FontWeight.w500, + fontSize: 12.0, + ), + ), + ), + ], + ), + ), + Padding( + padding: const EdgeInsets.only(bottom: 12.0), + child: LoginInput( + style: LoginInputStyle.password, + controller: passwordController, + ), + ), + + // School + Padding( + padding: const EdgeInsets.only(bottom: 6.0), + child: Text( + "school".i18n, + maxLines: 1, + style: const TextStyle( + color: Colors.white, + fontWeight: FontWeight.w600, + fontSize: 14.0, + ), + ), + ), + SchoolInput( + scroll: _scrollController, + controller: schoolController, + ), + ], + ), + ), + ), + + // Log in button + SizedBox( + width: 400.0, + child: Padding( + padding: const EdgeInsets.only(top: 42.0), + child: Visibility( + child: LoginButton( + child: Text("login".i18n, + maxLines: 1, + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 15.0, + )), + onPressed: () => _loginApi(context: context), + ), + visible: _loginState != LoginState.inProgress, + replacement: const Padding( + padding: EdgeInsets.symmetric(vertical: 6.0), + child: Center( + child: CircularProgressIndicator( + valueColor: AlwaysStoppedAnimation(Colors.white), + ), + ), + ), + ), + ), + ), + if (_loginState == LoginState.missingFields || _loginState == LoginState.invalidGrant || _loginState == LoginState.failed) + Padding( + padding: const EdgeInsets.only(top: 8.0), + child: Text( + ["missing_fields", "invalid_grant", "error"][_loginState.index].i18n, + style: const TextStyle(color: Colors.red, fontWeight: FontWeight.w500), + ), + ), + ], + ), + ), + ], + ), + if (showBack) + Container( + alignment: Alignment.topLeft, + padding: EdgeInsets.only(left: 16.0, top: topInset), + child: const ClipOval( + child: Material( + type: MaterialType.transparency, + child: BackButton(color: Colors.white), + ), + ), + ), + ], + ), + ), + ); + } + + void _loginApi({required BuildContext context}) { + String username = usernameController.text; + String password = passwordController.text; + + if (username == "" || password == "" || schoolController.selectedSchool == null) { + return setState(() => _loginState = LoginState.missingFields); + } + + setState(() => _loginState = LoginState.inProgress); + + loginApi( + username: username, + password: password, + instituteCode: schoolController.selectedSchool!.instituteCode, + context: context, + onLogin: (user) { + ElegantNotification.success( + background: Colors.white, + description: Text( + "welcome".i18n.fill([user.name]), + overflow: TextOverflow.ellipsis, + style: const TextStyle(color: Colors.black), + ), + onActionPressed: () {}, + onCloseButtonPressed: () {}, + onDismiss: () {}, + onProgressFinished: () {}, + displayCloseButton: false, + showProgressIndicator: false, + autoDismiss: true, + animation: AnimationType.fromTop, + ).show(context); + }, + onSuccess: () { + Navigator.of(context).pushNamedAndRemoveUntil("login_to_navigation", (_) => false); + }).then((res) => setState(() => _loginState = res)); + } +} diff --git a/filcnaplo_desktop_ui/lib/screens/login/login_screen.i18n.dart b/filcnaplo_desktop_ui/lib/screens/login/login_screen.i18n.dart new file mode 100644 index 0000000..f463081 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/screens/login/login_screen.i18n.dart @@ -0,0 +1,51 @@ +import 'package:i18n_extension/i18n_extension.dart'; + +extension Localization on String { + static final _t = Translations.byLocale("hu_hu") + + { + "en_en": { + "username": "Username", + "usernameHint": "Student ID number", + "password": "Password", + "passwordHint": "Date of birth", + "school": "School", + "login": "Log in", + "welcome": "Welcome, %s!", + "missing_fields": "Missing Fields!", + "invalid_grant": "Invalid Username/Password!", + "error": "Failed to log in.", + "schools_error": "Failed to get schools." + }, + "hu_hu": { + "username": "Felhasználónév", + "usernameHint": "Oktatási azonosító", + "password": "Jelszó", + "passwordHint": "Születési dátum", + "school": "Iskola", + "login": "Belépés", + "welcome": "Üdv, %s!", + "missing_fields": "Hiányzó adatok!", + "invalid_grant": "Helytelen Felhasználónév/Jelszó!", + "error": "Sikertelen bejelentkezés.", + "schools_error": "Nem sikerült lekérni az iskolákat." + }, + "de_de": { + "username": "Benutzername", + "usernameHint": "Ausbildung ID", + "password": "Passwort", + "passwordHint": "Geburtsdatum", + "school": "Schule", + "login": "Einloggen", + "welcome": "Wilkommen, %s!", + "missing_fields": "Fehlende Felder!", + "invalid_grant": "Ungültiger Benutzername/Passwort!", + "error": "Anmeldung fehlgeschlagen.", + "schools_error": "Keine Schulen gefunden." + }, + }; + + String get i18n => localize(this, _t); + String fill(List params) => localizeFill(this, params); + String plural(int value) => localizePlural(value, this, _t); + String version(Object modifier) => localizeVersion(modifier, this, _t); +} diff --git a/filcnaplo_desktop_ui/lib/screens/navigation/navigation_route.dart b/filcnaplo_desktop_ui/lib/screens/navigation/navigation_route.dart new file mode 100644 index 0000000..79778aa --- /dev/null +++ b/filcnaplo_desktop_ui/lib/screens/navigation/navigation_route.dart @@ -0,0 +1,25 @@ +class NavigationRoute { + late String _name; + late int _index; + + final List _internalPageMap = [ + "home", + "grades", + "timetable", + "messages", + "absences", + ]; + + String get name => _name; + int get index => _index; + + set name(String n) { + _name = n; + _index = _internalPageMap.indexOf(n); + } + + set index(int i) { + _index = i; + _name = _internalPageMap.elementAt(i); + } +} diff --git a/filcnaplo_desktop_ui/lib/screens/navigation/navigation_route_handler.dart b/filcnaplo_desktop_ui/lib/screens/navigation/navigation_route_handler.dart new file mode 100644 index 0000000..ba315bb --- /dev/null +++ b/filcnaplo_desktop_ui/lib/screens/navigation/navigation_route_handler.dart @@ -0,0 +1,37 @@ +import 'package:animations/animations.dart'; +import 'package:filcnaplo_desktop_ui/pages/absences/absences_page.dart'; +import 'package:filcnaplo_desktop_ui/pages/grades/grades_page.dart'; +import 'package:filcnaplo_desktop_ui/pages/home/home_page.dart'; +import 'package:filcnaplo_desktop_ui/pages/messages/messages_page.dart'; +import 'package:filcnaplo_desktop_ui/pages/timetable/timetable_page.dart'; +import 'package:flutter/material.dart'; + +Route navigationRouteHandler(RouteSettings settings) { + switch (settings.name) { + case "grades": + return navigationPageRoute((context) => const GradesPage()); + case "timetable": + return navigationPageRoute((context) => const TimetablePage()); + case "messages": + return navigationPageRoute((context) => const MessagesPage()); + case "absences": + return navigationPageRoute((context) => const AbsencesPage()); + case "home": + default: + return navigationPageRoute((context) => const HomePage()); + } +} + +Route navigationPageRoute(Widget Function(BuildContext) builder) { + return PageRouteBuilder( + pageBuilder: (context, _, __) => builder(context), + transitionsBuilder: (context, animation, secondaryAnimation, child) { + return FadeThroughTransition( + fillColor: Theme.of(context).scaffoldBackgroundColor, + animation: animation, + secondaryAnimation: secondaryAnimation, + child: child, + ); + }, + ); +} diff --git a/filcnaplo_desktop_ui/lib/screens/navigation/navigation_screen.dart b/filcnaplo_desktop_ui/lib/screens/navigation/navigation_screen.dart new file mode 100644 index 0000000..866d43b --- /dev/null +++ b/filcnaplo_desktop_ui/lib/screens/navigation/navigation_screen.dart @@ -0,0 +1,137 @@ +import 'dart:io'; + +import 'package:filcnaplo/api/providers/news_provider.dart'; +import 'package:filcnaplo/api/providers/sync.dart'; +import 'package:filcnaplo/theme/colors/colors.dart'; +import 'package:filcnaplo/theme/observer.dart'; +import 'package:filcnaplo_desktop_ui/screens/navigation/navigation_route.dart'; +import 'package:filcnaplo_desktop_ui/screens/navigation/navigation_route_handler.dart'; +import 'package:filcnaplo_desktop_ui/screens/navigation/sidebar.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_acrylic/flutter_acrylic.dart'; +import 'package:provider/provider.dart'; +import 'package:filcnaplo/models/settings.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; + +class NavigationScreen extends StatefulWidget { + const NavigationScreen({Key? key}) : super(key: key); + + static NavigationScreenState? of(BuildContext context) => context.findAncestorStateOfType(); + + @override + State createState() => NavigationScreenState(); +} + +class NavigationScreenState extends State with WidgetsBindingObserver { + final _navigatorState = GlobalKey(); + late NavigationRoute selected; + late SettingsProvider settings; + late NewsProvider newsProvider; + double topInset = 0.0; + + @override + void initState() { + super.initState(); + settings = Provider.of(context, listen: false); + selected = NavigationRoute(); + selected.index = 0; + + // add brightness observer + WidgetsBinding.instance.addObserver(this); + + // set client User-Agent + Provider.of(context, listen: false).userAgent = settings.config.userAgent; + + // Get news + newsProvider = Provider.of(context, listen: false); + newsProvider.restore().then((value) => newsProvider.fetch()); + + // Initial sync + syncAll(context); + + () async { + try { + await Window.initialize(); + } catch (_) {} + // Transparent sidebar + await Window.setEffect(effect: WindowEffect.acrylic, color: Platform.isMacOS ? Colors.transparent : const Color.fromARGB(27, 27, 27, 27)); + + // todo: do for windows + if (Platform.isMacOS) { + topInset = await Window.getTitlebarHeight(); + await Window.enableFullSizeContentView(); + await Window.hideTitle(); + await Window.makeTitlebarTransparent(); + } + }(); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + @override + void didChangePlatformBrightness() { + if (settings.theme == ThemeMode.system) { + Brightness? brightness = WidgetsBinding.instance.window.platformBrightness; + Provider.of(context, listen: false).changeTheme(brightness == Brightness.light ? ThemeMode.light : ThemeMode.dark); + } + super.didChangePlatformBrightness(); + } + + void setPage(String page) => setState(() => selected.name = page); + + @override + Widget build(BuildContext context) { + settings = Provider.of(context); + newsProvider = Provider.of(context); + + // Show news + WidgetsBinding.instance.addPostFrameCallback((_) { + if (newsProvider.show) { + newsProvider.lock(); + // NewsView.show(newsProvider.news[newsProvider.state], context: context).then((value) => newsProvider.release()); + } + }); + + return Scaffold( + backgroundColor: Colors.transparent, + body: Row( + children: [ + if (_navigatorState.currentState != null) + Container( + decoration: BoxDecoration( + color: Theme.of(context).scaffoldBackgroundColor.withOpacity(.5), + border: Border(right: BorderSide(color: AppColors.of(context).shadow.withOpacity(.7), width: 1.0)), + ), + child: Padding( + padding: EdgeInsets.only(top: topInset), + child: Sidebar( + navigator: _navigatorState.currentState!, + selected: selected.name, + onRouteChange: (name) => setPage(name), + ), + ), + ), + Expanded( + child: Container( + color: Theme.of(context).scaffoldBackgroundColor, + child: MediaQuery( + data: MediaQuery.of(context).copyWith( + padding: EdgeInsets.only(top: topInset), + ), + child: Navigator( + key: _navigatorState, + initialRoute: selected.name, + onGenerateRoute: (settings) => navigationRouteHandler(settings), + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/screens/navigation/sidebar.dart b/filcnaplo_desktop_ui/lib/screens/navigation/sidebar.dart new file mode 100644 index 0000000..32ad7a0 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/screens/navigation/sidebar.dart @@ -0,0 +1,304 @@ +import 'package:animations/animations.dart'; +import 'package:filcnaplo/api/providers/database_provider.dart'; +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/icons/filc_icons.dart'; +import 'package:filcnaplo/models/settings.dart'; +import 'package:filcnaplo/utils/color.dart'; +import 'package:filcnaplo_desktop_ui/common/panel_button.dart'; +import 'package:filcnaplo_desktop_ui/common/profile_image.dart'; +import 'package:filcnaplo_desktop_ui/screens/navigation/sidebar_action.dart'; +import 'package:filcnaplo_desktop_ui/screens/settings/settings_screen.dart'; +import 'package:filcnaplo_mobile_ui/screens/settings/accounts/account_tile.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; +import 'package:filcnaplo_kreta_api/providers/absence_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/event_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/exam_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/grade_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/homework_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/message_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/note_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/timetable_provider.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_feather_icons/flutter_feather_icons.dart'; +import 'package:provider/provider.dart'; +import 'package:filcnaplo/theme/colors/colors.dart'; + +class Sidebar extends StatefulWidget { + const Sidebar({Key? key, required this.navigator, required this.onRouteChange, this.selected = "home"}) : super(key: key); + + final NavigatorState navigator; + final String selected; + final Function(String) onRouteChange; + + @override + State createState() => _SidebarState(); +} + +class _SidebarState extends State { + late UserProvider user; + late SettingsProvider settings; + late String firstName; + + String topNav = ""; + bool expandAccount = false; + List accountTiles = []; + + @override + void initState() { + super.initState(); + user = Provider.of(context, listen: false); + } + + Future restore() => Future.wait([ + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restoreUser(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).refreshLogin(), + ]); + + @override + Widget build(BuildContext context) { + user = Provider.of(context); + settings = Provider.of(context); + + List nameParts = user.name?.split(" ") ?? ["?"]; + if (!settings.presentationMode) { + firstName = nameParts.length > 1 ? nameParts[1] : nameParts[0]; + } else { + firstName = "Béla"; + } + + List pageWidgets = [ + SidebarAction( + title: const Text("Home"), + icon: const Icon(FilcIcons.home), + selected: widget.selected == "home", + onTap: () { + if (widget.selected != "home") { + widget.navigator.pushReplacementNamed("home"); + widget.onRouteChange("home"); + } + }, + ), + SidebarAction( + title: const Text("Grades"), + icon: const Icon(FeatherIcons.bookmark), + selected: widget.selected == "grades", + onTap: () { + if (widget.selected != "grades") { + widget.navigator.pushReplacementNamed("grades"); + widget.onRouteChange("grades"); + } + }, + ), + SidebarAction( + title: const Text("Timetable"), + icon: const Icon(FeatherIcons.calendar), + selected: widget.selected == "timetable", + onTap: () { + if (widget.selected != "timetable") { + widget.navigator.pushReplacementNamed("timetable"); + widget.onRouteChange("timetable"); + } + }, + ), + SidebarAction( + title: const Text("Messages"), + icon: const Icon(FeatherIcons.messageSquare), + selected: widget.selected == "messages", + onTap: () { + if (widget.selected != "messages") { + widget.navigator.pushReplacementNamed("messages"); + widget.onRouteChange("messages"); + } + }, + ), + SidebarAction( + title: const Text("Absences"), + icon: const Icon(FeatherIcons.clock), + selected: widget.selected == "absences", + onTap: () { + if (widget.selected != "absences") { + widget.navigator.pushReplacementNamed("absences"); + widget.onRouteChange("absences"); + } + }, + ), + ]; + + List bottomActions = [ + SidebarAction( + title: const Text("Settings"), + selected: true, + icon: const Icon(FeatherIcons.settings), + onTap: () { + if (topNav != "settings") { + widget.navigator.push(CupertinoPageRoute(builder: (context) => const SettingsScreen())).then((value) => topNav = ""); + topNav = "settings"; + } + }, + ), + ]; + + buildAccountTiles(); + + List accountWidgets = [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12.0), + child: Column(children: accountTiles), + ), + + // Account settings + PanelButton( + onPressed: () { + Navigator.of(context).pushNamed("login_back"); + }, + title: const Text("Add User"), + leading: const Icon(FeatherIcons.userPlus), + ), + PanelButton( + onPressed: () async { + String? userId = user.id; + if (userId == null) return; + + // Delete User + user.removeUser(userId); + await Provider.of(context, listen: false).store.removeUser(userId); + + // If no other Users left, go back to LoginScreen + if (user.getUsers().isNotEmpty) { + user.setUser(user.getUsers().first.id); + restore().then((_) => user.setUser(user.getUsers().first.id)); + } else { + Navigator.of(context).pushNamedAndRemoveUntil("login", (_) => false); + } + }, + title: const Text("Log Out"), + leading: Icon(FeatherIcons.logOut, color: AppColors.of(context).red), + ), + ]; + + return SizedBox( + height: double.infinity, + width: 250.0, + child: Column( + children: [ + Padding( + padding: const EdgeInsets.only(left: 18.0, top: 18.0, bottom: 24.0, right: 8.0), + child: Row( + children: [ + Padding( + padding: const EdgeInsets.only(right: 12.0), + child: ProfileImage( + name: firstName, + radius: 18.0, + backgroundColor: + !settings.presentationMode ? ColorUtils.stringToColor(user.name ?? "?") : Theme.of(context).colorScheme.secondary, + ), + ), + Expanded( + child: Text( + firstName, + style: const TextStyle( + fontSize: 16.0, + fontWeight: FontWeight.w600, + ), + ), + ), + PageTransitionSwitcher( + transitionBuilder: (child, primaryAnimation, secondaryAnimation) { + return FadeThroughTransition( + fillColor: Colors.transparent, + animation: primaryAnimation, + secondaryAnimation: secondaryAnimation, + child: child, + ); + }, + child: IconButton( + key: Key(expandAccount ? "accounts" : "pages"), + icon: Icon(expandAccount ? FeatherIcons.chevronDown : FeatherIcons.chevronRight), + padding: EdgeInsets.zero, + splashRadius: 20.0, + onPressed: () { + setState(() { + expandAccount = !expandAccount; + }); + }, + ), + ), + ], + ), + ), + + // Pages + Expanded( + child: PageTransitionSwitcher( + duration: const Duration(milliseconds: 500), + transitionBuilder: (child, primaryAnimation, secondaryAnimation) { + return SharedAxisTransition( + fillColor: Colors.transparent, + animation: primaryAnimation, + secondaryAnimation: secondaryAnimation, + transitionType: SharedAxisTransitionType.scaled, + child: child, + ); + }, + child: !expandAccount + ? Column( + key: const Key("pages"), + children: pageWidgets, + ) + : Column( + key: const Key("accounts"), + children: accountWidgets, + ), + ), + ), + + // Settings + ...bottomActions, + + // Bottom padding + const SizedBox(height: 12.0), + ], + ), + ); + } + + void buildAccountTiles() { + accountTiles = []; + user.getUsers().forEach((account) { + if (account.id == user.id) return; + + String _firstName; + + List _nameParts = user.name?.split(" ") ?? ["?"]; + if (!settings.presentationMode) { + _firstName = _nameParts.length > 1 ? _nameParts[1] : _nameParts[0]; + } else { + _firstName = "Béla"; + } + + accountTiles.add(AccountTile( + name: Text(!settings.presentationMode ? account.name : "Béla", style: const TextStyle(fontWeight: FontWeight.w500)), + username: Text(!settings.presentationMode ? account.username : "72469696969"), + profileImage: ProfileImage( + name: _firstName, + backgroundColor: !settings.presentationMode ? ColorUtils.stringToColor(account.name) : Theme.of(context).colorScheme.secondary, + role: account.role, + ), + onTap: () { + user.setUser(account.id); + restore().then((_) => user.setUser(account.id)); + }, + // onTapMenu: () => _showBottomSheet(account), + )); + }); + } +} diff --git a/filcnaplo_desktop_ui/lib/screens/navigation/sidebar_action.dart b/filcnaplo_desktop_ui/lib/screens/navigation/sidebar_action.dart new file mode 100644 index 0000000..ca9b92f --- /dev/null +++ b/filcnaplo_desktop_ui/lib/screens/navigation/sidebar_action.dart @@ -0,0 +1,49 @@ +import 'package:flutter/material.dart'; +import 'package:filcnaplo/theme/colors/colors.dart'; + +class SidebarAction extends StatelessWidget { + const SidebarAction({Key? key, this.title, this.icon, this.onTap, this.selected = false}) : super(key: key); + + final bool selected; + final Widget? icon; + final Widget? title; + final Function()? onTap; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 2.0, horizontal: 12.0), + child: InkWell( + onTap: onTap, + borderRadius: BorderRadius.circular(12.0), + child: Padding( + padding: const EdgeInsets.all(8.0), + child: Row( + children: [ + if (icon != null) + IconTheme( + data: IconThemeData( + color: AppColors.of(context).text.withOpacity(selected ? 1.0 : .3), + ), + child: icon!, + ), + if (title != null) + Padding( + padding: const EdgeInsets.only(left: 24.0), + child: AnimatedDefaultTextStyle( + duration: const Duration(milliseconds: 500), + style: TextStyle( + color: AppColors.of(context).text.withOpacity(selected ? 1.0 : .8), + fontWeight: FontWeight.w500, + fontFamily: "Montserrat", + ), + child: title!, + ), + ), + ], + ), + ), + ), + ); + } +} diff --git a/filcnaplo_desktop_ui/lib/screens/news/news_view.dart b/filcnaplo_desktop_ui/lib/screens/news/news_view.dart new file mode 100644 index 0000000..9b6c307 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/screens/news/news_view.dart @@ -0,0 +1,10 @@ +import 'package:flutter/material.dart'; + +class NewsView extends StatelessWidget { + const NewsView({Key? key}) : super(key: key); + + @override + Widget build(BuildContext context) { + return Container(); + } +} diff --git a/filcnaplo_desktop_ui/lib/screens/settings/settings_screen.dart b/filcnaplo_desktop_ui/lib/screens/settings/settings_screen.dart new file mode 100644 index 0000000..52bd601 --- /dev/null +++ b/filcnaplo_desktop_ui/lib/screens/settings/settings_screen.dart @@ -0,0 +1,725 @@ +import 'package:filcnaplo/api/providers/update_provider.dart'; +import 'package:filcnaplo/theme/colors/accent.dart'; +import 'package:filcnaplo/theme/observer.dart'; +import 'package:filcnaplo_kreta_api/providers/absence_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/event_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/exam_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/grade_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/homework_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/message_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/note_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/timetable_provider.dart'; +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/utils/format.dart'; +import 'package:filcnaplo/models/settings.dart'; +import 'package:filcnaplo/models/user.dart'; +import 'package:filcnaplo/theme/colors/colors.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; +import 'package:filcnaplo_mobile_ui/common/action_button.dart'; +import 'package:filcnaplo_mobile_ui/common/bottom_sheet_menu/bottom_sheet_menu.dart'; +import 'package:filcnaplo_mobile_ui/common/bottom_sheet_menu/bottom_sheet_menu_item.dart'; +import 'package:filcnaplo_mobile_ui/common/panel/panel.dart'; +import 'package:filcnaplo_mobile_ui/common/panel/panel_button.dart'; +import 'package:filcnaplo_mobile_ui/common/profile_image/profile_image.dart'; +import 'package:filcnaplo_mobile_ui/common/widgets/update/updates_view.dart'; +import 'package:filcnaplo_mobile_ui/premium/premium_button.dart'; +import 'package:filcnaplo_mobile_ui/screens/news/news_screen.dart'; +import 'package:filcnaplo_mobile_ui/screens/settings/accounts/account_tile.dart'; +import 'package:filcnaplo_mobile_ui/screens/settings/accounts/account_view.dart'; +import 'package:filcnaplo_mobile_ui/screens/settings/debug/subject_icon_gallery.dart'; +import 'package:filcnaplo_mobile_ui/screens/settings/privacy_view.dart'; +import 'package:filcnaplo_mobile_ui/screens/settings/settings_helper.dart'; +import 'package:filcnaplo_premium/providers/premium_provider.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_custom_tabs/flutter_custom_tabs.dart' as tabs; +import 'package:flutter_feather_icons/flutter_feather_icons.dart'; +import 'package:provider/provider.dart'; +import 'package:filcnaplo/utils/color.dart'; +import 'package:url_launcher/url_launcher.dart'; +import 'settings_screen.i18n.dart'; +import 'package:flutter/services.dart'; +import 'package:filcnaplo_premium/ui/mobile/settings/nickname.dart'; +import 'package:filcnaplo_premium/ui/mobile/settings/icon_pack.dart'; + +class SettingsScreen extends StatefulWidget { + const SettingsScreen({Key? key}) : super(key: key); + + @override + _SettingsScreenState createState() => _SettingsScreenState(); +} + +class _SettingsScreenState extends State with SingleTickerProviderStateMixin { + int devmodeCountdown = 3; + final bool __ss = false; // secret settings + + late UserProvider user; + late UpdateProvider updateProvider; + late SettingsProvider settings; + late KretaClient kretaClient; + late String firstName; + List accountTiles = []; + + late AnimationController _hideContainersController; + + Future restore() => Future.wait([ + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restoreUser(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).restore(), + Provider.of(context, listen: false).refreshLogin(), + ]); + + void buildAccountTiles() { + accountTiles = []; + user.getUsers().forEach((account) { + if (account.id == user.id) return; + + String _firstName; + + List _nameParts = user.displayName?.split(" ") ?? ["?"]; + if (!settings.presentationMode) { + _firstName = _nameParts.length > 1 ? _nameParts[1] : _nameParts[0]; + } else { + _firstName = "Béla"; + } + + accountTiles.add(AccountTile( + name: Text(!settings.presentationMode ? account.name : "Béla", style: const TextStyle(fontWeight: FontWeight.w500)), + username: Text(!settings.presentationMode ? account.username : "72469696969"), + profileImage: ProfileImage( + name: _firstName, + backgroundColor: !settings.presentationMode ? ColorUtils.stringToColor(account.name) : Theme.of(context).colorScheme.secondary, + role: account.role, + ), + onTap: () { + user.setUser(account.id); + restore().then((_) => user.setUser(account.id)); + Navigator.of(context).pop(); + }, + onTapMenu: () => _showBottomSheet(account), + )); + }); + } + + void _showBottomSheet(User u) { + showBottomSheetMenu(context, items: [ + BottomSheetMenuItem( + onPressed: () => AccountView.show(u, context: context), + icon: const Icon(FeatherIcons.user), + title: Text("personal_details".i18n), + ), + BottomSheetMenuItem( + onPressed: () => _openDKT(u), + icon: Icon(FeatherIcons.grid, color: AppColors.of(context).teal), + title: Text("open_dkt".i18n), + ), + const UserMenuNickname(), + // BottomSheetMenuItem( + // onPressed: () {}, + // icon: Icon(FeatherIcons.camera), + // title: Text("edit_profile_picture".i18n), + // ), + // BottomSheetMenuItem( + // onPressed: () {}, + // icon: Icon(FeatherIcons.trash2, color: AppColors.of(context).red), + // title: Text("remove_profile_picture".i18n), + // ), + ]); + } + + void _openDKT(User u) => tabs.launch("https://dkttanulo.e-kreta.hu/sso?id_token=${kretaClient.idToken}", + customTabsOption: tabs.CustomTabsOption( + toolbarColor: Theme.of(context).scaffoldBackgroundColor, + showPageTitle: true, + )); + + @override + void initState() { + super.initState(); + _hideContainersController = AnimationController(vsync: this, duration: const Duration(milliseconds: 200)); + } + + @override + Widget build(BuildContext context) { + user = Provider.of(context); + settings = Provider.of(context); + updateProvider = Provider.of(context); + kretaClient = Provider.of(context); + + List nameParts = user.displayName?.split(" ") ?? ["?"]; + if (!settings.presentationMode) { + firstName = nameParts.length > 1 ? nameParts[1] : nameParts[0]; + } else { + firstName = "Béla"; + } + + String startPageTitle = SettingsHelper.localizedPageTitles()[settings.startPage] ?? "?"; + String themeModeText = {ThemeMode.light: "light".i18n, ThemeMode.dark: "dark".i18n, ThemeMode.system: "system".i18n}[settings.theme] ?? "?"; + String languageText = SettingsHelper.langMap[settings.language] ?? "?"; + String vibrateTitle = { + VibrationStrength.off: "voff".i18n, + VibrationStrength.light: "vlight".i18n, + VibrationStrength.medium: "vmedium".i18n, + VibrationStrength.strong: "vstrong".i18n, + }[settings.vibrate] ?? + "?"; + + buildAccountTiles(); + + if (settings.developerMode) devmodeCountdown = -1; + + return Scaffold( + body: Padding( + padding: const EdgeInsets.only(top: 11.5), + child: CustomScrollView( + slivers: [ + SliverAppBar( + pinned: true, + floating: true, + snap: false, + centerTitle: false, + title: const Text("Settings"), + surfaceTintColor: Theme.of(context).scaffoldBackgroundColor, + ), + SliverToBoxAdapter( + child: AnimatedBuilder( + animation: _hideContainersController, + builder: (context, child) => Opacity( + opacity: 1 - _hideContainersController.value, + child: SingleChildScrollView( + child: Column( + children: [ + const SizedBox(height: 32.0), + + // Updates + if (updateProvider.available) + Padding( + padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), + child: Panel( + child: PanelButton( + onPressed: () => _openUpdates(context), + title: Text("update_available".i18n), + leading: const Icon(FeatherIcons.download), + trailing: Text( + updateProvider.releases.first.tag, + style: TextStyle( + fontWeight: FontWeight.w500, + color: Theme.of(context).colorScheme.secondary, + ), + ), + ), + ), + ), + + // const Padding( + // padding: EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), + // child: PremiumBannerButton(), + // ), + if (!Provider.of(context).hasPremium) + const ClipRect( + child: Padding( + padding: EdgeInsets.symmetric(vertical: 12.0), + child: PremiumButton(), + ), + ), + + // General Settings + Padding( + padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), + child: Panel( + title: Text("general".i18n), + child: Column( + children: [ + PanelButton( + onPressed: () { + SettingsHelper.language(context); + setState(() {}); + }, + title: Text("language".i18n), + leading: const Icon(FeatherIcons.globe), + trailing: Text(languageText), + ), + PanelButton( + onPressed: () { + SettingsHelper.startPage(context); + setState(() {}); + }, + title: Text("startpage".i18n), + leading: const Icon(FeatherIcons.play), + trailing: Text(startPageTitle.capital()), + ), + PanelButton( + onPressed: () { + SettingsHelper.rounding(context); + setState(() {}); + }, + title: Text("rounding".i18n), + leading: const Icon(FeatherIcons.gitCommit), + trailing: Text((settings.rounding / 10).toStringAsFixed(1)), + ), + PanelButton( + onPressed: () { + SettingsHelper.vibrate(context); + setState(() {}); + }, + title: Text("vibrate".i18n), + leading: const Icon(FeatherIcons.radio), + trailing: Text(vibrateTitle), + ), + PanelButton( + padding: const EdgeInsets.only(left: 14.0), + onPressed: () { + SettingsHelper.bellDelay(context); + setState(() {}); + }, + title: Text( + "bell_delay".i18n, + style: TextStyle(color: AppColors.of(context).text.withOpacity(settings.bellDelayEnabled ? 1.0 : .5)), + ), + leading: settings.bellDelayEnabled + ? const Icon(FeatherIcons.bell) + : Icon(FeatherIcons.bellOff, color: AppColors.of(context).text.withOpacity(.25)), + trailingDivider: true, + trailing: Switch( + onChanged: (v) => settings.update(bellDelayEnabled: v), + value: settings.bellDelayEnabled, + activeColor: Theme.of(context).colorScheme.secondary, + ), + ), + ], + ), + ), + ), + + if (kDebugMode) + Padding( + padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), + child: Panel( + title: const Text("Debug"), + child: Column( + children: [ + PanelButton( + title: const Text("Subject Icon Gallery"), + leading: const Icon(CupertinoIcons.rectangle_3_offgrid_fill), + trailing: const Icon(Icons.arrow_forward), + onPressed: () { + Navigator.of(context, rootNavigator: true).push( + CupertinoPageRoute(builder: (context) => const SubjectIconGallery()), + ); + }, + ) + ], + ), + ), + ), + + // Secret Settings + if (__ss) + Padding( + padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), + child: Panel( + title: Text("secret".i18n), + child: Column( + children: [ + // Good student mode + Material( + type: MaterialType.transparency, + child: SwitchListTile( + contentPadding: const EdgeInsets.only(left: 12.0), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)), + title: Text("goodstudent".i18n, style: const TextStyle(fontWeight: FontWeight.w500)), + onChanged: (v) { + if (v) { + showDialog( + context: context, + builder: (context) => WillPopScope( + onWillPop: () async => false, + child: AlertDialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)), + title: Text("attention".i18n), + content: Text("goodstudent_disclaimer".i18n), + actions: [ + ActionButton( + label: "understand".i18n, + onTap: () { + Navigator.of(context).pop(); + settings.update(goodStudent: v); + Provider.of(context, listen: false).fetch(); + }) + ], + ), + ), + ); + } else { + settings.update(goodStudent: v); + Provider.of(context, listen: false).fetch(); + } + }, + value: settings.goodStudent, + activeColor: Theme.of(context).colorScheme.secondary, + ), + ), + + // Presentation mode + Material( + type: MaterialType.transparency, + child: SwitchListTile( + contentPadding: const EdgeInsets.only(left: 12.0), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)), + title: const Text("Presentation Mode", style: TextStyle(fontWeight: FontWeight.w500)), + onChanged: (v) => settings.update(presentationMode: v), + value: settings.presentationMode, + activeColor: Theme.of(context).colorScheme.secondary, + ), + ), + ], + ), + ), + ), + + // Theme Settings + Padding( + padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), + child: Panel( + title: Text("appearance".i18n), + child: Column( + children: [ + PanelButton( + onPressed: () { + SettingsHelper.theme(context); + setState(() {}); + }, + title: Text("theme".i18n), + leading: const Icon(FeatherIcons.sun), + trailing: Text(themeModeText), + ), + PanelButton( + onPressed: () async { + await _hideContainersController.forward(); + SettingsHelper.accentColor(context); + setState(() {}); + _hideContainersController.reset(); + }, + title: Text("color".i18n), + leading: const Icon(FeatherIcons.droplet), + trailing: Container( + width: 12.0, + height: 12.0, + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.secondary, + shape: BoxShape.circle, + ), + ), + ), + PanelButton( + onPressed: () { + SettingsHelper.gradeColors(context); + setState(() {}); + }, + title: Text("grade_colors".i18n), + leading: const Icon(FeatherIcons.star), + trailing: Row( + mainAxisSize: MainAxisSize.min, + children: List.generate( + 5, + (i) => Container( + margin: const EdgeInsets.only(left: 2.0), + width: 12.0, + height: 12.0, + decoration: BoxDecoration( + shape: BoxShape.circle, + color: settings.gradeColors[i], + ), + ), + ), + ), + ), + Material( + type: MaterialType.transparency, + child: SwitchListTile( + contentPadding: const EdgeInsets.only(left: 12.0), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)), + title: Row( + children: [ + Icon( + FeatherIcons.barChart, + color: settings.graphClassAvg + ? Theme.of(context).colorScheme.secondary + : AppColors.of(context).text.withOpacity(.25), + ), + const SizedBox(width: 24.0), + Expanded( + child: Text( + "graph_class_avg".i18n, + style: TextStyle( + fontWeight: FontWeight.w600, + fontSize: 16.0, + color: AppColors.of(context).text.withOpacity(settings.graphClassAvg ? 1.0 : .5), + ), + ), + ), + ], + ), + onChanged: (v) => settings.update(graphClassAvg: v), + value: settings.graphClassAvg, + activeColor: Theme.of(context).colorScheme.secondary, + ), + ), + const PremiumIconPackSelector(), + ], + ), + ), + ), + + // Notifications + Padding( + padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), + child: Panel( + title: Text("notifications".i18n), + child: Material( + type: MaterialType.transparency, + child: SwitchListTile( + contentPadding: const EdgeInsets.only(left: 12.0), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)), + title: Row( + children: [ + Icon( + Icons.newspaper_outlined, + color: settings.newsEnabled + ? Theme.of(context).colorScheme.secondary + : AppColors.of(context).text.withOpacity(.25), + ), + const SizedBox(width: 24.0), + Expanded( + child: Text( + "news".i18n, + style: TextStyle( + fontWeight: FontWeight.w600, + fontSize: 16.0, + color: AppColors.of(context).text.withOpacity(settings.newsEnabled ? 1.0 : .5), + ), + ), + ), + ], + ), + onChanged: (v) => settings.update(newsEnabled: v), + value: settings.newsEnabled, + activeColor: Theme.of(context).colorScheme.secondary, + ), + ), + ), + ), + + // Extras + Padding( + padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), + child: Panel( + title: Text("extras".i18n), + child: Column(children: [ + Material( + type: MaterialType.transparency, + child: SwitchListTile( + contentPadding: const EdgeInsets.only(left: 12.0), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)), + title: Row( + children: [ + Icon( + FeatherIcons.gift, + color: settings.gradeOpeningFun + ? Theme.of(context).colorScheme.secondary + : AppColors.of(context).text.withOpacity(.25), + ), + const SizedBox(width: 24.0), + Expanded( + child: Text( + "surprise_grades".i18n, + style: TextStyle( + fontWeight: FontWeight.w600, + fontSize: 16.0, + color: AppColors.of(context).text.withOpacity(settings.gradeOpeningFun ? 1.0 : .5), + ), + ), + ), + ], + ), + onChanged: (v) => settings.update(gradeOpeningFun: v), + value: settings.gradeOpeningFun, + activeColor: Theme.of(context).colorScheme.secondary, + ), + ), + ]), + ), + ), + + // About + Padding( + padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), + child: Panel( + title: Text("about".i18n), + child: Column(children: [ + PanelButton( + leading: const Icon(FeatherIcons.atSign), + title: const Text("Discord"), + onPressed: () => launchUrl(Uri.parse("https://filcnaplo.hu/discord"), mode: LaunchMode.externalApplication), + ), + PanelButton( + leading: const Icon(FeatherIcons.globe), + title: const Text("www.filcnaplo.hu"), + onPressed: () => launchUrl(Uri.parse("https://filcnaplo.hu"), mode: LaunchMode.externalApplication), + ), + PanelButton( + leading: const Icon(FeatherIcons.github), + title: const Text("Github"), + onPressed: () => launchUrl(Uri.parse("https://github.com/filc"), mode: LaunchMode.externalApplication), + ), + PanelButton( + leading: const Icon(FeatherIcons.mail), + title: Text("news".i18n), + onPressed: () => _openNews(context), + ), + PanelButton( + leading: const Icon(FeatherIcons.lock), + title: Text("privacy".i18n), + onPressed: () => _openPrivacy(context), + ), + PanelButton( + leading: const Icon(FeatherIcons.award), + title: Text("licenses".i18n), + onPressed: () => showLicensePage(context: context), + ), + Tooltip( + message: "data_collected".i18n, + padding: const EdgeInsets.all(4.0), + textStyle: TextStyle(fontWeight: FontWeight.w500, color: AppColors.of(context).text), + decoration: BoxDecoration(color: Theme.of(context).colorScheme.background), + child: Material( + type: MaterialType.transparency, + child: SwitchListTile( + contentPadding: const EdgeInsets.only(left: 12.0), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)), + secondary: Icon( + FeatherIcons.barChart2, + color: settings.xFilcId != "none" + ? Theme.of(context).colorScheme.secondary + : AppColors.of(context).text.withOpacity(.25), + ), + title: Text( + "Analytics".i18n, + style: TextStyle( + fontWeight: FontWeight.w600, + fontSize: 16.0, + color: AppColors.of(context).text.withOpacity(settings.xFilcId != "none" ? 1.0 : .5), + ), + ), + subtitle: Text( + "Anonymous Usage Analytics".i18n, + style: TextStyle( + color: AppColors.of(context).text.withOpacity(settings.xFilcId != "none" ? .5 : .2), + ), + ), + onChanged: (v) { + String newId; + if (v == false) { + newId = "none"; + } else if (settings.xFilcId == "none") { + newId = SettingsProvider.defaultSettings().xFilcId; + } else { + newId = settings.xFilcId; + } + settings.update(xFilcId: newId); + }, + value: settings.xFilcId != "none", + activeColor: Theme.of(context).colorScheme.secondary, + ), + ), + ), + ]), + ), + ), + if (settings.developerMode) + Padding( + padding: const EdgeInsets.symmetric(vertical: 12.0, horizontal: 24.0), + child: Panel( + title: const Text("Developer Settings"), + child: Column( + children: [ + Material( + type: MaterialType.transparency, + child: SwitchListTile( + contentPadding: const EdgeInsets.only(left: 12.0), + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12.0)), + title: const Text("Developer Mode", style: TextStyle(fontWeight: FontWeight.w500)), + onChanged: (v) => settings.update(developerMode: false), + value: settings.developerMode, + activeColor: Theme.of(context).colorScheme.secondary, + ), + ), + PanelButton( + leading: const Icon(FeatherIcons.copy), + title: const Text("Copy JWT"), + onPressed: () => + Clipboard.setData(ClipboardData(text: Provider.of(context, listen: false).accessToken)), + ), + if (Provider.of(context, listen: false).hasPremium) + PanelButton( + leading: const Icon(FeatherIcons.key), + title: const Text("Remove Premium"), + onPressed: () { + Provider.of(context, listen: false).activate(removePremium: true); + settings.update(accentColor: AccentColor.filc, store: true); + Provider.of(context, listen: false).changeTheme(settings.theme); + }, + ), + ], + ), + ), + ), + SafeArea( + top: false, + child: Center( + child: GestureDetector( + child: const Panel(title: Text("v" + String.fromEnvironment("APPVER", defaultValue: "?"))), + onTap: () { + if (devmodeCountdown > 0) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + duration: const Duration(milliseconds: 200), + content: Text("You are $devmodeCountdown taps away from Developer Mode."), + )); + + setState(() => devmodeCountdown--); + } else if (devmodeCountdown == 0) { + ScaffoldMessenger.of(context).showSnackBar(const SnackBar( + content: Text("Developer Mode successfully activated."), + )); + + settings.update(developerMode: true); + + setState(() => devmodeCountdown--); + } + }, + ), + ), + ), + ], + ), + ), + ), + ), + ) + ], + ), + ), + ); + } + + void _openNews(BuildContext context) => + Navigator.of(context, rootNavigator: true).push(CupertinoPageRoute(builder: (context) => const NewsScreen())); + void _openUpdates(BuildContext context) => UpdateView.show(updateProvider.releases.first, context: context); + void _openPrivacy(BuildContext context) => PrivacyView.show(context); +} diff --git a/filcnaplo_desktop_ui/lib/screens/settings/settings_screen.i18n.dart b/filcnaplo_desktop_ui/lib/screens/settings/settings_screen.i18n.dart new file mode 100644 index 0000000..59f373c --- /dev/null +++ b/filcnaplo_desktop_ui/lib/screens/settings/settings_screen.i18n.dart @@ -0,0 +1,188 @@ +import 'package:i18n_extension/i18n_extension.dart'; + +extension SettingsLocalization on String { + static final _t = Translations.byLocale("hu_hu") + + { + "en_en": { + "personal_details": "Personal Details", + "open_dkt": "Open DKT", + "edit_nickname": "Edit Nickname", + "edit_profile_picture": "Edit Profile Picture", + "remove_profile_picture": "Remove Profile Picture", + "light": "Light", + "dark": "Dark", + "system": "System", + "add_user": "Add User", + "log_out": "Log Out", + "update_available": "Update Available", + "general": "General", + "language": "Language", + "startpage": "Startpage", + "rounding": "Rounding", + "appearance": "Appearance", + "theme": "Theme", + "color": "Color", + "grade_colors": "Grade Colors", + "notifications": "Notifications", + "news": "News", + "extras": "Extras", + "about": "About", + "supporters": "Supporters", + "privacy": "Privacy Policy", + "licenses": "Licenses", + "vibrate": "Vibration", + "voff": "Off", + "vlight": "Light", + "vmedium": "Medium", + "vstrong": "Strong", + "cancel": "Cancel", + "done": "Done", + "reset": "Reset", + "open": "Open", + "data_collected": "Data collected: Platform (eg. Android), App version (eg. 3.0.0), Unique Install Identifier", + "Analytics": "Analytics", + "Anonymous Usage Analytics": "Anonymous Usage Analytics", + "graph_class_avg": "Class average on graph", + "goodstudent": "Good student mode", + "attention": "Attention!", + "goodstudent_disclaimer": + "Filc Napló® Informatikai Zrt. can not be held liable for the usage of this feature.\n\n(if your mother beats you up because you showed her fake grades, you can only blame yourself for it)", + "understand": "I understand", + "secret": "Secret Settings", + "bell_delay": "Bell Delay", + "delay": "Delay", + "hurry": "Hurry", + "sync": "Synchronize", + "sync_help": "Press the Synchronize button when the bell rings.", + "surprise_grades": "Surprise Grades", + "icon_pack": "Icon Pack", + "change_username": "Set a nickname", + "Accent Color": "Accent Color", + "Background Color": "Background Color", + "Highlight Color": "Highlight Color", + "Adaptive Theme": "Adaptive Theme", + }, + "hu_hu": { + "personal_details": "Személyes információk", + "open_dkt": "DKT megnyitása", + "edit_nickname": "Becenév szerkesztése", + "edit_profile_picture": "Profil-kép szerkesztése", + "remove_profile_picture": "Profil-kép törlése", + "light": "Világos", + "dark": "Sötét", + "system": "Rendszer", + "add_user": "Felhasználó hozzáadása", + "log_out": "Kijelentkezés", + "update_available": "Frissítés elérhető", + "general": "Általános", + "language": "Nyelv", + "startpage": "Kezdőlap", + "rounding": "Kerekítés", + "appearance": "Kinézet", + "theme": "Téma", + "color": "Színek", + "grade_colors": "Jegyek színei", + "notifications": "Értesítések", + "news": "Hírek", + "extras": "Extrák", + "about": "Névjegy", + "supporters": "Támogatók", + "privacy": "Adatvédelmi irányelvek", + "licenses": "Licenszek", + "vibrate": "Rezgés", + "voff": "Kikapcsolás", + "vlight": "Alacsony", + "vmedium": "Közepes", + "vstrong": "Erős", + "cancel": "Mégsem", + "done": "Kész", + "reset": "Visszaállítás", + "open": "Megnyitás", + "data_collected": "Gyűjtött adat: Platform (pl. Android), App verzió (pl. 3.0.0), Egyedi telepítési azonosító", + "Analytics": "Analitika", + "Anonymous Usage Analytics": "Névtelen használati analitika", + "graph_class_avg": "Osztályátlag a grafikonon", + "goodstudent": "Jó tanuló mód", + "attention": "Figyelem!", + "goodstudent_disclaimer": + "A Filc Napló® Informatikai Zrt. minden felelősséget elhárít a funkció használatával kapcsolatban.\n\n(Értsd: ha az anyád megver, mert megtévesztő ábrákat mutattál neki, azért csakis magadadat hibáztathatod.)", + "understand": "Értem", + "secret": "Titkos Beállítások", + "bell_delay": "Csengő eltolódása", + "delay": "Késleltetés", + "hurry": "Siettetés", + "sync": "Szinkronizálás", + "sync_help": "Csengetéskor nyomd meg a Szinkronizálás gombot.", + "surprise_grades": "Meglepetés jegyek", + "icon_pack": "Ikon séma", + "change_username": "Becenév beállítása", + "Accent Color": "Egyedi szín", + "Background Color": "Háttér színe", + "Highlight Color": "Panelek színe", + "Adaptive Theme": "Adaptív téma", + }, + "de_de": { + "personal_details": "Persönliche Angaben", + "open_dkt": "Öffnen DKT", + "edit_nickname": "Spitznamen bearbeiten", + "edit_profile_picture": "Profilbild bearbeiten", + "remove_profile_picture": "Profilbild entfernen", + "light": "Licht", + "dark": "Dunkel", + "system": "System", + "add_user": "Benutzer hinzufügen", + "log_out": "Abmelden", + "update_available": "Update verfügbar", + "general": "Allgemein", + "language": "Sprache", + "startpage": "Startseite", + "rounding": "Rundung", + "appearance": "Erscheinungsbild", + "theme": "Thema", + "color": "Farbe", + "grade_colors": "Grad Farben", + "notifications": "Benachrichtigungen", + "news": "Nachrichten", + "extras": "Extras", + "about": "Informationen", + "supporters": "Unterstützer", + "privacy": "Datenschutzbestimmungen", + "licenses": "Lizenzen", + "vibrate": "Vibration", + "voff": "Aus", + "vlight": "Leicht", + "vmedium": "Mittel", + "vstrong": "Stark", + "cancel": "Abbrechen", + "done": "Fertig", + "reset": "Zurücksetzen", + "open": "Öffnen", + "data_collected": "Erhobene Daten: Plattform (z.B. Android), App version (z.B. 3.0.0), Eindeutige Installationskennung", + "Analytics": "Analytik", + "Anonymous Usage Analytics": "Anonyme Nutzungsanalyse", + "graph_class_avg": "Klassendurchschnitt in der Grafik", + "goodstudent": "Guter Student Modus", + "attention": "Achtung!", + "goodstudent_disclaimer": "Same in English.", + "understand": "Ich verstehe", + "secret": "Geheime Einstellungen", + "bell_delay": "Klingelverzögerung", + "delay": "Verzögern", + "hurry": "Eile", + "sync": "Synchronisieren", + "sync_help": "Drücken Sie die Sync-Taste, wenn die Glocke läutet.", + "surprise_grades": "Überraschungsnoten", + "icon_pack": "Icon-Pack", + "change_username": "Einen Spitznamen festlegen", + "Accent Color": "Accent Color", + "Background Color": "Background Color", + "Highlight Color": "Highlight Color", + "Adaptive Theme": "Adaptive Theme", + }, + }; + + String get i18n => localize(this, _t); + String fill(List params) => localizeFill(this, params); + String plural(int value) => localizePlural(value, this, _t); + String version(Object modifier) => localizeVersion(modifier, this, _t); +} diff --git a/filcnaplo_desktop_ui/pubspec.yaml b/filcnaplo_desktop_ui/pubspec.yaml new file mode 100644 index 0000000..8e7a77b --- /dev/null +++ b/filcnaplo_desktop_ui/pubspec.yaml @@ -0,0 +1,36 @@ +name: filcnaplo_desktop_ui +publish_to: "none" + +environment: + sdk: ">=2.17.0 <3.0.0" + +dependencies: + flutter: + sdk: flutter + + # Filcnaplo main dep + filcnaplo: + path: ../filcnaplo/ + filcnaplo_kreta_api: + path: ../filcnaplo_kreta_api/ + + cupertino_icons: ^1.0.2 + flutter_feather_icons: ^2.0.0+1 + provider: ^5.0.0 + url_launcher: ^6.0.9 + flutter_linkify: ^5.0.2 + flutter_markdown: ^0.6.5 + animations: ^2.0.1 + confetti: ^0.6.0 + auto_size_text: ^3.0.0 + flutter_acrylic: + git: + url: https://github.com/filc/flutter_acrylic + ref: master + elegant_notification: ^1.6.1 + +dev_dependencies: + flutter_lints: ^1.0.0 + +flutter: + uses-material-design: true diff --git a/filcnaplo_kreta_api/LICENSE b/filcnaplo_kreta_api/LICENSE new file mode 100644 index 0000000..a23e6cd --- /dev/null +++ b/filcnaplo_kreta_api/LICENSE @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2021, Filc +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/filcnaplo_kreta_api/README.md b/filcnaplo_kreta_api/README.md new file mode 100644 index 0000000..e69de29 diff --git a/filcnaplo_kreta_api/analysis_options.yaml b/filcnaplo_kreta_api/analysis_options.yaml new file mode 100644 index 0000000..fd16f92 --- /dev/null +++ b/filcnaplo_kreta_api/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-lang.github.io/linter/lints/index.html. + # + # 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/filcnaplo_kreta_api/lib/client/api.dart b/filcnaplo_kreta_api/lib/client/api.dart new file mode 100644 index 0000000..5887ff6 --- /dev/null +++ b/filcnaplo_kreta_api/lib/client/api.dart @@ -0,0 +1,82 @@ +import 'package:intl/intl.dart'; + +class KretaAPI { + // IDP API + static const login = BaseKreta.kretaIdp + KretaApiEndpoints.token; + static const nonce = BaseKreta.kretaIdp + KretaApiEndpoints.nonce; + static const clientId = "kreta-ellenorzo-mobile-android"; + + // ELLENORZO API + static String notes(String iss) => BaseKreta.kreta(iss) + KretaApiEndpoints.notes; + static String events(String iss) => BaseKreta.kreta(iss) + KretaApiEndpoints.events; + static String student(String iss) => BaseKreta.kreta(iss) + KretaApiEndpoints.student; + static String grades(String iss) => BaseKreta.kreta(iss) + KretaApiEndpoints.grades; + static String absences(String iss) => BaseKreta.kreta(iss) + KretaApiEndpoints.absences; + static String groups(String iss) => BaseKreta.kreta(iss) + KretaApiEndpoints.groups; + static String groupAverages(String iss, String uid) => + BaseKreta.kreta(iss) + KretaApiEndpoints.groupAverages + "?oktatasiNevelesiFeladatUid=" + uid; + static String timetable(String iss, {DateTime? start, DateTime? end}) => + BaseKreta.kreta(iss) + + KretaApiEndpoints.timetable + + (start != null && end != null ? "?datumTol=" + start.toUtc().toIso8601String() + "&datumIg=" + end.toUtc().toIso8601String() : ""); + static String exams(String iss) => BaseKreta.kreta(iss) + KretaApiEndpoints.exams; + static String homework(String iss, {DateTime? start, String? id}) => + BaseKreta.kreta(iss) + + KretaApiEndpoints.homework + + (id != null ? "/$id" : "") + + (id == null && start != null ? "?datumTol=" + DateFormat('yyyy-MM-dd').format(start) : ""); + static String capabilities(String iss) => BaseKreta.kreta(iss) + KretaApiEndpoints.capabilities; + static String downloadHomeworkAttachments(String iss, String uid, String type) => + BaseKreta.kreta(iss) + KretaApiEndpoints.downloadHomeworkAttachments(uid, type); + + // ADMIN API + static const sendMessage = BaseKreta.kretaAdmin + KretaAdminEndpoints.sendMessage; + static String messages(String endpoint) => BaseKreta.kretaAdmin + KretaAdminEndpoints.messages(endpoint); + static String message(String id) => BaseKreta.kretaAdmin + KretaAdminEndpoints.message(id); + static const recipientCategories = BaseKreta.kretaAdmin + KretaAdminEndpoints.recipientCategories; + static const availableCategories = BaseKreta.kretaAdmin + KretaAdminEndpoints.availableCategories; + static const recipientsTeacher = BaseKreta.kretaAdmin + KretaAdminEndpoints.recipientsTeacher; + static const uploadAttachment = BaseKreta.kretaAdmin + KretaAdminEndpoints.uploadAttachment; + static String downloadAttachment(String id) => BaseKreta.kretaAdmin + KretaAdminEndpoints.downloadAttachment(id); + static const trashMessage = BaseKreta.kretaAdmin + KretaAdminEndpoints.trashMessage; + static const deleteMessage = BaseKreta.kretaAdmin + KretaAdminEndpoints.deleteMessage; +} + +class BaseKreta { + static String kreta(String iss) => "https://$iss.e-kreta.hu"; + static const kretaIdp = "https://idp.e-kreta.hu"; + static const kretaAdmin = "https://eugyintezes.e-kreta.hu"; + static const kretaFiles = "https://files.e-kreta.hu"; +} + +class KretaApiEndpoints { + static const token = "/connect/token"; + static const nonce = "/nonce"; + static const notes = "/ellenorzo/V3/Sajat/Feljegyzesek"; + static const events = "/ellenorzo/V3/Sajat/FaliujsagElemek"; + static const student = "/ellenorzo/V3/Sajat/TanuloAdatlap"; + static const grades = "/ellenorzo/V3/Sajat/Ertekelesek"; + static const absences = "/ellenorzo/V3/Sajat/Mulasztasok"; + static const groups = "/ellenorzo/V3/Sajat/OsztalyCsoportok"; + static const groupAverages = "/ellenorzo/V3/Sajat/Ertekelesek/Atlagok/OsztalyAtlagok"; + static const timetable = "/ellenorzo/V3/Sajat/OrarendElemek"; + static const exams = "/ellenorzo/V3/Sajat/BejelentettSzamonkeresek"; + static const homework = "/ellenorzo/V3/Sajat/HaziFeladatok"; + // static const homeworkDone = "/ellenorzo/V3/Sajat/HaziFeladatok/Megoldva"; // Removed from the API + static const capabilities = "/ellenorzo/V3/Sajat/Intezmenyek"; + static String downloadHomeworkAttachments(String uid, String type) => "/ellenorzo/V3/Sajat/Csatolmany/$uid"; +} + +class KretaAdminEndpoints { + //static const messages = "/api/v1/kommunikacio/postaladaelemek/sajat"; + static const sendMessage = "/api/v1/kommunikacio/uzenetek"; + static String messages(String endpoint) => "/api/v1/kommunikacio/postaladaelemek/$endpoint"; + static String message(String id) => "/api/v1/kommunikacio/postaladaelemek/$id"; + static const recipientCategories = "/api/v1/adatszotarak/cimzetttipusok"; + static const availableCategories = "/api/v1/kommunikacio/cimezhetotipusok"; + static const recipientsTeacher = "/api/v1/kreta/alkalmazottak/tanar"; + static const uploadAttachment = "/ideiglenesfajlok"; + static String downloadAttachment(String id) => "/api/v1/dokumentumok/uzenetek/$id"; + static const trashMessage = "/api/v1/kommunikacio/postaladaelemek/kuka"; + static const deleteMessage = "/api/v1/kommunikacio/postaladaelemek/torles"; +} diff --git a/filcnaplo_kreta_api/lib/client/client.dart b/filcnaplo_kreta_api/lib/client/client.dart new file mode 100644 index 0000000..6a5bbed --- /dev/null +++ b/filcnaplo_kreta_api/lib/client/client.dart @@ -0,0 +1,193 @@ +// ignore_for_file: avoid_print + +import 'dart:convert'; +import 'dart:io'; + +import 'package:filcnaplo/api/login.dart'; +import 'package:filcnaplo/api/nonce.dart'; +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/api/providers/status_provider.dart'; +import 'package:filcnaplo/models/settings.dart'; +import 'package:filcnaplo/models/user.dart'; +import 'package:filcnaplo/utils/jwt.dart'; +import 'package:filcnaplo_kreta_api/client/api.dart'; +import 'package:http/http.dart' as http; +import 'package:http/io_client.dart' as http; +import 'dart:async'; + +class KretaClient { + String? accessToken; + String? refreshToken; + String? idToken; + String? userAgent; + late http.Client client; + + late final SettingsProvider _settings; + late final UserProvider _user; + late final StatusProvider _status; + + KretaClient({ + this.accessToken, + required SettingsProvider settings, + required UserProvider user, + required StatusProvider status, + }) : _settings = settings, + _user = user, + _status = status, + userAgent = settings.config.userAgent { + var ioclient = HttpClient(); + ioclient.badCertificateCallback = _checkCerts; + client = http.IOClient(ioclient); + } + + bool _checkCerts(X509Certificate cert, String host, int port) { + return _settings.developerMode; + } + + Future getAPI( + String url, { + Map? headers, + bool autoHeader = true, + bool json = true, + bool rawResponse = false, + }) async { + Map headerMap; + + if (rawResponse) json = false; + + if (headers != null) { + headerMap = headers; + } else { + headerMap = {}; + } + + try { + http.Response? res; + + for (int i = 0; i < 3; i++) { + if (autoHeader) { + if (!headerMap.containsKey("authorization") && accessToken != null) headerMap["authorization"] = "Bearer $accessToken"; + if (!headerMap.containsKey("user-agent") && userAgent != null) headerMap["user-agent"] = "$userAgent"; + } + + res = await client.get(Uri.parse(url), headers: headerMap); + _status.triggerRequest(res); + + if (res.statusCode == 401) { + await refreshLogin(); + headerMap.remove("authorization"); + } else { + break; + } + + // Wait before retrying + await Future.delayed(const Duration(milliseconds: 500)); + } + + if (res == null) throw "Login error"; + + if (json) { + return jsonDecode(res.body); + } else if (rawResponse) { + return res.bodyBytes; + } else { + return res.body; + } + } on http.ClientException catch (error) { + print("ERROR: KretaClient.getAPI ($url) ClientException: ${error.message}"); + } catch (error) { + print("ERROR: KretaClient.getAPI ($url) ${error.runtimeType}: $error"); + } + } + + Future postAPI( + String url, { + Map? headers, + bool autoHeader = true, + bool json = true, + Object? body, + }) async { + Map headerMap; + + if (headers != null) { + headerMap = headers; + } else { + headerMap = {}; + } + + try { + http.Response? res; + + for (int i = 0; i < 3; i++) { + if (autoHeader) { + if (!headerMap.containsKey("authorization") && accessToken != null) headerMap["authorization"] = "Bearer $accessToken"; + if (!headerMap.containsKey("user-agent") && userAgent != null) headerMap["user-agent"] = "$userAgent"; + if (!headerMap.containsKey("content-type")) headerMap["content-type"] = "application/json"; + } + + res = await client.post(Uri.parse(url), headers: headerMap, body: body); + if (res.statusCode == 401) { + await refreshLogin(); + headerMap.remove("authorization"); + } else { + break; + } + } + + if (res == null) throw "Login error"; + + if (json) { + return jsonDecode(res.body); + } else { + return res.body; + } + } on http.ClientException catch (error) { + print("ERROR: KretaClient.getAPI ($url) ClientException: ${error.message}"); + } catch (error) { + print("ERROR: KretaClient.getAPI ($url) ${error.runtimeType}: $error"); + } + } + + Future refreshLogin() async { + User? loginUser = _user.user; + if (loginUser == null) return; + + Map headers = { + "content-type": "application/x-www-form-urlencoded", + }; + + String nonceStr = await getAPI(KretaAPI.nonce, json: false); + Nonce nonce = getNonce(nonceStr, loginUser.username, loginUser.instituteCode); + headers.addAll(nonce.header()); + + if (_settings.presentationMode) { + print("DEBUG: refreshLogin: ${loginUser.id}"); + } else { + print("DEBUG: refreshLogin: ${loginUser.id} ${loginUser.name}"); + } + + Map? loginRes = await postAPI(KretaAPI.login, + headers: headers, + body: User.loginBody( + username: loginUser.username, + password: loginUser.password, + instituteCode: loginUser.instituteCode, + )); + + if (loginRes != null) { + if (loginRes.containsKey("access_token")) accessToken = loginRes["access_token"]; + if (loginRes.containsKey("refresh_token")) refreshToken = loginRes["refresh_token"]; + + // Update role + loginUser.role = JwtUtils.getRoleFromJWT(accessToken ?? "") ?? Role.student; + } + + if (refreshToken != null) { + Map? refreshRes = await postAPI(KretaAPI.login, + headers: headers, body: User.refreshBody(refreshToken: refreshToken!, instituteCode: loginUser.instituteCode)); + if (refreshRes != null) { + if (refreshRes.containsKey("id_token")) idToken = refreshRes["id_token"]; + } + } + } +} diff --git a/filcnaplo_kreta_api/lib/controllers/timetable_controller.dart b/filcnaplo_kreta_api/lib/controllers/timetable_controller.dart new file mode 100644 index 0000000..9b7e0ef --- /dev/null +++ b/filcnaplo_kreta_api/lib/controllers/timetable_controller.dart @@ -0,0 +1,217 @@ +// ignore_for_file: avoid_print + +import 'dart:async'; +import 'dart:developer'; +import 'dart:math' as math; +import 'package:filcnaplo_kreta_api/providers/homework_provider.dart'; +import 'package:filcnaplo_kreta_api/providers/timetable_provider.dart'; +import 'package:filcnaplo_kreta_api/models/lesson.dart'; +import 'package:filcnaplo_kreta_api/models/week.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; +import 'package:provider/provider.dart'; + +enum LoadType { initial, offline, loading, online } + +class TimetableController extends ChangeNotifier { + late Week currentWeek; + int currentWeekId = -1; + late int previousWeekId; + List>? days; + LoadType loadType = LoadType.initial; + + TimetableController() { + current(); + } + + static int getWeekId(Week week) => (week.start.difference(getSchoolYearStart()).inDays / DateTime.daysPerWeek).ceil(); + + static DateTime getSchoolYearStart() { + DateTime now = DateTime.now(); + DateTime nowStart = _getYearStart(now.year); + + if (nowStart.isBefore(now)) { + return nowStart; + } else { + return _getYearStart(now.year - 1); + } + } + + static DateTime _getYearStart(int year) { + var s1 = DateTime(year, DateTime.september, 1); + if (s1.weekday == 6) { + s1.add(const Duration(days: 2)); + } else if (s1.weekday == 7) { + s1.add(const Duration(days: 1)); + } + return s1; + } + + // Jump shortcuts + Future next(BuildContext context) => jump(Week.fromId(currentWeekId + 1), context: context); + Future previous(BuildContext context) => jump(Week.fromId(currentWeekId - 1), context: context); + void current() { + Week week = Week.current(); + int id = getWeekId(week); + + if (id > 51) id = 51; + if (id < 0) id = 0; + + _setWeek(Week.fromId(id)); + } + + Future jump(Week week, {required BuildContext context, bool initial = false, bool skip = false, bool loader = true}) async { + if (_setWeek(week)) return; + + loadType = LoadType.initial; + + if (loader) { + days = null; + + // Don't start loading on init + if (!initial) notifyListeners(); + } + + days = _sortDays(week, context: context); + + if (week != currentWeek) return; + + loadType = LoadType.loading; + + notifyListeners(); + + try { + await _fetchWeek(week, context: context).timeout(const Duration(seconds: 5), onTimeout: (() => throw "timeout")); + loadType = LoadType.online; + } catch (error, stack) { + print("ERROR: TimetableController.jump: $error\n$stack"); + loadType = LoadType.offline; + } + + if (week != currentWeek) return; + + days = _sortDays(week, context: context); + + if (week != currentWeek) return; + + // Jump to next week on weekends + if (skip && (days?.length ?? 0) > 0 && days!.last.last.end.isBefore(DateTime.now())) return next(context); + + notifyListeners(); + } + + bool _setWeek(Week week) { + int id = getWeekId(week); + if (id > 51) return true; // Max 52. + if (id < 0) return true; // Min 1. + + // Set week start to Sept. 1 of first week + if (!_differentDate(week.start, Week.fromId(0).start)) week.start = TimetableController.getSchoolYearStart(); + + currentWeek = week; + previousWeekId = currentWeekId; + currentWeekId = id; + return false; + } + + Future _fetchWeek(Week week, {required BuildContext context}) async { + await Future.wait([ + context.read().fetch(week: week), + context.read().fetch(from: week.start, db: false), + ]); + } + + List> _sortDays(Week week, {required BuildContext context}) { + List> days = []; + + final timetableProvider = context.read(); + + try { + List lessons = timetableProvider.getWeek(week) ?? []; + + if (lessons.isNotEmpty) { + days.add([]); + lessons.sort((a, b) => a.date.compareTo(b.date)); + for (var lesson in lessons) { + if (days.last.isNotEmpty && _differentDate(lesson.date, days.last.last.date)) days.add([]); + days.last.add(lesson); + } + + for (int i = 0; i < days.length; i++) { + List _day = List.castFrom(days[i]); + + List lessonIndexes = _getIndexes(_day); + int minIndex = 0, maxIndex = 0; + + if (lessonIndexes.isNotEmpty) { + minIndex = lessonIndexes.reduce(math.min); + maxIndex = lessonIndexes.reduce(math.max); + } + + List day = []; + + if (lessonIndexes.isNotEmpty) { + // Fill missing indexes with empty spaces + for (var i in List.generate(maxIndex - minIndex + 1, (int i) => minIndex + i)) { + List indexLessons = _getLessonsByIndex(_day, i); + + // Empty lesson + if (indexLessons.isEmpty) { + // Get start date by previous lesson + List prevLesson = _getLessonsByIndex(day, i - 1); + try { + DateTime? startDate = prevLesson.last.start.add(const Duration(seconds: 1)); + indexLessons.add(Lesson.fromJson({'isEmpty': true, 'Oraszam': i, 'KezdetIdopont': startDate.toIso8601String()})); + // ignore: empty_catches + } catch (e) {} + } + + day.addAll(indexLessons); + } + } + + // Additional lessons + day.addAll(_day.where((l) => int.tryParse(l.lessonIndex) == null && l.subject.id != '')); + + day.sort((a, b) => a.start.compareTo(b.start)); + + // Special Dates + for (var l in _day) { + l.subject.id == '' ? day.insert(0, l) : null; + } + + days[i] = day; + } + } + } catch (e) { + log("_sortDays error: $e"); + } + + return days; + } + + List _getLessonsByIndex(List lessons, int index) { + List ret = []; + + for (var lesson in lessons) { + int? lessonIndex = int.tryParse(lesson.lessonIndex); + + if (lessonIndex != null && lessonIndex == index) { + ret.add(lesson); + } + } + + return ret; + } + + List _getIndexes(List lessons) { + List indexes = []; + for (var l in lessons) { + int? index = int.tryParse(l.lessonIndex); + if (index != null) indexes.add(index); + } + return indexes; + } + + bool _differentDate(DateTime a, DateTime b) => !(a.year == b.year && a.month == b.month && a.day == b.day); +} diff --git a/filcnaplo_kreta_api/lib/models/absence.dart b/filcnaplo_kreta_api/lib/models/absence.dart new file mode 100644 index 0000000..45ca79d --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/absence.dart @@ -0,0 +1,76 @@ +import "category.dart"; +import "subject.dart"; + +class Absence { + Map? json; + String id; + DateTime date; + int delay; + DateTime submitDate; + String teacher; + Justification state; + Category? justification; + Category? type; + Category? mode; + Subject subject; + DateTime lessonStart; + DateTime lessonEnd; + int? lessonIndex; + String group; + + Absence({ + required this.id, + required this.date, + required this.delay, + required this.submitDate, + required this.teacher, + required this.state, + this.justification, + this.type, + this.mode, + required this.subject, + required this.lessonStart, + required this.lessonEnd, + this.lessonIndex, + required this.group, + this.json, + }); + + factory Absence.fromJson(Map json) { + DateTime lessonStart; + DateTime lessonEnd; + int? lessonIndex; + if (json["Ora"] != null) { + lessonStart = json["Ora"]["KezdoDatum"] != null ? DateTime.parse(json["Ora"]["KezdoDatum"]).toLocal() : DateTime(0); + lessonEnd = json["Ora"]["VegDatum"] != null ? DateTime.parse(json["Ora"]["VegDatum"]).toLocal() : DateTime(0); + lessonIndex = json["Ora"]["Oraszam"]; + } else { + lessonStart = DateTime(0); + lessonEnd = DateTime(0); + } + + return Absence( + id: json["Uid"], + date: json["Datum"] != null ? DateTime.parse(json["Datum"]).toLocal() : DateTime(0), + delay: json["KesesPercben"] ?? 0, + submitDate: json["KeszitesDatuma"] != null ? DateTime.parse(json["KeszitesDatuma"]).toLocal() : DateTime(0), + teacher: (json["RogzitoTanarNeve"] ?? "").trim(), + state: json["IgazolasAllapota"] == "Igazolt" + ? Justification.excused + : json["IgazolasAllapota"] == "Igazolando" + ? Justification.pending + : Justification.unexcused, + justification: json["IgazolasTipusa"] != null ? Category.fromJson(json["IgazolasTipusa"]) : null, + type: json["Tipus"] != null ? Category.fromJson(json["Tipus"]) : null, + mode: json["Mod"] != null ? Category.fromJson(json["Mod"]) : null, + subject: Subject.fromJson(json["Tantargy"] ?? {}), + lessonStart: lessonStart, + lessonEnd: lessonEnd, + lessonIndex: lessonIndex, + group: json["OsztalyCsoport"] != null ? json["OsztalyCsoport"]["Uid"] : "", + json: json, + ); + } +} + +enum Justification { excused, unexcused, pending } \ No newline at end of file diff --git a/filcnaplo_kreta_api/lib/models/attachment.dart b/filcnaplo_kreta_api/lib/models/attachment.dart new file mode 100644 index 0000000..0cab365 --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/attachment.dart @@ -0,0 +1,32 @@ +import 'package:file_picker/file_picker.dart'; +import 'package:filcnaplo_kreta_api/client/api.dart'; + +class Attachment { + Map? json; + int id; + PlatformFile? file; + String name; + String? fileId; + String kretaFilePath; + + Attachment({ + required this.id, + this.file, + required this.name, + this.fileId, + required this.kretaFilePath, + this.json, + }); + + factory Attachment.fromJson(Map json) { + return Attachment( + id: json["azonosito"], + name: (json["fajlNev"] ?? "attachment").trim(), + kretaFilePath: json["utvonal"] ?? "", + json: json, + ); + } + + String get downloadUrl => KretaAPI.downloadAttachment(id.toString()); + bool get isImage => name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png"); +} diff --git a/filcnaplo_kreta_api/lib/models/category.dart b/filcnaplo_kreta_api/lib/models/category.dart new file mode 100644 index 0000000..144e1e9 --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/category.dart @@ -0,0 +1,44 @@ +import 'grade.dart'; + +class Category { + String id; + String description; + String name; + + Category({ + required this.id, + this.description = "", + this.name = "", + }); + + factory Category.fromJson(Map json) { + return Category( + id: json["Uid"] ?? "", + description: json["Leiras"] != "Na" ? json["Leiras"] ?? "" : "", + name: json["Nev"] != "Na" ? json["Nev"] ?? "" : "", + ); + } + + static GradeType getGradeType(String string) { + switch (string) { + case "evkozi_jegy_ertekeles": + return GradeType.midYear; + case "I_ne_jegy_ertekeles": + return GradeType.firstQ; + case "II_ne_jegy_ertekeles": + return GradeType.secondQ; + case "felevi_jegy_ertekeles": + return GradeType.halfYear; + case "III_ne_jegy_ertekeles": + return GradeType.thirdQ; + case "IV_ne_jegy_ertekeles": + return GradeType.fourthQ; + case "evvegi_jegy_ertekeles": + return GradeType.endYear; + case "osztalyozo_vizsga": + return GradeType.levelExam; + default: + return GradeType.unknown; + } + } +} diff --git a/filcnaplo_kreta_api/lib/models/event.dart b/filcnaplo_kreta_api/lib/models/event.dart new file mode 100644 index 0000000..26aa057 --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/event.dart @@ -0,0 +1,28 @@ +class Event { + Map? json; + String id; + DateTime start; + DateTime end; + String title; + String content; + + Event({ + required this.id, + required this.start, + required this.end, + this.title = "", + this.content = "", + this.json, + }); + + factory Event.fromJson(Map json) { + return Event( + id: json["Uid"] ?? "", + start: json["ErvenyessegKezdete"] != null ? DateTime.parse(json["ErvenyessegKezdete"]).toLocal() : DateTime(0), + end: json["ErvenyessegVege"] != null ? DateTime.parse(json["ErvenyessegVege"]).toLocal() : DateTime(0), + title: json["Cim"] ?? "", + content: json["Tartalom"] != null ? json["Tartalom"].replaceAll("\r", "") : "", + json: json, + ); + } +} diff --git a/filcnaplo_kreta_api/lib/models/exam.dart b/filcnaplo_kreta_api/lib/models/exam.dart new file mode 100644 index 0000000..1d1a1bc --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/exam.dart @@ -0,0 +1,42 @@ +import 'category.dart'; + +class Exam { + Map? json; + DateTime date; + DateTime writeDate; + Category? mode; + int? subjectIndex; + String subjectName; + String teacher; + String description; + String group; + String id; + + Exam({ + required this.id, + required this.date, + required this.writeDate, + this.mode, + this.subjectIndex, + required this.subjectName, + required this.teacher, + required this.description, + required this.group, + this.json, + }); + + factory Exam.fromJson(Map json) { + return Exam( + id: json["Uid"] ?? "", + date: json["BejelentesDatuma"] != null ? DateTime.parse(json["BejelentesDatuma"]).toLocal() : DateTime(0), + writeDate: json["Datum"] != null ? DateTime.parse(json["Datum"]).toLocal() : DateTime(0), + mode: json["Modja"] != null ? Category.fromJson(json["Modja"]) : null, + subjectIndex: json["OrarendiOraOraszama"], + subjectName: json["TantargyNeve"] ?? "", + teacher: (json["RogzitoTanarNeve"] ?? "").trim(), + description: (json["Temaja"] ?? "").trim(), + group: json["OsztalyCsoport"] != null ? json["OsztalyCsoport"]["Uid"] ?? "" : "", + json: json, + ); + } +} diff --git a/filcnaplo_kreta_api/lib/models/grade.dart b/filcnaplo_kreta_api/lib/models/grade.dart new file mode 100644 index 0000000..1b6f8cd --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/grade.dart @@ -0,0 +1,120 @@ +import 'package:filcnaplo/utils/format.dart'; +import 'category.dart'; +import 'subject.dart'; + +class Grade { + Map? json; + String id; + DateTime date; + GradeValue value; + String teacher; + String description; + GradeType type; + String groupId; + Subject subject; + Category? gradeType; + Category mode; + DateTime writeDate; + DateTime seenDate; + String form; + + Grade({ + required this.id, + required this.date, + required this.value, + required this.teacher, + required this.description, + required this.type, + required this.groupId, + required this.subject, + this.gradeType, + required this.mode, + required this.writeDate, + required this.seenDate, + required this.form, + this.json, + }); + + factory Grade.fromJson(Map json) { + return Grade( + id: json["Uid"] ?? "", + date: json["KeszitesDatuma"] != null ? DateTime.parse(json["KeszitesDatuma"]).toLocal() : DateTime(0), + value: GradeValue( + json["SzamErtek"] ?? 0, + json["SzovegesErtek"] ?? "", + json["SzovegesErtekelesRovidNev"] ?? "", + json["SulySzazalekErteke"] ?? 0, + percentage: json["ErtekFajta"] != null ? json["ErtekFajta"]["Uid"] == "3,Szazalekos" : false, + ), + teacher: (json["ErtekeloTanarNeve"] ?? "").trim(), + description: json["Tema"] ?? "", + type: json["Tipus"] != null ? Category.getGradeType(json["Tipus"]["Nev"]) : GradeType.unknown, + groupId: (json["OsztalyCsoport"] ?? {})["Uid"] ?? "", + subject: Subject.fromJson(json["Tantargy"] ?? {}), + gradeType: json["ErtekFajta"] != null ? Category.fromJson(json["ErtekFajta"]) : null, + mode: Category.fromJson(json["Mod"] ?? {}), + writeDate: json["RogzitesDatuma"] != null ? DateTime.parse(json["RogzitesDatuma"]).toLocal() : DateTime(0), + seenDate: json["LattamozasDatuma"] != null ? DateTime.parse(json["LattamozasDatuma"]).toLocal() : DateTime(0), + form: (json["Jelleg"] ?? "Na") != "Na" ? json["Jelleg"] : "", + json: json, + ); + } + + bool compareTo(dynamic other) { + if (runtimeType != other.runtimeType) return false; + + if (id == other.id && seenDate == other.seenDate) { + return true; + } + + return false; + } +} + +class GradeValue { + int _value; + set value(int v) => _value = v; + int get value { + String _valueName = valueName.toLowerCase().specialChars(); + if (_value == 0 && ["peldas", "jo", "valtozo", "rossz", "hanyag"].contains(_valueName)) { + switch (_valueName) { + case "peldas": + return 5; + case "jo": + return 4; + case "valtozo": + return 3; + case "rossz": + return 2; + case "hanyag": + return 2; + } + } + return _value; + } + + String _valueName; + set valueName(String v) => _valueName = v; + String get valueName => _valueName.split("(")[0]; + String shortName; + int _weight; + set weight(int v) => _weight = v; + int get weight { + String _valueName = valueName.toLowerCase().specialChars(); + if (_value == 0 && ["peldas", "jo", "valtozo", "rossz", "hanyag"].contains(_valueName)) { + return 0; + } + return _weight; + } + + final bool _percentage; + bool get percentage => _percentage; + + GradeValue(int value, String valueName, this.shortName, int weight, {bool percentage = false}) + : _value = value, + _valueName = valueName, + _weight = weight, + _percentage = percentage; +} + +enum GradeType { midYear, firstQ, secondQ, halfYear, thirdQ, fourthQ, endYear, levelExam, ghost, unknown } diff --git a/filcnaplo_kreta_api/lib/models/group_average.dart b/filcnaplo_kreta_api/lib/models/group_average.dart new file mode 100644 index 0000000..ac1414b --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/group_average.dart @@ -0,0 +1,19 @@ +import 'package:filcnaplo_kreta_api/models/subject.dart'; + +class GroupAverage { + String uid; + double average; + Subject subject; + Map json; + + GroupAverage({required this.uid, required this.average, required this.subject, this.json = const {}}); + + factory GroupAverage.fromJson(Map json) { + return GroupAverage( + uid: json["Uid"] ?? "", + average: json["OsztalyCsoportAtlag"] ?? 0, + subject: Subject.fromJson(json["Tantargy"] ?? {}), + json: json, + ); + } +} diff --git a/filcnaplo_kreta_api/lib/models/homework.dart b/filcnaplo_kreta_api/lib/models/homework.dart new file mode 100644 index 0000000..5f4f39a --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/homework.dart @@ -0,0 +1,69 @@ +import 'package:filcnaplo_kreta_api/client/api.dart'; + +class Homework { + Map? json; + DateTime date; + DateTime lessonDate; + DateTime deadline; + bool byTeacher; + bool homeworkEnabled; + String teacher; + String content; + String subjectName; + String group; + List attachments; + String id; + + Homework({ + required this.date, + required this.lessonDate, + required this.deadline, + required this.byTeacher, + required this.homeworkEnabled, + required this.teacher, + required this.content, + required this.subjectName, + required this.group, + required this.attachments, + required this.id, + this.json, + }); + + factory Homework.fromJson(Map json) { + return Homework( + id: json["Uid"] ?? "", + date: json["RogzitesIdopontja"] != null ? DateTime.parse(json["RogzitesIdopontja"]).toLocal() : DateTime(0), + lessonDate: json["FeladasDatuma"] != null ? DateTime.parse(json["FeladasDatuma"]).toLocal() : DateTime(0), + deadline: json["HataridoDatuma"] != null ? DateTime.parse(json["HataridoDatuma"]).toLocal() : DateTime(0), + byTeacher: json["IsTanarRogzitette"] ?? true, + homeworkEnabled: json["IsTanuloHaziFeladatEnabled"] ?? false, + teacher: (json["RogzitoTanarNeve"] ?? "").trim(), + content: (json["Szoveg"] ?? "").trim(), + subjectName: json["TantargyNeve"] ?? "", + group: json["OsztalyCsoport"] != null ? json["OsztalyCsoport"]["Uid"] ?? "" : "", + attachments: ((json["Csatolmanyok"] ?? []) as List).cast().map((Map json) => HomeworkAttachment.fromJson(json)).toList(), + json: json, + ); + } +} + +class HomeworkAttachment { + Map? json; + String id; + String name; + String type; + + HomeworkAttachment({required this.id, this.name = "", this.type = "", this.json}); + + factory HomeworkAttachment.fromJson(Map json) { + return HomeworkAttachment( + id: json["Uid"] ?? "", + name: json["Nev"] ?? "", + type: json["Tipus"] ?? "", + json: json, + ); + } + + String downloadUrl(String iss) => KretaAPI.downloadHomeworkAttachments(iss, id, type); + bool get isImage => name.endsWith(".jpg") || name.endsWith(".jpeg") || name.endsWith(".png"); +} diff --git a/filcnaplo_kreta_api/lib/models/lesson.dart b/filcnaplo_kreta_api/lib/models/lesson.dart new file mode 100644 index 0000000..3ebf4e1 --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/lesson.dart @@ -0,0 +1,97 @@ +import 'subject.dart'; +import 'category.dart'; + +class Lesson { + Map? json; + Category? status; + DateTime date; + Subject subject; + String lessonIndex; + int? lessonYearIndex; + String substituteTeacher; + String teacher; + bool homeworkEnabled; + DateTime start; + DateTime end; + bool studentPresence; + String homeworkId; + String exam; + String id; + Category? type; + String description; + String room; + String groupName; + String name; + bool online; + bool isEmpty; + + Lesson({ + this.status, + required this.date, + required this.subject, + required this.lessonIndex, + this.lessonYearIndex, + this.substituteTeacher = "", + required this.teacher, + this.homeworkEnabled = false, + required this.start, + required this.end, + this.studentPresence = true, + required this.homeworkId, + this.exam = "", + required this.id, + this.type, + required this.description, + required this.room, + required this.groupName, + required this.name, + this.online = false, + this.isEmpty = false, + this.json, + }); + + factory Lesson.fromJson(Map json) { + return Lesson( + id: json["Uid"] ?? "", + status: json["Allapot"] != null ? Category.fromJson(json["Allapot"]) : null, + date: json["Datum"] != null ? DateTime.parse(json["Datum"]).toLocal() : DateTime(0), + subject: Subject.fromJson(json["Tantargy"] ?? {}), + lessonIndex: json["Oraszam"] != null ? json["Oraszam"].toString() : "+", + lessonYearIndex: json["OraEvesSorszama"], + substituteTeacher: (json["HelyettesTanarNeve"] ?? "").trim(), + teacher: (json["TanarNeve"] ?? "").trim(), + homeworkEnabled: json["IsTanuloHaziFeladatEnabled"] ?? false, + start: json["KezdetIdopont"] != null ? DateTime.parse(json["KezdetIdopont"]).toLocal() : DateTime(0), + studentPresence: json["TanuloJelenlet"] != null + ? (json["TanuloJelenlet"]["Nev"] ?? "") == "Hianyzas" + ? false + : true + : true, + end: json["VegIdopont"] != null ? DateTime.parse(json["VegIdopont"]).toLocal() : DateTime(0), + homeworkId: json["HaziFeladatUid"] ?? "", + exam: json["BejelentettSzamonkeresUid"] ?? "", + type: json["Tipus"] != null ? Category.fromJson(json["Tipus"]) : null, + description: json["Tema"] ?? "", + room: ((json["TeremNeve"] ?? "").split("_").join(" ") as String).replaceAll(RegExp(r" ?terem ?", caseSensitive: false), ""), + groupName: json["OsztalyCsoport"] != null ? json["OsztalyCsoport"]["Nev"] ?? "" : "", + name: json["Nev"] ?? "", + online: json["IsDigitalisOra"] ?? false, + isEmpty: json['isEmpty'] ?? false, + json: json, + ); + } + + int? getFloor() { + final match = RegExp(r"(\d{3})").firstMatch(room); + if (match != null) { + final floorNumber = int.tryParse(match[0] ?? ""); + if (floorNumber != null) { + return (floorNumber / 100).floor(); + } + } + return null; + } + + bool get isChanged => status?.name == "Elmaradt" || substituteTeacher != ""; + bool get swapDesc => room.length > 8; +} diff --git a/filcnaplo_kreta_api/lib/models/message.dart b/filcnaplo_kreta_api/lib/models/message.dart new file mode 100644 index 0000000..8e95878 --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/message.dart @@ -0,0 +1,97 @@ +import 'recipient.dart'; +import 'attachment.dart'; + +class Message { + Map? json; + int id; + int? replyId; + int messageId; + int? conversationId; + bool seen; + bool deleted; + DateTime date; + String author; + String content; + String subject; + MessageType? type; + List recipients; + List attachments; + + Message({ + required this.id, + required this.messageId, + required this.seen, + required this.deleted, + required this.date, + required this.author, + required this.content, + required this.subject, + this.type, + required this.recipients, + required this.attachments, + this.replyId, + this.conversationId, + this.json, + }); + + factory Message.fromJson(Map json, {MessageType? forceType}) { + Map message = json["uzenet"]; + + MessageType? type = forceType; + if (type == null) { + switch (json["tipus"]["kod"]) { + case "BEERKEZETT": + type = MessageType.inbox; + break; + case "ELKULDOTT": + type = MessageType.sent; + break; + case "PISZKOZAT": + type = MessageType.draft; + break; + } + + if (json["isToroltElem"] == true) type = MessageType.trash; + } + + return Message( + id: json["azonosito"], + messageId: message["azonosito"], + seen: json["isElolvasva"] ?? false, + deleted: json["isToroltElem"] ?? false, + date: message["kuldesDatum"] != null ? DateTime.parse(message["kuldesDatum"]).toLocal() : DateTime(0), + author: (message["feladoNev"] ?? "").trim(), + content: message["szoveg"].replaceAll("\r", "") ?? "", + subject: message["targy"] ?? "", + type: type, + recipients: (message["cimzettLista"] as List).cast().map((Map recipient) => Recipient.fromJson(recipient)).toList(), + attachments: (message["csatolmanyok"] as List).cast().map((Map attachment) => Attachment.fromJson(attachment)).toList(), + replyId: message["elozoUzenetAzonosito"], + conversationId: message["beszelgetesAzonosito"], + json: json, + ); + } + + bool compareTo(dynamic other) { + if (runtimeType != other.runtimeType) return false; + + return id == other.id && seen == other.seen && deleted == other.deleted; + } +} + +enum MessageType { inbox, sent, trash, draft } + +class Conversation { + int id; + late List _messages; + List get messages => _messages; + + Conversation({required this.id, List messages = const []}) { + _messages = List.from(messages); + } + + void sort() => _messages.sort((a, b) => -a.date.compareTo(b.date)); + void add(Message message) => _messages.add(message); + + Message get newest => _messages.first; +} diff --git a/filcnaplo_kreta_api/lib/models/note.dart b/filcnaplo_kreta_api/lib/models/note.dart new file mode 100644 index 0000000..183c0a3 --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/note.dart @@ -0,0 +1,42 @@ +import 'category.dart'; + +class Note { + Map? json; + String id; + String title; + DateTime date; + DateTime submitDate; + String teacher; + DateTime seenDate; + String groupId; + String content; + Category? type; + + Note({ + required this.id, + required this.title, + required this.date, + required this.submitDate, + required this.teacher, + required this.seenDate, + required this.groupId, + required this.content, + this.type, + this.json, + }); + + factory Note.fromJson(Map json) { + return Note( + id: json["Uid"] ?? "", + title: json["Cim"] ?? "", + date: json["Datum"] != null ? DateTime.parse(json["Datum"]).toLocal() : DateTime(0), + submitDate: json["KeszitesDatuma"] != null ? DateTime.parse(json["KeszitesDatuma"]).toLocal() : DateTime(0), + teacher: (json["KeszitoTanarNeve"] ?? "").trim(), + seenDate: json["LattamozasDatuma"] != null ? DateTime.parse(json["LattamozasDatuma"]).toLocal() : DateTime(0), + groupId: json["OsztalyCsoport"] != null ? json["OsztalyCsoport"]["Uid"] ?? "" : "", + content: json["Tartalom"].replaceAll("\r", "") ?? "", + type: json["Tipus"] != null ? Category.fromJson(json["Tipus"]) : null, + json: json, + ); + } +} diff --git a/filcnaplo_kreta_api/lib/models/recipient.dart b/filcnaplo_kreta_api/lib/models/recipient.dart new file mode 100644 index 0000000..cc7805c --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/recipient.dart @@ -0,0 +1,56 @@ +class Recipient { + Map? json; + int id; + String? studentId; // oktatasi azonosito + int kretaId; + String name; + RecipientCategory? category; + + Recipient({ + required this.id, + this.studentId, + required this.name, + required this.kretaId, + this.category, + this.json, + }); + + factory Recipient.fromJson(Map json) { + return Recipient( + id: json["azonosito"], + name: json["nev"] ?? "", + kretaId: json["kretaAzonosito"], + category: json["tipus"] != null ? RecipientCategory.fromJson(json["tipus"]) : null, + json: json, + ); + } +} + +class RecipientCategory { + Map? json; + int id; + String code; + String shortName; + String name; + String description; + + RecipientCategory({ + required this.id, + required this.code, + required this.shortName, + required this.name, + required this.description, + this.json, + }); + + factory RecipientCategory.fromJson(Map json) { + return RecipientCategory( + id: json["azonosito"], + code: json["kod"] ?? "", + shortName: json["rovidNev"] ?? "", + name: json["nev"] ?? "", + description: json["leiras"] ?? "", + json: json, + ); + } +} diff --git a/filcnaplo_kreta_api/lib/models/school.dart b/filcnaplo_kreta_api/lib/models/school.dart new file mode 100644 index 0000000..999b302 --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/school.dart @@ -0,0 +1,19 @@ +class School { + String instituteCode; + String name; + String city; + + School({ + required this.instituteCode, + required this.name, + required this.city, + }); + + factory School.fromJson(Map json) { + return School( + instituteCode: json["instituteCode"] ?? "", + name: (json["name"] ?? "").trim(), + city: json["city"] ?? "", + ); + } +} diff --git a/filcnaplo_kreta_api/lib/models/student.dart b/filcnaplo_kreta_api/lib/models/student.dart new file mode 100644 index 0000000..399cc86 --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/student.dart @@ -0,0 +1,55 @@ +import 'school.dart'; +import 'package:filcnaplo/utils/format.dart'; + +class Student { + Map? json; + String id; + String name; + School school; + DateTime birth; + String yearId; + String? address; + String? groupId; + List parents; + String? className; + + Student({ + required this.id, + required this.name, + required this.school, + required this.birth, + required this.yearId, + this.address, + required this.parents, + this.json, + }); + + factory Student.fromJson(Map json) { + List parents = []; + + parents = ((json["Gondviselok"] ?? []) as List).cast().map((e) => e["Nev"] ?? "").toList().cast(); + if (json["AnyjaNeve"] != null) parents.insert(0, json["AnyjaNeve"]); + + parents = parents.map((e) => e.capitalize()).toList(); // fix name casing + parents = parents.toSet().toList(); // remove duplicates + + return Student( + id: json["Uid"] ?? "", + name: (json["Nev"] ?? json["SzuletesiNev"] ?? "").trim(), + school: School( + instituteCode: json["IntezmenyAzonosito"] ?? "", + name: json["IntezmenyNev"] ?? "", + city: "", + ), + birth: json["SzuletesiDatum"] != null ? DateTime.parse(json["SzuletesiDatum"]).toLocal() : DateTime(0), + yearId: json["TanevUid"] ?? "", + address: json["Cimek"] != null + ? json["Cimek"].length > 0 + ? json["Cimek"][0] + : null + : null, + parents: parents, + json: json, + ); + } +} diff --git a/filcnaplo_kreta_api/lib/models/subject.dart b/filcnaplo_kreta_api/lib/models/subject.dart new file mode 100644 index 0000000..6adc113 --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/subject.dart @@ -0,0 +1,30 @@ +import 'category.dart'; + +class Subject { + String id; + Category category; + String name; + String? renamedTo; + + bool get isRenamed => renamedTo != null; + + Subject({required this.id, required this.category, required this.name, this.renamedTo}); + + factory Subject.fromJson(Map json) { + final id = json["Uid"] ?? ""; + return Subject( + id: id, + category: Category.fromJson(json["Kategoria"] ?? {}), + name: (json["Nev"] ?? "").trim(), + ); + } + + @override + bool operator ==(other) { + if (other is! Subject) return false; + return id == other.id; + } + + @override + int get hashCode => id.hashCode; +} diff --git a/filcnaplo_kreta_api/lib/models/week.dart b/filcnaplo_kreta_api/lib/models/week.dart new file mode 100644 index 0000000..3698957 --- /dev/null +++ b/filcnaplo_kreta_api/lib/models/week.dart @@ -0,0 +1,41 @@ +import 'package:filcnaplo_kreta_api/controllers/timetable_controller.dart'; + +class Week { + DateTime start; + DateTime end; + + Week({required this.start, required this.end}); + + factory Week.current() => Week.fromDate(DateTime.now()); + + factory Week.fromId(int id) { + DateTime _now = TimetableController.getSchoolYearStart().add(Duration(days: id * DateTime.daysPerWeek)); + DateTime now = DateTime(_now.year, _now.month, _now.day); + return Week( + start: now.subtract(Duration(days: now.weekday - 1)), + end: now.add(Duration(days: DateTime.daysPerWeek - now.weekday)), + ); + } + + factory Week.fromDate(DateTime date) { + // fix #32 + DateTime _date = DateTime(date.year, date.month, date.day); + return Week( + start: _date.subtract(Duration(days: _date.weekday - 1)), + end: _date.add(Duration(days: DateTime.daysPerWeek - _date.weekday)), + ); + } + + Week next() => Week.fromDate(start.add(const Duration(days: 8))); + + int get id => -(TimetableController.getSchoolYearStart().difference(start).inDays / DateTime.daysPerWeek).floor(); + + @override + String toString() => "Week(start: $start, end: $end)"; + + @override + bool operator ==(Object other) => other is Week && id == other.id; + + @override + int get hashCode => id; +} diff --git a/filcnaplo_kreta_api/lib/providers/absence_provider.dart b/filcnaplo_kreta_api/lib/providers/absence_provider.dart new file mode 100644 index 0000000..9fc5f47 --- /dev/null +++ b/filcnaplo_kreta_api/lib/providers/absence_provider.dart @@ -0,0 +1,73 @@ +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/api/providers/database_provider.dart'; +import 'package:filcnaplo/models/user.dart'; +import 'package:filcnaplo_kreta_api/client/api.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; +import 'package:filcnaplo_kreta_api/models/absence.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class AbsenceProvider with ChangeNotifier { + late List _absences; + late BuildContext _context; + List get absences => _absences; + + AbsenceProvider({ + List initialAbsences = const [], + required BuildContext context, + }) { + _absences = List.castFrom(initialAbsences); + _context = context; + + if (_absences.isEmpty) restore(); + } + + Future restore() async { + String? userId = Provider.of(_context, listen: false).id; + + // Load absences from the database + if (userId != null) { + var dbAbsences = await Provider.of(_context, listen: false).userQuery.getAbsences(userId: userId); + _absences = dbAbsences; + await convertBySettings(); + } + } + + // for renamed subjects + Future convertBySettings() async { + final _database = Provider.of(_context, listen: false); + Map renamedSubjects = (await _database.query.getSettings(_database)).renamedSubjectsEnabled + ? await _database.userQuery.renamedSubjects(userId: Provider.of(_context, listen: false).user!.id) + : {}; + + for (Absence absence in _absences) { + absence.subject.renamedTo = renamedSubjects.isNotEmpty ? renamedSubjects[absence.subject.id] : null; + } + + notifyListeners(); + } + + // Fetches Absences from the Kreta API then stores them in the database + Future fetch() async { + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot fetch Absences for User null"; + String iss = user.instituteCode; + + List? absencesJson = await Provider.of(_context, listen: false).getAPI(KretaAPI.absences(iss)); + if (absencesJson == null) throw "Cannot fetch Absences for User ${user.id}"; + List absences = absencesJson.map((e) => Absence.fromJson(e)).toList(); + + if (absences.isNotEmpty || _absences.isNotEmpty) await store(absences); + } + + // Stores Absences in the database + Future store(List absences) async { + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot store Absences for User null"; + String userId = user.id; + + await Provider.of(_context, listen: false).userStore.storeAbsences(absences, userId: userId); + _absences = absences; + await convertBySettings(); + } +} diff --git a/filcnaplo_kreta_api/lib/providers/event_provider.dart b/filcnaplo_kreta_api/lib/providers/event_provider.dart new file mode 100644 index 0000000..8c4f8ec --- /dev/null +++ b/filcnaplo_kreta_api/lib/providers/event_provider.dart @@ -0,0 +1,59 @@ +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/api/providers/database_provider.dart'; +import 'package:filcnaplo/models/user.dart'; +import 'package:filcnaplo_kreta_api/client/api.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; +import 'package:filcnaplo_kreta_api/models/event.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class EventProvider with ChangeNotifier { + late List _events; + late BuildContext _context; + List get events => _events; + + EventProvider({ + List initialEvents = const [], + required BuildContext context, + }) { + _events = List.castFrom(initialEvents); + _context = context; + + if (_events.isEmpty) restore(); + } + + Future restore() async { + String? userId = Provider.of(_context, listen: false).id; + + // Load events from the database + if (userId != null) { + var dbEvents = await Provider.of(_context, listen: false).userQuery.getEvents(userId: userId); + _events = dbEvents; + notifyListeners(); + } + } + + // Fetches Events from the Kreta API then stores them in the database + Future fetch() async { + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot fetch Events for User null"; + String iss = user.instituteCode; + + List? eventsJson = await Provider.of(_context, listen: false).getAPI(KretaAPI.events(iss)); + if (eventsJson == null) throw "Cannot fetch Events for User ${user.id}"; + List events = eventsJson.map((e) => Event.fromJson(e)).toList(); + + if (events.isNotEmpty || _events.isNotEmpty) await store(events); + } + + // Stores Events in the database + Future store(List events) async { + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot store Events for User null"; + String userId = user.id; + + await Provider.of(_context, listen: false).userStore.storeEvents(events, userId: userId); + _events = events; + notifyListeners(); + } +} diff --git a/filcnaplo_kreta_api/lib/providers/exam_provider.dart b/filcnaplo_kreta_api/lib/providers/exam_provider.dart new file mode 100644 index 0000000..1ff787f --- /dev/null +++ b/filcnaplo_kreta_api/lib/providers/exam_provider.dart @@ -0,0 +1,59 @@ +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/api/providers/database_provider.dart'; +import 'package:filcnaplo/models/user.dart'; +import 'package:filcnaplo_kreta_api/client/api.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; +import 'package:filcnaplo_kreta_api/models/exam.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class ExamProvider with ChangeNotifier { + late List _exams; + late BuildContext _context; + List get exams => _exams; + + ExamProvider({ + List initialExams = const [], + required BuildContext context, + }) { + _exams = List.castFrom(initialExams); + _context = context; + + if (_exams.isEmpty) restore(); + } + + Future restore() async { + String? userId = Provider.of(_context, listen: false).id; + + // Load exams from the database + if (userId != null) { + var dbExams = await Provider.of(_context, listen: false).userQuery.getExams(userId: userId); + _exams = dbExams; + notifyListeners(); + } + } + + // Fetches Exams from the Kreta API then stores them in the database + Future fetch() async { + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot fetch Exams for User null"; + String iss = user.instituteCode; + + List? examsJson = await Provider.of(_context, listen: false).getAPI(KretaAPI.exams(iss)); + if (examsJson == null) throw "Cannot fetch Exams for User ${user.id}"; + List exams = examsJson.map((e) => Exam.fromJson(e)).toList(); + + if (exams.isNotEmpty || _exams.isNotEmpty) await store(exams); + } + + // Stores Exams in the database + Future store(List exams) async { + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot store Exams for User null"; + String userId = user.id; + + await Provider.of(_context, listen: false).userStore.storeExams(exams, userId: userId); + _exams = exams; + notifyListeners(); + } +} diff --git a/filcnaplo_kreta_api/lib/providers/grade_provider.dart b/filcnaplo_kreta_api/lib/providers/grade_provider.dart new file mode 100644 index 0000000..56dbafa --- /dev/null +++ b/filcnaplo_kreta_api/lib/providers/grade_provider.dart @@ -0,0 +1,134 @@ +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/api/providers/database_provider.dart'; +import 'package:filcnaplo/models/settings.dart'; +import 'package:filcnaplo/models/user.dart'; +import 'package:filcnaplo_kreta_api/client/api.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; +import 'package:filcnaplo_kreta_api/models/grade.dart'; +import 'package:filcnaplo_kreta_api/models/group_average.dart'; +import 'package:flutter/material.dart'; + +class GradeProvider with ChangeNotifier { + // Private + late List _grades; + late DateTime _lastSeen; + late String _groups; + List _groupAvg = []; + late final SettingsProvider _settings; + late final UserProvider _user; + late final DatabaseProvider _database; + late final KretaClient _kreta; + + // Public + List get grades => _grades; + DateTime get lastSeenDate => _settings.gradeOpeningFun ? _lastSeen : DateTime(3000); + String get groups => _groups; + List get groupAverages => _groupAvg; + + GradeProvider({ + List initialGrades = const [], + required SettingsProvider settings, + required UserProvider user, + required DatabaseProvider database, + required KretaClient kreta, + }) { + _settings = settings; + _user = user; + _database = database; + _kreta = kreta; + + _grades = List.castFrom(initialGrades); + _lastSeen = DateTime.now(); + + if (_grades.isEmpty) restore(); + } + + Future seenAll() async { + String? userId = _user.id; + if (userId != null) { + final userStore = _database.userStore; + userStore.storeLastSeenGrade(DateTime.now(), userId: userId); + _lastSeen = DateTime.now(); + notifyListeners(); + } + } + + Future restore() async { + String? userId = _user.id; + + // Load grades from the database + if (userId != null) { + final userQuery = _database.userQuery; + + _grades = await userQuery.getGrades(userId: userId); + await convertBySettings(); + _groupAvg = await userQuery.getGroupAverages(userId: userId); + notifyListeners(); + DateTime lastSeenDB = await userQuery.lastSeenGrade(userId: userId); + if (lastSeenDB.millisecondsSinceEpoch == 0 || lastSeenDB.year == 0 || !_settings.gradeOpeningFun) { + _lastSeen = DateTime.now(); + await seenAll(); + } else { + _lastSeen = lastSeenDB; + } + notifyListeners(); + } + } + + // good student mode, renamed subjects + Future convertBySettings() async { + Map renamedSubjects = _settings.renamedSubjectsEnabled ? await _database.userQuery.renamedSubjects(userId: _user.user!.id) : {}; + + for (Grade grade in _grades) { + grade.subject.renamedTo = renamedSubjects.isNotEmpty ? renamedSubjects[grade.subject.id] : null; + grade.value.value = _settings.goodStudent ? 5 : grade.json!["SzamErtek"] ?? 0; + grade.value.valueName = _settings.goodStudent ? "Példás" : grade.json!["SzovegesErtek"] ?? ""; + grade.value.shortName = _settings.goodStudent ? "Példás" : grade.json!["SzovegesErtekelesRovidNev"] ?? ""; + } + + notifyListeners(); + } + + // Fetches Grades from the Kreta API then stores them in the database + Future fetch() async { + User? user = _user.user; + if (user == null) throw "Cannot fetch Grades for User null"; + String iss = user.instituteCode; + + List? gradesJson = await _kreta.getAPI(KretaAPI.grades(iss)); + if (gradesJson == null) throw "Cannot fetch Grades for User ${user.id}"; + List grades = gradesJson.map((e) => Grade.fromJson(e)).toList(); + + if (grades.isNotEmpty || _grades.isNotEmpty) await store(grades); + + List? groupsJson = await _kreta.getAPI(KretaAPI.groups(iss)); + if (groupsJson == null || groupsJson.isEmpty) throw "Cannot fetch Groups for User ${user.id}"; + _groups = (groupsJson[0]["OktatasNevelesiFeladat"] ?? {})["Uid"] ?? ""; + + List? groupAvgJson = await _kreta.getAPI(KretaAPI.groupAverages(iss, _groups)); + if (groupAvgJson == null) throw "Cannot fetch Class Averages for User ${user.id}"; + final groupAvgs = groupAvgJson.map((e) => GroupAverage.fromJson(e)).toList(); + await storeGroupAvg(groupAvgs); + } + + // Stores Grades in the database + Future store(List grades) async { + User? user = _user.user; + if (user == null) throw "Cannot store Grades for User null"; + String userId = user.id; + + await _database.userStore.storeGrades(grades, userId: userId); + _grades = grades; + await convertBySettings(); + } + + Future storeGroupAvg(List groupAvgs) async { + _groupAvg = groupAvgs; + + User? user = _user.user; + if (user == null) throw "Cannot store Grades for User null"; + String userId = user.id; + await _database.userStore.storeGroupAverages(groupAvgs, userId: userId); + notifyListeners(); + } +} diff --git a/filcnaplo_kreta_api/lib/providers/homework_provider.dart b/filcnaplo_kreta_api/lib/providers/homework_provider.dart new file mode 100644 index 0000000..f3a30dc --- /dev/null +++ b/filcnaplo_kreta_api/lib/providers/homework_provider.dart @@ -0,0 +1,65 @@ +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/api/providers/database_provider.dart'; +import 'package:filcnaplo/models/user.dart'; +import 'package:filcnaplo_kreta_api/client/api.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; +import 'package:filcnaplo_kreta_api/models/homework.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class HomeworkProvider with ChangeNotifier { + late List _homework; + late BuildContext _context; + List get homework => _homework; + + HomeworkProvider({ + List initialHomework = const [], + required BuildContext context, + }) { + _homework = List.castFrom(initialHomework); + _context = context; + + if (_homework.isEmpty) restore(); + } + + Future restore() async { + String? userId = Provider.of(_context, listen: false).id; + + // Load homework from the database + if (userId != null) { + var dbHomework = await Provider.of(_context, listen: false).userQuery.getHomework(userId: userId); + _homework = dbHomework; + notifyListeners(); + } + } + + // Fetches Homework from the Kreta API then stores them in the database + Future fetch({DateTime? from, bool db = true}) async { + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot fetch Homework for User null"; + + String iss = user.instituteCode; + List? homeworkJson = await Provider.of(_context, listen: false).getAPI(KretaAPI.homework(iss, start: from)); + if (homeworkJson == null) throw "Cannot fetch Homework for User ${user.id}"; + + List homework = []; + await Future.forEach(homeworkJson.cast(), (Map hw) async { + Map? e = await Provider.of(_context, listen: false).getAPI(KretaAPI.homework(iss, id: hw["Uid"])); + if (e != null) homework.add(Homework.fromJson(e)); + }); + + if (homework.isEmpty && _homework.isEmpty) return; + + if (db) await store(homework); + _homework = homework; + notifyListeners(); + } + + // Stores Homework in the database + Future store(List homework) async { + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot store Homework for User null"; + String userId = user.id; + await Provider.of(_context, listen: false).userStore.storeHomework(homework, userId: userId); + } +} diff --git a/filcnaplo_kreta_api/lib/providers/message_provider.dart b/filcnaplo_kreta_api/lib/providers/message_provider.dart new file mode 100644 index 0000000..dfb55c3 --- /dev/null +++ b/filcnaplo_kreta_api/lib/providers/message_provider.dart @@ -0,0 +1,80 @@ +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/api/providers/database_provider.dart'; +import 'package:filcnaplo/models/user.dart'; +import 'package:filcnaplo_kreta_api/client/api.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; +import 'package:filcnaplo_kreta_api/models/message.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class MessageProvider with ChangeNotifier { + late List _messages; + late BuildContext _context; + List get messages => _messages; + + MessageProvider({ + List initialMessages = const [], + required BuildContext context, + }) { + _messages = List.castFrom(initialMessages); + _context = context; + + if (_messages.isEmpty) restore(); + } + + Future restore() async { + String? userId = Provider.of(_context, listen: false).id; + + // Load messages from the database + if (userId != null) { + var dbMessages = await Provider.of(_context, listen: false).userQuery.getMessages(userId: userId); + _messages = dbMessages; + notifyListeners(); + } + } + + // Fetches all types of Messages + Future fetchAll() => Future.forEach(MessageType.values, (MessageType v) => fetch(type: v)); + + // Fetches Messages from the Kreta API then stores them in the database + Future fetch({MessageType type = MessageType.inbox}) async { + // Check Message Type + if (type == MessageType.draft) return; + String messageType = ["beerkezett", "elkuldott", "torolt"].elementAt(type.index); + + // Check User + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot fetch Messages for User null"; + + // Get messages + List? messagesJson = await Provider.of(_context, listen: false).getAPI(KretaAPI.messages(messageType)); + if (messagesJson == null) throw "Cannot fetch Messages for User ${user.id}"; + + // Parse messages + List messages = []; + await Future.wait(List.generate(messagesJson.length, (index) { + return () async { + Map message = messagesJson.cast()[index]; + Map? messageJson = await Provider.of(_context, listen: false).getAPI(KretaAPI.message(message["azonosito"].toString())); + if (messageJson != null) messages.add(Message.fromJson(messageJson, forceType: type)); + }(); + })); + + await store(messages, type); + } + + // Stores Messages in the database + Future store(List messages, MessageType type) async { + // Only store the specified type + _messages.removeWhere((m) => m.type == type); + _messages.addAll(messages); + + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot store Messages for User null"; + + String userId = user.id; + await Provider.of(_context, listen: false).userStore.storeMessages(_messages, userId: userId); + + notifyListeners(); + } +} diff --git a/filcnaplo_kreta_api/lib/providers/note_provider.dart b/filcnaplo_kreta_api/lib/providers/note_provider.dart new file mode 100644 index 0000000..20ecac8 --- /dev/null +++ b/filcnaplo_kreta_api/lib/providers/note_provider.dart @@ -0,0 +1,59 @@ +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/api/providers/database_provider.dart'; +import 'package:filcnaplo/models/user.dart'; +import 'package:filcnaplo_kreta_api/client/api.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; +import 'package:filcnaplo_kreta_api/models/note.dart'; +import 'package:flutter/material.dart'; +import 'package:provider/provider.dart'; + +class NoteProvider with ChangeNotifier { + late List _notes; + late BuildContext _context; + List get notes => _notes; + + NoteProvider({ + List initialNotes = const [], + required BuildContext context, + }) { + _notes = List.castFrom(initialNotes); + _context = context; + + if (_notes.isEmpty) restore(); + } + + Future restore() async { + String? userId = Provider.of(_context, listen: false).id; + + // Load notes from the database + if (userId != null) { + var dbNotes = await Provider.of(_context, listen: false).userQuery.getNotes(userId: userId); + _notes = dbNotes; + notifyListeners(); + } + } + + // Fetches Notes from the Kreta API then stores them in the database + Future fetch() async { + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot fetch Notes for User null"; + String iss = user.instituteCode; + + List? notesJson = await Provider.of(_context, listen: false).getAPI(KretaAPI.notes(iss)); + if (notesJson == null) throw "Cannot fetch Notes for User ${user.id}"; + List notes = notesJson.map((e) => Note.fromJson(e)).toList(); + + if (notes.isNotEmpty || _notes.isNotEmpty) await store(notes); + } + + // Stores Notes in the database + Future store(List notes) async { + User? user = Provider.of(_context, listen: false).user; + if (user == null) throw "Cannot store Notes for User null"; + String userId = user.id; + + await Provider.of(_context, listen: false).userStore.storeNotes(notes, userId: userId); + _notes = notes; + notifyListeners(); + } +} diff --git a/filcnaplo_kreta_api/lib/providers/timetable_provider.dart b/filcnaplo_kreta_api/lib/providers/timetable_provider.dart new file mode 100644 index 0000000..634ce12 --- /dev/null +++ b/filcnaplo_kreta_api/lib/providers/timetable_provider.dart @@ -0,0 +1,92 @@ +import 'package:filcnaplo/api/providers/user_provider.dart'; +import 'package:filcnaplo/api/providers/database_provider.dart'; +import 'package:filcnaplo/models/user.dart'; +import 'package:filcnaplo_kreta_api/client/api.dart'; +import 'package:filcnaplo_kreta_api/client/client.dart'; +import 'package:filcnaplo_kreta_api/models/lesson.dart'; +import 'package:filcnaplo_kreta_api/models/week.dart'; +import 'package:flutter/material.dart'; + +class TimetableProvider with ChangeNotifier { + Map> _lessons = {}; + late final UserProvider _user; + late final DatabaseProvider _database; + late final KretaClient _kreta; + + TimetableProvider({ + required UserProvider user, + required DatabaseProvider database, + required KretaClient kreta, + }) : _user = user, + _database = database, + _kreta = kreta { + restoreUser(); + } + + Future restoreUser() async { + String? userId = _user.id; + + // Load lessons from the database + if (userId != null) { + var dbLessons = await _database.userQuery.getLessons(userId: userId); + _lessons = dbLessons; + await convertBySettings(); + } + } + + // for renamed subjects + Future convertBySettings() async { + Map renamedSubjects = + (await _database.query.getSettings(_database)).renamedSubjectsEnabled ? await _database.userQuery.renamedSubjects(userId: _user.id!) : {}; + + for (Lesson lesson in _lessons.values.expand((e) => e)) { + lesson.subject.renamedTo = renamedSubjects.isNotEmpty ? renamedSubjects[lesson.subject.id] : null; + } + + notifyListeners(); + } + + List? getWeek(Week week) => _lessons[week]; + + // Fetches Lessons from the Kreta API then stores them in the database + Future fetch({Week? week}) async { + if (week == null) return; + User? user = _user.user; + if (user == null) throw "Cannot fetch Lessons for User null"; + String iss = user.instituteCode; + List? lessonsJson = await _kreta.getAPI(KretaAPI.timetable(iss, start: week.start, end: week.end)); + if (lessonsJson == null) throw "Cannot fetch Lessons for User ${user.id}"; + List lessons = lessonsJson.map((e) => Lesson.fromJson(e)).toList(); + + if (lessons.isEmpty && _lessons.isEmpty) return; + + _lessons[week] = lessons; + + await store(); + await convertBySettings(); + } + + // Stores Lessons in the database + Future store() async { + User? user = _user.user; + if (user == null) throw "Cannot store Lessons for User null"; + String userId = user.id; + + // TODO: clear indexes with weeks outside of the current school year + await _database.userStore.storeLessons(_lessons, userId: userId); + } + + // Future setLessonCount(SubjectLessonCount lessonCount, {bool store = true}) async { + // _subjectLessonCount = lessonCount; + + // if (store) { + // User? user = Provider.of(_context, listen: false).user; + // if (user == null) throw "Cannot store Lesson Count for User null"; + // String userId = user.id; + + // await Provider.of(_context, listen: false).userStore.storeSubjectLessonCount(lessonCount, userId: userId); + // } + + // notifyListeners(); + // } +} diff --git a/filcnaplo_kreta_api/pubspec.yaml b/filcnaplo_kreta_api/pubspec.yaml new file mode 100644 index 0000000..d52a527 --- /dev/null +++ b/filcnaplo_kreta_api/pubspec.yaml @@ -0,0 +1,20 @@ +name: filcnaplo_kreta_api +publish_to: "none" + +environment: + sdk: ">=2.17.0 <3.0.0" + +dependencies: + flutter: + sdk: flutter + filcnaplo: + path: ../filcnaplo/ + http: ^0.13.3 + provider: ^5.0.0 + file_picker: + git: + url: https://github.com/filc/flutter_file_picker.git + ref: master + +dev_dependencies: + flutter_lints: ^1.0.0