diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9ac0801 --- /dev/null +++ b/.gitignore @@ -0,0 +1,54 @@ +# Xcode & macOS + +# OS X temporary files that should never be committed +.DS_Store +*.swp +*.lock +profile + +# Xcode temporary files that should never be committed +*~.nib + +# Xcode build files +DerivedData/ +build/ +.build/ + +# Xcode private settings (window sizes, bookmarks, breakpoints, custom executables, smart groups) +*.pbxuser +*.mode1v3 +*.mode2v3 +*.perspectivev3 +!default.pbxuser +!default.mode1v3 +!default.mode2v3 +!default.perspectivev3 +xcuserdata +xcuserdata/**/* + +# Cocoapods: cocoapods.org +Pods/ +Podfile.lock + +## Obj-C/Swift specific +*.hmap + +## App packaging +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +Packages/ +Package.pins +Package.resolved + +# fastlane +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/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/Modules/AppNotifications/.gitignore b/Modules/AppNotifications/.gitignore new file mode 100644 index 0000000..95c4320 --- /dev/null +++ b/Modules/AppNotifications/.gitignore @@ -0,0 +1,5 @@ +.DS_Store +/.build +/Packages +/*.xcodeproj +xcuserdata/ diff --git a/Modules/AppNotifications/Package.swift b/Modules/AppNotifications/Package.swift new file mode 100644 index 0000000..0df604b --- /dev/null +++ b/Modules/AppNotifications/Package.swift @@ -0,0 +1,32 @@ +// swift-tools-version:5.3 +// The swift-tools-version declares the minimum version of Swift required to build this package. + +import PackageDescription + +let package = Package( + name: "AppNotifications", + platforms: [ + .iOS(.v14), + .macOS(.v11) + ], + products: [ + // Products define the executables and libraries a package produces, and make them visible to other packages. + .library( + name: "AppNotifications", + targets: ["AppNotifications"]), + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + // .package(url: /* package url */, from: "1.0.0"), + ], + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages this package depends on. + .target( + name: "AppNotifications", + dependencies: []), + .testTarget( + name: "AppNotificationsTests", + dependencies: ["AppNotifications"]), + ] +) diff --git a/Modules/AppNotifications/README.md b/Modules/AppNotifications/README.md new file mode 100644 index 0000000..41a429a --- /dev/null +++ b/Modules/AppNotifications/README.md @@ -0,0 +1,6 @@ +# AppNotifications + +App notifications overlay. + +## Usage +Add the `.appNotificationOverlay()` modifier to the selected view (i.e. root app view). diff --git a/Modules/AppNotifications/Sources/AppNotifications/AppNotifications.swift b/Modules/AppNotifications/Sources/AppNotifications/AppNotifications.swift new file mode 100644 index 0000000..8d602c7 --- /dev/null +++ b/Modules/AppNotifications/Sources/AppNotifications/AppNotifications.swift @@ -0,0 +1,112 @@ +// +// AppNotifications.swift +// +// +// Created by royal on 10/07/2020. +// + +#if !WIDGET +import Foundation +import SwiftUI +import Combine + +@available (iOS 14, macOS 10.16, watchOS 7, tvOS 14, *) +public final class AppNotifications: ObservableObject { + public static let shared: AppNotifications = AppNotifications() + + @Published public var notification: NotificationData? = nil + @Published public var isPresented: Bool = false + + private var timer: AnyCancellable? = nil + private var cancellableSet: Set = [] + + private init() { + $notification + .sink { notification in + if notification == nil { + self.isPresented = false + return + } + + self.isPresented = true + self.instantiateTimer() + } + .store(in: &cancellableSet) + } + + public func instantiateTimer() { + self.timer?.cancel() + self.timer = Timer.publish(every: 5, on: .main, in: .common) + .autoconnect() + .sink { _ in + self.notification = nil + self.isPresented = false + self.timer?.cancel() + } + } + + public func cancelTimer() { + self.timer?.cancel() + } +} + +extension AppNotifications { + public struct NotificationData: Identifiable, Equatable { + public enum NotificationStyle { + case normal + case information + case warning + case error + case success + } + + public init(id: UUID = UUID(), autodismisses: Bool, dismissable: Bool, style: NotificationStyle, icon: String, title: String, subtitle: String, expandedText: String? = nil) { + self.id = id + self.autodismisses = autodismisses + self.dismissable = dismissable + self.style = style + self.icon = icon + self.title = title + self.subtitle = subtitle + self.expandedText = expandedText + } + + public init(error: String) { + self.init(autodismisses: true, dismissable: true, style: .error, icon: "exclamationmark.triangle.fill", title: "Error!", subtitle: error) + } + + public var id: UUID = UUID() + var autodismisses: Bool + var dismissable: Bool + var style: NotificationStyle + var icon: String + var title: String + var subtitle: String + var expandedText: String? + + var primaryColor: Color { + switch (self.style) { + case .normal: return .primary + case .information: return .blue + case .warning: return .orange + case .error: return .red + case .success: return .green + } + } + + var backgroundColor: Color { + switch (self.style) { + #if os(macOS) + case .normal: return Color(NSColor.controlBackgroundColor) + #else + case .normal: return Color(UIColor.tertiarySystemBackground) + #endif + case .information: return Color.blue.opacity(0.1) + case .warning: return Color.orange.opacity(0.1) + case .error: return Color.red.opacity(0.1) + case .success: return Color.green.opacity(0.1) + } + } + } +} +#endif diff --git a/Modules/AppNotifications/Sources/AppNotifications/NotificationsOverlay.swift b/Modules/AppNotifications/Sources/AppNotifications/NotificationsOverlay.swift new file mode 100644 index 0000000..53877c8 --- /dev/null +++ b/Modules/AppNotifications/Sources/AppNotifications/NotificationsOverlay.swift @@ -0,0 +1,140 @@ +// +// NotificationsOverlay.swift +// +// +// Created by royal on 10/07/2020. +// + +#if !WIDGET +import SwiftUI +import Combine +import os + +#if os(iOS) +import CoreHaptics +#endif + +@available (iOS 14, watchOS 7, macOS 10.16, tvOS 14, *) +public extension View { + func notificationOverlay(_ appNotifications: AppNotifications) -> some View { + return self.overlay(NotificationOverlay(appNotifications: appNotifications)) + } +} + +/// Overlays a notification on top of the views +@available (iOS 14, watchOS 7, macOS 10.16, tvOS 14, *) +public struct NotificationOverlay: View { + @ObservedObject var appNotifications: AppNotifications + + @State private var isExpanded: Bool = false + @State private var translation = CGSize.zero + + private var yOffset: CGFloat { + if translation.height > 0 { + return translation.height * 0.075 + } + + return translation.height + } + + private var notificationDragGesture: some Gesture { + DragGesture() + .onChanged { value in + translation = value.translation + } + .onEnded { value in + if value.translation.height < -20 { + appNotifications.isPresented = false + } + translation = CGSize.zero + } + } + + @ViewBuilder var notificationContent: some View { + if let notification = appNotifications.notification { + VStack(alignment: .leading) { + HStack { + Image(systemName: notification.icon) + .font(.system(size: 26, weight: .bold, design: .default)) + .id(notification.icon) + .foregroundColor(notification.primaryColor) + + VStack(alignment: .leading) { + Text(LocalizedStringKey(notification.title)) + .font(.headline) + .lineLimit(2) + .id(notification.title) + .foregroundColor(notification.primaryColor) + + Text(LocalizedStringKey(notification.subtitle)) + .font(.headline) + .opacity(0.5) + .lineLimit(3) + .id(notification.subtitle) + .foregroundColor(notification.primaryColor) + } + .padding(.horizontal, 5) + + Spacer() + } + + if let expandedText = notification.expandedText, + isExpanded { + VStack { + Text(LocalizedStringKey(expandedText)) + .font(.headline) + .multilineTextAlignment(.leading) + .lineLimit(nil) + .foregroundColor(notification.primaryColor) + .opacity(0.75) + } + .transition(.opacity) + .padding(.top, 5) + .onAppear { + appNotifications.cancelTimer() + } + .onDisappear { + if notification.autodismisses { + appNotifications.instantiateTimer() + } + } + } + } + .padding() + .padding(.vertical, 5) + .background(notification.backgroundColor) + .background(Color(UIColor.systemBackground)) + .mask(RoundedRectangle(cornerRadius: 14, style: .circular)) + .gesture(notificationDragGesture) + .onTapGesture { + if notification.expandedText != nil { + #if os(iOS) + UIImpactFeedbackGenerator(style: .light).impactOccurred() + #endif + isExpanded.toggle() + if notification.autodismisses { + if isExpanded { + appNotifications.cancelTimer() + } else { + appNotifications.instantiateTimer() + } + } + } + } + .shadow(color: Color.black.opacity(0.1), radius: 20, x: 0, y: 0) + .offset(x: 0, y: appNotifications.isPresented ? yOffset : -200) + .animation(.interpolatingSpring(mass: 0.5, stiffness: 45, damping: 45, initialVelocity: 15)) + .transition(.asymmetric(insertion: .move(edge: .top), removal: .offset(x: 0, y: -200))) + } + } + + public var body: some View { + VStack { + notificationContent + + Spacer() + } + .padding() + } +} +#endif diff --git a/Modules/AppNotifications/Tests/AppNotificationsTests/AppNotificationsTests.swift b/Modules/AppNotifications/Tests/AppNotificationsTests/AppNotificationsTests.swift new file mode 100644 index 0000000..a69a0b0 --- /dev/null +++ b/Modules/AppNotifications/Tests/AppNotificationsTests/AppNotificationsTests.swift @@ -0,0 +1,15 @@ +import XCTest +@testable import AppNotifications + +final class AppNotificationsTests: XCTestCase { + func testExample() { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct + // results. + XCTAssertEqual(AppNotifications().text, "Hello, World!") + } + + static var allTests = [ + ("testExample", testExample), + ] +} diff --git a/Modules/AppNotifications/Tests/AppNotificationsTests/XCTestManifests.swift b/Modules/AppNotifications/Tests/AppNotificationsTests/XCTestManifests.swift new file mode 100644 index 0000000..910db29 --- /dev/null +++ b/Modules/AppNotifications/Tests/AppNotificationsTests/XCTestManifests.swift @@ -0,0 +1,9 @@ +import XCTest + +#if !canImport(ObjectiveC) +public func allTests() -> [XCTestCaseEntry] { + return [ + testCase(AppNotificationsTests.allTests), + ] +} +#endif diff --git a/Modules/AppNotifications/Tests/LinuxMain.swift b/Modules/AppNotifications/Tests/LinuxMain.swift new file mode 100644 index 0000000..ed2abfa --- /dev/null +++ b/Modules/AppNotifications/Tests/LinuxMain.swift @@ -0,0 +1,7 @@ +import XCTest + +import AppNotificationsTests + +var tests = [XCTestCaseEntry]() +tests += AppNotificationsTests.allTests() +XCTMain(tests) diff --git a/Modules/Vulcan/.gitignore b/Modules/Vulcan/.gitignore new file mode 100644 index 0000000..95c4320 --- /dev/null +++ b/Modules/Vulcan/.gitignore @@ -0,0 +1,5 @@ +.DS_Store +/.build +/Packages +/*.xcodeproj +xcuserdata/ diff --git a/Modules/Vulcan/.swiftpm/xcode/xcshareddata/xcschemes/Vulcan.xcscheme b/Modules/Vulcan/.swiftpm/xcode/xcshareddata/xcschemes/Vulcan.xcscheme new file mode 100644 index 0000000..c7dfccd --- /dev/null +++ b/Modules/Vulcan/.swiftpm/xcode/xcshareddata/xcschemes/Vulcan.xcscheme @@ -0,0 +1,77 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Modules/Vulcan/Package.swift b/Modules/Vulcan/Package.swift new file mode 100644 index 0000000..fe6c9b7 --- /dev/null +++ b/Modules/Vulcan/Package.swift @@ -0,0 +1,33 @@ +// swift-tools-version:5.3 +// The swift-tools-version declares the minimum version of Swift required to build this package. + +import PackageDescription + +let package = Package( + name: "Vulcan", + platforms: [ + .iOS(.v14), + .macOS(.v11), + .watchOS(.v7) + ], + products: [ + // Products define the executables and libraries a package produces, and make them visible to other packages. + .library( + name: "Vulcan", + targets: ["Vulcan"]) + ], + dependencies: [ + .package(url: "https://github.com/kishikawakatsumi/KeychainAccess.git", from: "4.0.0"), + // .package(path: "../AppNotifications") + ], + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages this package depends on. + .target( + name: "Vulcan", + dependencies: ["KeychainAccess"]), + .testTarget( + name: "VulcanTests", + dependencies: ["Vulcan"]), + ] +) diff --git a/Modules/Vulcan/README.md b/Modules/Vulcan/README.md new file mode 100644 index 0000000..a388814 --- /dev/null +++ b/Modules/Vulcan/README.md @@ -0,0 +1,3 @@ +# Vulcan + +A description of this package. diff --git a/Modules/Vulcan/Sources/Vulcan/CoreDataModel.swift b/Modules/Vulcan/Sources/Vulcan/CoreDataModel.swift new file mode 100644 index 0000000..5656388 --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/CoreDataModel.swift @@ -0,0 +1,79 @@ +// +// CoreDataModel.swift +// Vulcan +// +// Created by royal on 06/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import Foundation +import CoreData +import os + +public final class CoreDataModel { + public static let shared: CoreDataModel = CoreDataModel() + private let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).CoreData", category: "CoreData") + + private init() { } + + lazy public var persistentContainer: NSPersistentContainer = { + let groupURL: URL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.dev.niepostek.vulcanGroup")!.appendingPathComponent("vulcan.sqlite") + let modelURL = Bundle.module.url(forResource: "VulcanStore", withExtension: "momd") + let model = NSManagedObjectModel(contentsOf: modelURL!) + + let container = NSPersistentContainer(name: "VulcanStore", managedObjectModel: model!) + + let description: NSPersistentStoreDescription = NSPersistentStoreDescription() + description.url = groupURL + description.shouldMigrateStoreAutomatically = true + description.shouldInferMappingModelAutomatically = true + description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) + description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) + + container.persistentStoreDescriptions = [description] + container.loadPersistentStores { storeDescription, error in + if let error = error { + self.logger.error("Could not load store: \(error.localizedDescription)") + self.logger.debug("\(String(describing: storeDescription))") + self.clearDatabase() + return + } + + container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy + self.logger.info("Store loaded!") + } + + return container + }() + + /// Saves the CoreData context. + public func saveContext(force: Bool = false) { + if self.persistentContainer.viewContext.hasChanges || force { + do { + try self.persistentContainer.viewContext.save() + } catch { + logger.error("Error saving: \(error.localizedDescription)") + } + } + } + + /// Resets the database. + public func clearDatabase() { + let urls = persistentContainer.persistentStoreDescriptions.map(\.url) + let persistentStoreCoordinator = persistentContainer.persistentStoreCoordinator + + logger.debug("Clearing database...") + + do { + let options = [NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true] + for url in urls { + guard let url = url else { return } + try persistentStoreCoordinator.destroyPersistentStore(at: url, ofType: NSSQLiteStoreType, options: nil) + try persistentStoreCoordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options) + } + logger.debug("Done!") + } catch { + logger.error("Error: \(error.localizedDescription)") + } + } +} diff --git a/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Array.swift b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Array.swift new file mode 100644 index 0000000..c7e961b --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Array.swift @@ -0,0 +1,62 @@ +// +// Array.swift +// Vulcan +// +// Created by royal on 03/06/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import Foundation + +public extension Sequence where Iterator.Element: Hashable { + var uniques: [Iterator.Element] { + var seen: [Iterator.Element: Bool] = [:] + return self.filter { seen.updateValue(true, forKey: $0) == nil } + } +} + +public extension Array where Element == Vulcan.ScheduleEvent { + /// Events for the selected day. + /// - Parameter day: Filter by this date + /// - Returns: Array of `Vulcan.ScheduleEvent` + func eventsForDay(_ day: Date) -> [Vulcan.ScheduleEvent] { + return self.filter { Calendar.autoupdatingCurrent.isDate($0.date, inSameDayAs: day) } + } + + func timeline() -> [(Date, Vulcan.ScheduleEvent)] { + return self + .enumerated() + .map { index, event in + var date: Date { + if index - 1 < 0 { + return Calendar.autoupdatingCurrent.startOfDay(for: (event.dateStarts ?? event.date)) + } + + if let previousEventDateStarts: Date = self[index - 1].dateStarts, + let previousEventDateEnds: Date = self[index - 1].dateEnds { + return Date(timeIntervalSinceReferenceDate: (previousEventDateStarts.timeIntervalSinceReferenceDate + previousEventDateEnds.timeIntervalSinceReferenceDate) / 2) + } else { + return event.dateStarts ?? Calendar.autoupdatingCurrent.startOfDay(for: event.date) + } + } + + return (date, event) + } + } +} + +public extension Array where Element == Vulcan.EndOfTermGrade { + var expected: [Vulcan.EndOfTermGrade] { + return self.filter { $0.type == .expected } + } + + var final: [Vulcan.EndOfTermGrade] { + return self.filter { $0.type == .final } + } +} + +public extension Array where Element == StoredScheduleEvent { + var grouped: [Date: [StoredScheduleEvent]] { + return Dictionary(grouping: self, by: { Date(timeIntervalSince1970: TimeInterval($0.dateEpoch)) }) + } +} diff --git a/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Bundle.swift b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Bundle.swift new file mode 100644 index 0000000..1a5103c --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Bundle.swift @@ -0,0 +1,70 @@ +// +// Bundle.swift +// Vulcan +// +// Created by royal on 06/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +#if os(watchOS) +import WatchKit +#endif + +#if canImport(UIKit) +import UIKit +#else +import AppKit +#endif + +import Foundation + +public extension Bundle { + var buildVersion: String { + return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown" + } + + var buildNumber: String { + return Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "Unknown" + } + + var modelName: String { + #if os(watchOS) + return WKInterfaceDevice.current().model + #elseif os(OSX) + return ProcessInfo().hostName + #else + return UIDevice.current.model + #endif + } + + var deviceName: String { + #if os(watchOS) + return WKInterfaceDevice.current().name + #elseif os(OSX) + return ProcessInfo().hostName + #else + return UIDevice.current.name + #endif + } + + var systemName: String { + #if os(watchOS) + return WKInterfaceDevice.current().systemName + #elseif os(OSX) + return "macOS" + #else + return UIDevice.current.systemName + #endif + } + + var systemVersion: String { + #if os(watchOS) + return WKInterfaceDevice.current().systemVersion + #elseif os(OSX) + let version = ProcessInfo().operatingSystemVersion + return "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)" + #else + return UIDevice.current.systemVersion + #endif + } +} diff --git a/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Date.swift b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Date.swift new file mode 100644 index 0000000..432eede --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Date.swift @@ -0,0 +1,107 @@ +// +// Date.swift +// Vulcan +// +// Created by royal on 06/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import Foundation + +public extension Date { + static func - (lhs: Date, rhs: Date) -> TimeInterval { + return lhs.timeIntervalSinceReferenceDate - rhs.timeIntervalSinceReferenceDate + } + + func formattedString(format: String) -> String { + let dateFormatter = DateFormatter() + dateFormatter.dateFormat = format + dateFormatter.locale = Locale.autoupdatingCurrent + + return dateFormatter.string(from: self) + } + + func formattedDateString(timeStyle: DateFormatter.Style = .none, dateStyle: DateFormatter.Style = .none, context: DateFormatter.Context = .unknown, hideDate: Bool = false) -> String { + let dateFormatter = DateFormatter() + dateFormatter.timeStyle = timeStyle + dateFormatter.dateStyle = (hideDate && self >= Date().startOfDay) ? .none : dateStyle + dateFormatter.locale = Calendar.autoupdatingCurrent.locale + dateFormatter.timeZone = Calendar.autoupdatingCurrent.timeZone + dateFormatter.formattingContext = context + + return dateFormatter.string(from: self) + } + + var relativeString: String { + let dateFormatter = DateFormatter() + dateFormatter.timeStyle = .none + dateFormatter.dateStyle = .long + dateFormatter.doesRelativeDateFormatting = true + return dateFormatter.string(from: self) + } + + var timestampString: String? { + let formatter = DateComponentsFormatter() + formatter.unitsStyle = .abbreviated + formatter.maximumUnitCount = 2 + formatter.allowedUnits = [.year, .month, .day, .hour, .minute, .second] + + guard let timeString = formatter.string(from: self, to: Date()) else { + return nil + } + + let formatString = NSLocalizedString("%@", comment: "") + return String(format: formatString, timeString) + } + + var localizedTime: String { + let dateFormatter = DateFormatter() + dateFormatter.dateStyle = .none + dateFormatter.timeStyle = .short + return dateFormatter.string(from: self) + } + + func startOfTheYear(offset: Int = 0) -> Date? { + let currentYear = Calendar.autoupdatingCurrent.component(.year, from: self) + return Calendar.autoupdatingCurrent.date(from: DateComponents(year: currentYear + offset, month: 1, day: 1)) + } + + func endOfTheYear(offset: Int = 0) -> Date? { + let currentYear = Calendar.autoupdatingCurrent.component(.year, from: self) + return Calendar.autoupdatingCurrent.date(from: DateComponents(year: currentYear + offset, month: 12, day: 31)) + } + + var startOfDay: Date { + return Calendar.autoupdatingCurrent.startOfDay(for: self) + } + + var endOfDay: Date { + var components = DateComponents() + components.day = 1 + components.second = -1 + return Calendar.autoupdatingCurrent.date(byAdding: components, to: startOfDay)! + } + + var startOfWeek: Date? { + guard let sunday = Calendar.autoupdatingCurrent.date(from: Calendar.autoupdatingCurrent.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil } + return Calendar.autoupdatingCurrent.date(byAdding: .day, value: 1, to: sunday)! + } + + var endOfWeek: Date? { + guard let sunday = Calendar.autoupdatingCurrent.date(from: Calendar.autoupdatingCurrent.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil } + return Calendar.autoupdatingCurrent.date(byAdding: .day, value: 7, to: sunday)! + } + + var startOfMonth: Date { + let calendar = Calendar(identifier: .gregorian) + let components = calendar.dateComponents([.year, .month], from: self) + return calendar.date(from: components)! + } + + var endOfMonth: Date { + var components = DateComponents() + components.month = 1 + components.second = -1 + return Calendar(identifier: .gregorian).date(byAdding: components, to: self.startOfMonth)! + } +} diff --git a/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Dictionary.swift b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Dictionary.swift new file mode 100644 index 0000000..06bfee7 --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Dictionary.swift @@ -0,0 +1,14 @@ +// +// Dictionary.swift +// +// +// Created by royal on 27/08/2020. +// + +import Foundation + +public extension Dictionary where Key == Vulcan.MessageTag, Value == [Vulcan.Message] { + var combined: [Vulcan.Message] { + Array(self.values).flatMap { $0 } + } +} diff --git a/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Sequence.swift b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Sequence.swift new file mode 100644 index 0000000..62adbba --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Sequence.swift @@ -0,0 +1,16 @@ +// +// Sequence.swift +// +// +// Created by royal on 18/10/2020. +// + +import Foundation + +extension Sequence { + func sorted(by keyPath: KeyPath) -> [Element] { + return sorted { a, b in + return a[keyPath: keyPath] < b[keyPath: keyPath] + } + } +} diff --git a/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/String.swift b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/String.swift new file mode 100644 index 0000000..379040b --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/String.swift @@ -0,0 +1,14 @@ +// +// File.swift +// +// +// Created by royal on 28/08/2020. +// + +import Foundation + +extension String { + var westernArabicNumeralsOnly: String { + String(unicodeScalars.compactMap { UnicodeScalar("0")..."9" ~= $0 ? Character($0) : nil }) + } +} diff --git a/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/UserDefaults.swift b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/UserDefaults.swift new file mode 100644 index 0000000..fbe720f --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/UserDefaults.swift @@ -0,0 +1,27 @@ +// +// UserDefaults.swift +// +// +// Created by royal on 23/07/2020. +// + +import Foundation + +public extension UserDefaults { + enum AppKeys: String { + case launchedBefore = "launchedBefore" + case isLoggedIn = "isLoggedIn" + case readMessageOnOpen = "readMessageOnOpen" + case enableScheduleNotifications = "enableScheduleNotifications" + case enableTaskNotifications = "enableTaskNotifications" + case colorizeGrades = "colorizeGrades" + case hapticFeedback = "hapticFeedback" + case showAllScheduleEvents = "showAllScheduleEvents" + case colorScheme = "colorScheme" + case dictionaryLastFetched = "dictionaryLastFetched" + case userID = "userID" + case filterSchedule = "filterSchedule" + } + + static let group = UserDefaults(suiteName: "group.dev.niepostek.vulcanGroup")! +} diff --git a/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Vulcan+.swift b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Vulcan+.swift new file mode 100644 index 0000000..cf1d10c --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/Extensions+Modifiers/Vulcan+.swift @@ -0,0 +1,94 @@ +// +// Vulcan+.swift +// +// +// Created by royal on 03/09/2020. +// + +import Foundation + +#if os(iOS) || os(macOS) +import EventKit + +public extension VulcanTask { + func addToReminders(isBigType: Bool? = nil) { + let eventStore: EKEventStore = EKEventStore() + eventStore.requestAccess(to: .reminder) { + granted, error in + if (granted && error == nil) { + let tag: String + + if let isBigType = isBigType { + tag = NSLocalizedString(isBigType ? "EXAM_BIG" : "EXAM_SMALL", comment: "") + } else { + switch (self.tag) { + case .exam: tag = NSLocalizedString("TAG_EXAM", comment: "") + case .homework: tag = NSLocalizedString("TAG_HOMEWORK", comment: "") + } + } + + let event: EKReminder = EKReminder(eventStore: eventStore) + if let subjectName = self.subject?.name { + event.title = "\(tag): \(subjectName)" + } else { + event.title = "\(tag): \(self.subjectID)" + } + event.notes = self.entry + event.calendar = eventStore.defaultCalendarForNewReminders() + + let date: Date = Calendar.autoupdatingCurrent.date(byAdding: .hour, value: 9, to: self.date) ?? self.date + let alarm = EKAlarm(absoluteDate: date) + event.addAlarm(alarm) + + let predicate = eventStore.predicateForReminders(in: [event.calendar]) + eventStore.fetchReminders(matching: predicate) { events in + let eventAlreadyExists: Bool = events?.contains(where: { $0.title == event.title && $0.notes == event.notes && $0.alarms == event.alarms }) ?? false + + if !eventAlreadyExists { + try? eventStore.save(event, commit: true) + } + } + } + } + } + + func addToCalendar(isBigType: Bool? = nil) { + let eventStore: EKEventStore = EKEventStore() + eventStore.requestAccess(to: .event) { + granted, error in + if (granted && error == nil) { + let tag: String + + if let isBigType = isBigType { + tag = NSLocalizedString(isBigType ? "EXAM_BIG" : "EXAM_SMALL", comment: "") + } else { + switch (self.tag) { + case .exam: tag = NSLocalizedString("TAG_EXAM", comment: "") + case .homework: tag = NSLocalizedString("TAG_HOMEWORK", comment: "") + } + } + + let event: EKEvent = EKEvent(eventStore: eventStore) + if let subjectName = self.subject?.name { + event.title = "\(tag): \(subjectName)" + } else { + event.title = "\(tag): \(self.subjectID)" + } + event.isAllDay = true + event.startDate = self.date + event.endDate = self.date + event.notes = self.entry + event.calendar = eventStore.defaultCalendarForNewEvents + + let predicate = eventStore.predicateForEvents(withStart: self.date.startOfDay, end: self.date.endOfDay, calendars: nil) + let existingEvents = eventStore.events(matching: predicate) + let eventAlreadyExists = existingEvents.contains(where: { $0.title == event.title && $0.notes == event.notes && $0.startDate == event.startDate && $0.endDate == event.endDate }) + + if !eventAlreadyExists { + try? eventStore.save(event, span: .thisEvent) + } + } + } + } +} +#endif diff --git a/Modules/Vulcan/Sources/Vulcan/Models.swift b/Modules/Vulcan/Sources/Vulcan/Models.swift new file mode 100644 index 0000000..da9c6d9 --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/Models.swift @@ -0,0 +1,1215 @@ +// +// Models.swift +// Vulcan +// +// Created by royal on 06/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import Foundation +import CoreData + +#if canImport(EventKit) +import EventKit +#endif + +public protocol VulcanTask { + var id: Int { get } + var dateEpoch: Int { get } + var employeeID: Int { get } + var subjectID: Int { get } + var entry: String { get } + + var tag: Vulcan.TaskTag { get } + var subject: DictionarySubject? { get set } + var employee: DictionaryEmployee? { get set } + + var date: Date { get } +} + +public extension Vulcan { + // MARK: - Utils + + /// API request error + enum APIError: Error, LocalizedError { + case unknown + case error(reason: String) + + public var errorDescription: String? { + switch self { + case .unknown: + return "Unknown error" + case .error (let reason): + return reason + } + } + } + + enum TaskTag: String { + case exam = "TAG_EXAM" + case homework = "TAG_HOMEWORK" + } + + enum MessageTag: String { + case received = "Received" + case deleted = "Deleted" + case sent = "Sent" + } + + enum MessageFolder: String { + case read = "Widoczna" + case deleted = "Usunieta" + } + + enum EndOfTermGradeType: Int, Comparable { + public static func < (lhs: Vulcan.EndOfTermGradeType, rhs: Vulcan.EndOfTermGradeType) -> Bool { + return lhs.rawValue < rhs.rawValue + } + + case unknown = 0 + case expected = 1 + case final = 2 + } + + /// Message recipient + class Recipient: NSObject, Identifiable, Codable { + public init(id: Int, name: String) { + self.id = id + self.name = name + } + + /// Initializes the entity from CoreData entity. + /// - Parameter entity: CoreData entity + public convenience init?(from entity: DictionaryEmployee) { + var name: String = "Unknown employee" + if let employeeName = entity.name, + let employeeSurname = entity.surname, + let employeeCode = entity.code { + name = "\(employeeSurname) \(employeeName) (\(employeeCode))" + } + + self.init(id: Int(entity.id), name: name) + } + + enum CodingKeys: String, CodingKey { + case name = "Nazwa" + case id = "LoginId" + } + + public let id: Int + public let name: String + } + + // MARK: - Misc. + + /// Struct containing the user data. + struct Student: Identifiable, Codable, Equatable { + public init(classificationPeriodID: Int, periodLevel: Int, periodNumber: Int, periodDateFrom: Int, periodDateTo: Int, reportingUnitID: Int, reportingUnitShort: String, reportingUnitName: String, reportingUnitSymbol: String, unitID: Int, unitName: String, unitShort: String, unitSymbol: String, unitCode: String, userRole: String, userLogin: String, userLoginID: Int, username: String, id: Int, branchID: Int, name: String, secondName: String, surname: String, nickname: String?, userGender: Int, position: Int, loginID: Int?) { + self.classificationPeriodID = classificationPeriodID + self.periodLevel = periodLevel + self.periodNumber = periodNumber + self.periodDateFrom = periodDateFrom + self.periodDateTo = periodDateTo + self.reportingUnitID = reportingUnitID + self.reportingUnitShort = reportingUnitShort + self.reportingUnitName = reportingUnitName + self.reportingUnitSymbol = reportingUnitSymbol + self.unitID = unitID + self.unitName = unitName + self.unitShort = unitShort + self.unitSymbol = unitSymbol + self.unitCode = unitCode + self.userRole = userRole + self.userLogin = userLogin + self.userLoginID = userLoginID + self.username = username + self.id = id + self.branchID = branchID + self.name = name + self.secondName = secondName + self.surname = surname + self.nickname = nickname + self.userGender = userGender + self.position = position + self.loginID = loginID + } + + + /// Initializes the object from CoreData entity. + /// - Parameter entity: CoreData entity + public init?(from entity: StoredStudent) { + guard let reportingUnitShort = entity.reportingUnitShort, + let reportingUnitName = entity.reportingUnitName, + let reportingUnitSymbol = entity.reportingUnitSymbol, + let unitName = entity.unitName, + let unitShort = entity.unitShort, + let unitSymbol = entity.unitSymbol, + let unitCode = entity.unitCode, + let userRole = entity.userRole, + let userLogin = entity.userLogin, + let username = entity.username, + let name = entity.name, + let secondName = entity.secondName, + let surname = entity.surname + else { + return nil + } + + self.init(classificationPeriodID: Int(entity.classificationPeriodID), periodLevel: Int(entity.periodLevel), periodNumber: Int(entity.periodNumber), periodDateFrom: Int(entity.periodDateFrom), periodDateTo: Int(entity.periodDateTo), reportingUnitID: Int(entity.reportingUnitID), reportingUnitShort: reportingUnitShort, reportingUnitName: reportingUnitName, reportingUnitSymbol: reportingUnitSymbol, unitID: Int(entity.unitID), unitName: unitName, unitShort: unitShort, unitSymbol: unitSymbol, unitCode: unitCode, userRole: userRole, userLogin: userLogin, userLoginID: Int(entity.userLoginID), username: username, id: Int(entity.id), branchID: Int(entity.branchID), name: name, secondName: secondName, surname: surname, nickname: entity.nickname, userGender: Int(entity.userGender), position: Int(entity.position), loginID: Int(entity.loginID)) + } + + enum CodingKeys: String, CodingKey { + case classificationPeriodID = "IdOkresKlasyfikacyjny" + case periodLevel = "OkresPoziom" + case periodNumber = "OkresNumer" + case periodDateFrom = "OkresDataOd" + case periodDateTo = "OkresDataDo" + case reportingUnitID = "IdJednostkaSprawozdawcza" + case reportingUnitShort = "JednostkaSprawozdawczaSkrot" + case reportingUnitName = "JednostkaSprawozdawczaNazwa" + case reportingUnitSymbol = "JednostkaSprawozdawczaSymbol" + case unitID = "IdJednostka" + case unitName = "JednostkaNazwa" + case unitShort = "JednostkaSkrot" + case unitSymbol = "OddzialSymbol" + case unitCode = "OddzialKod" + case userRole = "UzytkownikRola" + case userLogin = "UzytkownikLogin" + case userLoginID = "UzytkownikLoginId" + case username = "UzytkownikNazwa" + case id = "Id" + case branchID = "IdOddzial" + case name = "Imie" + case secondName = "Imie2" + case surname = "Nazwisko" + case nickname = "Pseudonim" + case userGender = "UczenPlec" + case position = "Pozycja" + case loginID = "LoginId" + } + + public let classificationPeriodID: Int + public let periodLevel: Int + public let periodNumber: Int + public let periodDateFrom: Int + public let periodDateTo: Int + public let reportingUnitID: Int + public let reportingUnitShort: String + public let reportingUnitName: String + public let reportingUnitSymbol: String + public let unitID: Int + public let unitName: String + public let unitShort: String + public let unitSymbol: String + public let unitCode: String + public let userRole: String + public let userLogin: String + public let userLoginID: Int + public let username: String + public let id: Int + public let branchID: Int + public let name: String + public let secondName: String + public let surname: String + public let nickname: String? + public let userGender: Int + public let position: Int + public let loginID: Int? + + /// Returns the CoreData entity. + /// - Parameter context: Context to insert into + /// - Returns: CoreData entity + public func entity(context: NSManagedObjectContext) -> StoredStudent { + let entity: StoredStudent = StoredStudent(context: context) + entity.branchID = Int32(self.branchID) + entity.classificationPeriodID = Int32(self.classificationPeriodID) + entity.id = Int64(self.id) + entity.name = self.name + entity.nickname = self.nickname + entity.periodDateFrom = Int64(self.periodDateFrom) + entity.periodDateTo = Int64(self.periodDateTo) + entity.periodLevel = Int16(self.periodLevel) + entity.periodNumber = Int16(self.periodNumber) + entity.position = Int16(self.position) + entity.reportingUnitID = Int16(self.reportingUnitID) + entity.reportingUnitName = self.reportingUnitName + entity.reportingUnitShort = self.reportingUnitShort + entity.reportingUnitSymbol = self.reportingUnitSymbol + entity.secondName = self.secondName + entity.surname = self.surname + entity.unitCode = self.unitCode + entity.unitID = Int16(self.unitID) + entity.unitName = self.unitName + entity.unitShort = self.unitShort + entity.unitSymbol = self.unitSymbol + entity.userGender = Int16(self.userGender) + entity.userLogin = self.userLogin + entity.userLoginID = Int32(self.userLoginID) + entity.userRole = self.userRole + entity.username = self.username + + if let loginID = self.loginID { entity.loginID = Int32(loginID) } + + return entity + } + } + + /// Holds the grades of the defined subject. + class SubjectGrades: Identifiable, Codable, Hashable { + public init(subject: Vulcan.Subject, employee: Vulcan.Employee, grades: [Vulcan.Grade]) { + self.subject = subject + self.employee = employee + self.grades = grades + } + + public static func == (lhs: Vulcan.SubjectGrades, rhs: Vulcan.SubjectGrades) -> Bool { + lhs.id == rhs.id && + lhs.subject.id == rhs.subject.id && + lhs.employee.id == rhs.employee.id && + lhs.grades == rhs.grades && + lhs.hasNewItems == rhs.hasNewItems + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(subject.id) + hasher.combine(employee.id) + hasher.combine(grades.map(\.entry)) + } + + public let subject: Vulcan.Subject + public let employee: Vulcan.Employee + public let grades: [Vulcan.Grade] + public var hasNewItems: Bool = false + + public var id: Int { + self.subject.id + } + } + + /// Holds the events for the date. + struct Schedule: Identifiable, Codable, Hashable { + public init(date: Date, events: [Vulcan.ScheduleEvent]) { + self.date = date + self.events = events + } + + public let date: Date + public let events: [Vulcan.ScheduleEvent] + + public var id: Int { + Int(self.date.timeIntervalSince1970) + } + } + + /// Holds the various tasks, because of course vulcan couldn't merge these two. + struct Tasks: Codable { + public init(exams: [Vulcan.Exam], homework: [Vulcan.Homework]) { + self.exams = exams + self.homework = homework + } + + public var exams: [Exam] + public var homework: [Homework] + + public var combined: [VulcanTask] { + return self.exams + self.homework + } + } + + // MARK: - Dictionary + + struct Employee: Identifiable, Codable, Hashable { + enum CodingKeys: String, CodingKey { + case id = "Id" + case name = "Imie" + case surname = "Nazwisko" + case code = "Kod" + case active = "Aktywny" + case teacher = "Nauczyciel" + case loginID = "LoginID" + } + + public let id: Int + public let name: String + public let surname: String + public let code: String + public let active: Bool? + public let teacher: Bool? + public let loginID: Int? + } + + struct Subject: Identifiable, Codable, Hashable { + enum CodingKeys: String, CodingKey { + case id = "Id" + case name = "Nazwa" + case code = "Kod" + case active = "Aktywny" + case position = "Pozycja" + } + + public let id: Int + public let name: String + public let code: String + public let active: Bool + public let position: Int + } + + struct LessonTime: Identifiable, Codable { + enum CodingKeys: String, CodingKey { + case id = "Id" + case number = "Numer" + case start = "Poczatek" + case end = "Koniec" + } + + public let id: Int + public let number: Int + public let start: Int + public let end: Int + } + + struct GradeCategory: Identifiable, Codable { + enum CodingKeys: String, CodingKey { + case id = "Id" + case code = "Kod" + case name = "Nazwa" + } + + public let id: Int + public let code: String + public let name: String + } + + struct NoteCategory: Identifiable, Codable { + enum CodingKeys: String, CodingKey { + case id = "Id" + case name = "Nazwa" + case active = "Aktywny" + } + + public let id: Int + public let name: String + public let active: Bool + } + + struct PresenceCategory: Identifiable, Codable { + enum CodingKeys: String, CodingKey { + case id = "Id" + case name = "Nazwa" + case position = "Pozycja" + case present = "Obecnosc" + case exempt = "Zwolnienie" + case late = "Spoznienie" + case justified = "Usprawiedliwione" + case removed = "Usuniete" + } + + public let id: Int + public let name: String + public let position: Int + public let present: Bool + public let exempt: Bool + public let late: Bool + public let justified: Bool + public let removed: Bool + } + + struct PresenceType: Identifiable, Codable { + enum CodingKeys: String, CodingKey { + case id = "Id" + case symbol = "Symbol" + case name = "Nazwa" + case active = "Aktywny" + case isDefault = "WpisDomyslny" + case categoryID = "IdKategoriaFrek" + } + + public let id: Int + public let symbol: String + public let name: String + public let active: Bool + public let isDefault: Bool + public let categoryID: Int + } + + // MARK: - API + + struct Presence { + enum CodingKeys: String, CodingKey { + case categoryID = "IdKategoria" + case number = "Numer" + case lessonTimeID = "IdPoraLekcji" + case day = "Dzien" + case subjectID = "IdPrzedmiot" + case subjectName = "PrzedmiotNazwa" + } + + public let categoryID: Int + public let number: Int + public let lessonTimeID: Int + public let day: Int + public let subjectID: Int + public let subjectName: String + } + + struct ScheduleEvent: Identifiable, Codable, Hashable { + public init(dateEpoch: Int, lessonOfTheDay: Int, lessonTimeID: Int, subjectID: Int, subjectName: String, divisionShort: String?, room: String, employeeID: Int, helpingEmployeeID: Int?, oldEmployeeID: Int?, oldHelpingEmployeeID: Int?, scheduleID: Int, note: String?, labelStrikethrough: Bool, labelBold: Bool, isUserSchedule: Bool, dateStartsEpoch: TimeInterval? = nil, dateEndsEpoch: TimeInterval? = nil, employeeFullName: String? = nil) { + self.dateEpoch = dateEpoch + self.lessonOfTheDay = lessonOfTheDay + self.lessonTimeID = lessonTimeID + self.subjectID = subjectID + self.subjectName = subjectName + self.divisionShort = divisionShort + self.room = room + self.employeeID = employeeID + self.helpingEmployeeID = helpingEmployeeID + self.oldEmployeeID = oldEmployeeID + self.oldHelpingEmployeeID = oldHelpingEmployeeID + self.scheduleID = scheduleID + self.note = note + self.labelStrikethrough = labelStrikethrough + self.labelBold = labelBold + self.isUserSchedule = isUserSchedule + self.dateStartsEpoch = dateStartsEpoch + self.dateEndsEpoch = dateEndsEpoch + self.employeeFullName = employeeFullName + } + + /// Initializes the entity from CoreData entity. + /// - Parameter entity: CoreData entity + public init?(from entity: StoredScheduleEvent) { + guard let subjectName = entity.subjectName, + let room = entity.room else { + return nil + } + + self.init(dateEpoch: Int(entity.dateEpoch), lessonOfTheDay: Int(entity.lessonOfTheDay), lessonTimeID: Int(entity.lessonTimeID), subjectID: Int(entity.subjectID), subjectName: subjectName, divisionShort: entity.divisionShort, room: room, employeeID: Int(entity.employeeID), helpingEmployeeID: Int(entity.helpingEmployeeID), oldEmployeeID: Int(entity.oldEmployeeID), oldHelpingEmployeeID: Int(entity.oldHelpingEmployeeID), scheduleID: Int(entity.scheduleID), note: entity.note, labelStrikethrough: entity.labelStrikethrough, labelBold: entity.labelBold, isUserSchedule: entity.isUserSchedule, dateStartsEpoch: TimeInterval(entity.dateStartsEpoch), dateEndsEpoch: TimeInterval(entity.dateEndsEpoch), employeeFullName: entity.employeeFullName) + } + + enum CodingKeys: String, CodingKey { + case dateEpoch = "Dzien" + case lessonOfTheDay = "NumerLekcji" + case lessonTimeID = "IdPoraLekcji" + case subjectID = "IdPrzedmiot" + case subjectName = "PrzedmiotNazwa" + case divisionShort = "PodzialSkrot" + case room = "Sala" + case employeeID = "IdPracownik" + case helpingEmployeeID = "IdPracownikWspomagajacy" + case oldEmployeeID = "IdPracownikOld" + case oldHelpingEmployeeID = "IdPracownikWspomagajacyOld" + case scheduleID = "IdPlanLekcji" + case note = "AdnotacjaOZmianie" + case labelStrikethrough = "PrzekreslonaNazwa" + case labelBold = "PogrubionaNazwa" + case isUserSchedule = "PlanUcznia" + case dateStartsEpoch = "GodzinaRozpoczecia" + case dateEndsEpoch = "GodzinaZakonczenia" + case employeeFullName = "PracownikPelnaNazwa" + } + + public let dateEpoch: Int + public let lessonOfTheDay: Int + public let lessonTimeID: Int + public let subjectID: Int + public let subjectName: String + public let divisionShort: String? + public let room: String + public let employeeID: Int + public let helpingEmployeeID: Int? + public let oldEmployeeID: Int? + public let oldHelpingEmployeeID: Int? + public let scheduleID: Int + public let note: String? + public let labelStrikethrough: Bool + public let labelBold: Bool + public let isUserSchedule: Bool + + public var dateStartsEpoch: TimeInterval? + public var dateEndsEpoch: TimeInterval? + public var employeeFullName: String? + + public var subject: DictionarySubject? + public var employee: DictionaryEmployee? + + public var id: String { + "\(self.dateEpoch):\(self.lessonOfTheDay):\(self.lessonTimeID):\(self.subjectID):\(self.divisionShort ?? "ungrouped")" + } + + public var date: Date { Date(timeIntervalSince1970: TimeInterval(self.dateEpoch)) } + + public var dateStarts: Date? { + guard let epoch = self.dateStartsEpoch else { + return nil + } + + return Date(timeIntervalSince1970: TimeInterval(epoch)) + } + + public var dateEnds: Date? { + guard let epoch = self.dateEndsEpoch else { + return nil + } + + return Date(timeIntervalSince1970: TimeInterval(epoch)) + } + + public var isCurrent: Bool? { + get { + guard let dateStarts = dateStarts, + let dateEnds = dateEnds else { + return nil + } + + let now: Date = Date() + return now > dateStarts && now < dateEnds + } + } + + public var group: Int? { + guard let division = self.divisionShort, + let firstCharacter = division.first else { + return nil + } + + return Int(String(firstCharacter)) + } + + /// Returns the CoreData entity. + /// - Parameter context: Context to insert into + /// - Returns: CoreData entity + public func entity(context: NSManagedObjectContext) -> StoredScheduleEvent { + let entity: StoredScheduleEvent = StoredScheduleEvent(context: context) + entity.dateEpoch = Int64(self.dateEpoch) + entity.labelBold = self.labelBold + entity.labelStrikethrough = self.labelStrikethrough + entity.lessonOfTheDay = Int16(self.lessonOfTheDay) + entity.lessonTimeID = Int16(self.lessonTimeID) + entity.note = self.note + entity.room = self.room + entity.subjectID = Int32(self.subjectID) + entity.subjectName = self.subjectName + entity.employeeID = Int32(self.employeeID) + entity.isUserSchedule = self.isUserSchedule + entity.divisionShort = self.divisionShort + entity.id = self.id + + if let dateStartsEpoch = self.dateStartsEpoch { entity.dateStartsEpoch = Int64(dateStartsEpoch) } + if let dateEndsEpoch = self.dateEndsEpoch { entity.dateEndsEpoch = Int64(dateEndsEpoch) } + if let oldEmployeeID = self.oldEmployeeID { entity.oldEmployeeID = Int32(oldEmployeeID) } + if let helpingEmployeeID = self.helpingEmployeeID { entity.helpingEmployeeID = Int32(helpingEmployeeID) } + if let oldHelpingEmployeeID = self.oldHelpingEmployeeID { entity.oldHelpingEmployeeID = Int32(oldHelpingEmployeeID) } + if let employeeName = self.employee?.name, + let employeeSurname = self.employee?.surname { + entity.employeeFullName = "\(employeeName) \(employeeSurname)" + } else if let employeeFullName = self.employeeFullName { + entity.employeeFullName = employeeFullName + } + + return entity + } + } + + struct Grade: Identifiable, Codable, Hashable, Equatable { + public init(id: Int, position: Int, subjectPosition: Int, subjectID: Int, categoryID: Int?, entry: String?, value: Double?, modifierWeight: Double?, gradeWeight: Double?, counter: Double?, denominator: Double?, comment: String?, weight: String?, description: String?, dateCreatedEpoch: Int, dateModifiedEpoch: Int?, dEmployeeID: Int, mEmployeeID: Int?) { + self.id = id + self.position = position + self.subjectPosition = subjectPosition + self.subjectID = subjectID + self.categoryID = categoryID + self.entry = entry + self.value = value + self.modifierWeight = modifierWeight + self.gradeWeight = gradeWeight + self.counter = counter + self.denominator = denominator + self.comment = comment + self.weight = weight + self.description = description + self.dateCreatedEpoch = dateCreatedEpoch + self.dateModifiedEpoch = dateModifiedEpoch + self.dEmployeeID = dEmployeeID + self.mEmployeeID = mEmployeeID + } + + /// Initializes the object from CoreData entity. + /// - Parameter entity: CoreData entity + public init(from entity: StoredGrade) { + self.init(id: Int(entity.id), position: Int(entity.position), subjectPosition: Int(entity.subjectPosition), subjectID: Int(entity.subjectID), categoryID: Int(entity.categoryID), entry: entity.entry, value: Double(entity.value), modifierWeight: Double(entity.modifierWeight), gradeWeight: Double(entity.gradeWeight), counter: Double(entity.counter), denominator: Double(entity.denominator), comment: entity.comment, weight: entity.weight, description: entity.gradeDescription, dateCreatedEpoch: Int(entity.dateCreatedEpoch), dateModifiedEpoch: Int(entity.dateModifiedEpoch), dEmployeeID: Int(entity.dEmployeeID), mEmployeeID: Int(entity.mEmployeeID)) + } + + public static func == (lhs: Vulcan.Grade, rhs: Vulcan.Grade) -> Bool { + lhs.entry == rhs.entry && + lhs.categoryID == rhs.categoryID && + lhs.dateCreatedEpoch == rhs.dateCreatedEpoch && + lhs.dateModifiedEpoch == rhs.dateModifiedEpoch && + lhs.weight == rhs.weight + } + + enum CodingKeys: String, CodingKey { + case id = "Id" + case position = "Pozycja" + case subjectPosition = "PrzedmiotPozycja" + case subjectID = "IdPrzedmiot" + case categoryID = "IdKategoria" + case entry = "Wpis" + case value = "Wartosc" + case modifierWeight = "WagaModyfikatora" + case gradeWeight = "WagaOceny" + case counter = "Licznik" + case denominator = "Mianownik" + case comment = "Komentarz" + case weight = "Waga" + case description = "Opis" + case dateCreatedEpoch = "DataUtworzenia" + case dateModifiedEpoch = "DataModyfikacji" + case dEmployeeID = "IdPracownikD" + case mEmployeeID = "IdPracownikM" + } + + public let id: Int + public let position: Int + public let subjectPosition: Int + public let subjectID: Int + public let categoryID: Int? + public let entry: String? + public let value: Double? + public let modifierWeight: Double? + public let gradeWeight: Double? + public let counter: Double? + public let denominator: Double? + public let comment: String? + public let weight: String? + public let description: String? + public let dateCreatedEpoch: Int + public let dateModifiedEpoch: Int? + public let dEmployeeID: Int + public let mEmployeeID: Int? + + public var category: DictionaryGradeCategory? + + public var dateCreated: Date { Date(timeIntervalSince1970: TimeInterval(self.dateCreatedEpoch)) } + + public var grade: Int? { + guard let entry = self.entry else { + return nil + } + + return Int(entry.westernArabicNumeralsOnly) + } + + /// Returns the CoreData entity. + /// - Parameter context: Context to insert into + /// - Returns: CoreData entity + public func entity(context: NSManagedObjectContext) -> StoredGrade { + let entity: StoredGrade = StoredGrade(context: context) + entity.comment = self.comment + entity.subjectID = Int32(self.subjectID) + entity.dEmployeeID = Int32(self.dEmployeeID) + entity.dateCreatedEpoch = Int64(self.dateCreatedEpoch) + entity.entry = self.entry + entity.gradeDescription = self.description + entity.id = Int64(self.id) + entity.position = Int16(self.position) + entity.weight = self.weight + + if let value = self.categoryID { entity.categoryID = Int32(value) } + if let value = self.counter { entity.counter = Float(value) } + if let value = self.dateModifiedEpoch { entity.dateModifiedEpoch = Int64(value) } + if let value = self.gradeWeight { entity.gradeWeight = Float(value) } + if let value = self.denominator { entity.denominator = Float(value) } + if let value = self.mEmployeeID { entity.mEmployeeID = Int32(value) } + if let value = self.modifierWeight { entity.modifierWeight = Float(value) } + + return entity + } + } + + struct EndOfTermGrade: Identifiable, Codable { + public init(subjectID: Int, entry: String, subject: DictionarySubject? = nil, type: EndOfTermGradeType? = .unknown) { + self.subjectID = subjectID + self.entry = entry + self.subject = subject + self.type = type + } + + /// Initializes the object from CoreData entity. + /// - Parameter entity: CoreData entity + public init?(from entity: StoredEndOfTermGrade) { + guard let entry = entity.entry else { + return nil + } + + self.init(subjectID: Int(entity.subjectID), entry: entry, type: EndOfTermGradeType(rawValue: Int(entity.type))) + } + + enum CodingKeys: String, CodingKey { + case subjectID = "IdPrzedmiot" + case entry = "Wpis" + } + + public let subjectID: Int + public let entry: String + + public var subject: DictionarySubject? + public var type: EndOfTermGradeType? + + public var id: Int { + self.subjectID + } + + /// Returns the CoreData entity. + /// - Parameter context: Context to insert into + /// - Returns: CoreData entity + public func entity(context: NSManagedObjectContext) -> StoredEndOfTermGrade { + let entity: StoredEndOfTermGrade = StoredEndOfTermGrade(context: context) + entity.entry = self.entry + entity.subjectID = Int32(self.subjectID) + entity.type = Int16(self.type?.rawValue ?? 0) + + return entity + } + } + + struct EndOfTermPoints: Identifiable, Codable { + public init(subjectID: Int, gradeAverage: String, points: String) { + self.subjectID = subjectID + self.gradeAverage = gradeAverage + self.points = points + } + + /// Initializes the object from CoreData entity. + /// - Parameter entity: CoreData entity + public init?(from entity: StoredEndOfTermPoints) { + guard let gradeAverage = entity.gradeAverage, + let points = entity.points + else { + return nil + } + + self.init(subjectID: Int(entity.subjectID), gradeAverage: gradeAverage, points: points) + } + + enum CodingKeys: String, CodingKey { + case subjectID = "IdPrzedmiot" + case gradeAverage = "SredniaOcen" + case points = "SumaPunktow" + } + + public let subjectID: Int + public let gradeAverage: String + public let points: String + + public var id: Int { + self.subjectID + } + + public var grade: Double? { + Double(self.gradeAverage) + } + + /// Returns the CoreData entity. + /// - Parameter context: Context to insert into + /// - Returns: CoreData entity + public func entity(context: NSManagedObjectContext) -> StoredEndOfTermPoints { + let entity: StoredEndOfTermPoints = StoredEndOfTermPoints(context: context) + entity.subjectID = Int32(self.subjectID) + entity.gradeAverage = self.gradeAverage + entity.points = self.points + + return entity + } + } + + class Exam: Identifiable, Codable, VulcanTask { + public init(id: Int, subjectID: Int, employeeID: Int, branchID: Int, divisionID: Int?, divisionName: String?, divisionShort: String?, isBigType: Bool, entry: String, dateEpoch: Int, subject: DictionarySubject? = nil, employee: DictionaryEmployee? = nil) { + self.id = id + self.subjectID = subjectID + self.employeeID = employeeID + self.branchID = branchID + self.divisionID = divisionID + self.divisionName = divisionName + self.divisionShort = divisionShort + self.isBigType = isBigType + self.entry = entry + self.dateEpoch = dateEpoch + self.subject = subject + self.employee = employee + } + + /// Initializes the object from CoreData entity. + /// - Parameter entity: CoreData entity + public convenience init?(from entity: StoredExam) { + guard let entry = entity.entry else { + return nil + } + + self.init(id: Int(entity.id), subjectID: Int(entity.subjectID), employeeID: Int(entity.employeeID), branchID: Int(entity.branchID), divisionID: Int(entity.divisionID), divisionName: entity.divisionName, divisionShort: entity.divisionShort, isBigType: entity.isBigType, entry: entry, dateEpoch: Int(entity.dateEpoch)) + } + + enum CodingKeys: String, CodingKey { + case id = "Id" + case subjectID = "IdPrzedmiot" + case employeeID = "IdPracownik" + case branchID = "IdOddzial" + case divisionID = "IdPodzial" + case divisionName = "PodzialNazwa" + case divisionShort = "PodzialSkrot" + case isBigType = "Rodzaj" + case entry = "Opis" + case dateEpoch = "Data" + } + + public let id: Int + public let subjectID: Int + public let employeeID: Int + public let branchID: Int + public let divisionID: Int? + public let divisionName: String? + public let divisionShort: String? + public let isBigType: Bool + public let entry: String + public let dateEpoch: Int + + public let tag: Vulcan.TaskTag = .exam + + public var subject: DictionarySubject? + public var employee: DictionaryEmployee? + + public var date: Date { + Date(timeIntervalSince1970: TimeInterval(self.dateEpoch)) + } + + /// Returns the CoreData entity. + /// - Parameter context: Context to insert into + /// - Returns: CoreData entity + public func entity(context: NSManagedObjectContext) -> StoredExam { + let entity: StoredExam = StoredExam(context: context) + entity.id = Int64(self.id) + entity.subjectID = Int32(self.subjectID) + entity.employeeID = Int32(self.employeeID) + entity.branchID = Int32(self.branchID) + entity.divisionName = self.divisionName + entity.divisionShort = self.divisionShort + entity.isBigType = self.isBigType + entity.entry = self.entry + entity.dateEpoch = Int64(self.dateEpoch) + + if let divisionID = self.divisionID { + entity.divisionID = Int16(divisionID) + } + + return entity + } + } + + class Homework: Identifiable, Codable, VulcanTask { + public init(id: Int, studentID: Int, dateEpoch: Int, employeeID: Int, subjectID: Int, entry: String, subject: DictionarySubject? = nil, employee: DictionaryEmployee? = nil) { + self.id = id + self.studentID = studentID + self.dateEpoch = dateEpoch + self.employeeID = employeeID + self.subjectID = subjectID + self.entry = entry + self.subject = subject + self.employee = employee + } + + /// Initializes the object from CoreData entity. + /// - Parameter entity: CoreData entity + public convenience init?(from entity: StoredHomework) { + guard let entry = entity.entry else { + return nil + } + + self.init(id: Int(entity.id), studentID: Int(entity.studentID), dateEpoch: Int(entity.dateEpoch), employeeID: Int(entity.employeeID), subjectID: Int(entity.subjectID), entry: entry) + } + + enum CodingKeys: String, CodingKey { + case id = "Id" + case studentID = "IdUczen" + case dateEpoch = "Data" + case employeeID = "IdPracownik" + case subjectID = "IdPrzedmiot" + case entry = "Opis" + } + + public var id: Int + public let studentID: Int + public let dateEpoch: Int + public let employeeID: Int + public let subjectID: Int + public let entry: String + + public let tag: Vulcan.TaskTag = .homework + + public var subject: DictionarySubject? + public var employee: DictionaryEmployee? + + public var date: Date { + Date(timeIntervalSince1970: TimeInterval(self.dateEpoch)) + } + + /// Returns the CoreData entity. + /// - Parameter context: Context to insert into + /// - Returns: CoreData entity + public func entity(context: NSManagedObjectContext) -> StoredHomework { + let entity: StoredHomework = StoredHomework(context: context) + entity.id = Int64(self.id) + entity.studentID = Int32(self.studentID) + entity.dateEpoch = Int64(self.dateEpoch) + entity.employeeID = Int32(self.employeeID) + entity.subjectID = Int32(self.subjectID) + entity.entry = self.entry + + return entity + } + } + + struct Note: Identifiable, Codable { + public init(employeeID: Int, studentName: String, studentSurname: String, employeeName: String, employeeSurname: String, dateCreatedEpoch: Int, dateModifiedEpoch: Int?, key: String, id: Int, entry: String, studentID: Int, categoryID: Int) { + self.employeeID = employeeID + self.studentName = studentName + self.studentSurname = studentSurname + self.employeeName = employeeName + self.employeeSurname = employeeSurname + self.dateCreatedEpoch = dateCreatedEpoch + self.dateModifiedEpoch = dateModifiedEpoch + self.key = key + self.id = id + self.entry = entry + self.studentID = studentID + self.categoryID = categoryID + } + + /// Initializes the object from CoreData entity. + /// - Parameter entity: CoreData entity + public init?(from entity: StoredNote) { + guard let studentName = entity.studentName, + let studentSurname = entity.studentSurname, + let employeeName = entity.employeeName, + let employeeSurname = entity.employeeSurname, + let key = entity.key, + let entry = entity.entry else { + return nil + } + + self.init(employeeID: Int(entity.employeeID), studentName: studentName, studentSurname: studentSurname, employeeName: employeeName, employeeSurname: employeeSurname, dateCreatedEpoch: Int(entity.dateCreatedEpoch), dateModifiedEpoch: Int(entity.dateModifiedEpoch), key: key, id: Int(entity.id), entry: entry, studentID: Int(entity.studentID), categoryID: Int(entity.categoryID)) + } + + enum CodingKeys: String, CodingKey { + case key = "UwagaKey" + case id = "Id" + case categoryID = "IdKategoriaUwag" + case dateCreatedEpoch = "DataWpisu" + case dateModifiedEpoch = "DataModyfikacji" + case studentID = "IdUczen" + case entry = "TrescUwagi" + case employeeName = "PracownikImie" + case employeeSurname = "PracownikNazwisko" + case studentName = "UczenImie" + case studentSurname = "UczenNazwisko" + case employeeID = "IdPracownik" + } + + public let key: String + public let id: Int + public let categoryID: Int? + public let dateCreatedEpoch: Int + public let dateModifiedEpoch: Int? + public let studentID: Int + public let entry: String + public let employeeName: String + public let employeeSurname: String + public let studentName: String + public let studentSurname: String + public let employeeID: Int + + public var employee: DictionaryEmployee? + public var category: DictionaryNoteCategory? + + public var date: Date { + Date(timeIntervalSince1970: TimeInterval(self.dateCreatedEpoch)) + } + + /// Returns the CoreData entity. + /// - Parameter context: Context to insert into + /// - Returns: CoreData entity + public func entity(context: NSManagedObjectContext) -> StoredNote { + let entity: StoredNote = StoredNote(context: context) + entity.entry = self.entry + entity.dateCreatedEpoch = Int64(self.dateCreatedEpoch) + entity.id = Int64(self.id) + entity.key = self.key + entity.employeeID = Int32(self.employeeID) + entity.employeeName = self.employeeName + entity.employeeSurname = self.employeeSurname + entity.studentID = Int32(self.studentID) + entity.studentName = self.studentName + entity.studentSurname = self.studentSurname + + if let categoryID = self.categoryID { + entity.categoryID = Int32(categoryID) + } + + if let dateModified = self.dateModifiedEpoch { + entity.dateModifiedEpoch = Int64(dateModified) + } + + return entity + } + } + + class Message: Identifiable, Codable, Hashable { + public init(id: Int, sender: String?, senderID: Int, recipients: [Vulcan.Recipient]?, title: String, content: String, dateSentEpoch: Int, dateReadEpoch: Int?, status: String, folder: String, read: String?, tag: Vulcan.MessageTag? = nil) { + self.id = id + self.sender = sender + self.senderID = senderID + self.recipients = recipients + self.title = title + self.content = content + self.dateSentEpoch = dateSentEpoch + self.dateReadEpoch = dateReadEpoch + self.status = status + self.folder = folder + self.read = read + self.tag = tag + } + + /// Initializes the object from CoreData entity. + /// - Parameter entity: CoreData entity + public convenience init?(from entity: StoredMessage) { + guard let title = entity.title, + let content = entity.content, + let status = entity.status, + let folder = entity.folder else { + return nil + } + + var recipients: [Vulcan.Recipient]? + if let entityRecipients = entity.recipients { + let decoder: JSONDecoder = JSONDecoder() + recipients = try? decoder.decode([Vulcan.Recipient].self, from: entityRecipients) + } + + self.init(id: Int(entity.id), sender: entity.sender, senderID: Int(entity.senderID), recipients: recipients, title: title, content: content, dateSentEpoch: Int(entity.dateSentEpoch), dateReadEpoch: Int(entity.dateReadEpoch), status: status, folder: folder, read: entity.read, tag: nil) + } + + enum CodingKeys: String, CodingKey { + case id = "WiadomoscId" + case sender = "Nadawca" + case senderID = "NadawcaId" + case recipients = "Adresaci" + case title = "Tytul" + case content = "Tresc" + case dateSentEpoch = "DataWyslaniaUnixEpoch" + case dateReadEpoch = "DataPrzeczytaniaUnixEpoch" + case status = "StatusWiadomosci" + case folder = "FolderWiadomosci" + case read = "Przeczytane" + } + + public func hash(into hasher: inout Hasher) { + hasher.combine(id) + } + + public static func == (lhs: Vulcan.Message, rhs: Vulcan.Message) -> Bool { + lhs.id == rhs.id && + lhs.dateSentEpoch == rhs.dateSentEpoch && + lhs.senderID == rhs.senderID && + lhs.title == rhs.title && + lhs.content == rhs.content && + lhs.read == rhs.read + } + + public let id: Int + public let sender: String? + public let senderID: Int + public let recipients: [Vulcan.Recipient]? + public let title: String + public let content: String + public let dateSentEpoch: Int + public var dateReadEpoch: Int? + public let status: String + public var folder: String + public var read: String? // Int? + + public var tag: Vulcan.MessageTag? + + public var dateSent: Date { + Date(timeIntervalSince1970: TimeInterval(self.dateSentEpoch)) + } + + public var dateRead: Date? { + get { + guard let date = dateReadEpoch else { + return nil + } + + return Date(timeIntervalSince1970: TimeInterval(date)) + } + + set(value) { + if let timeInterval = value?.timeIntervalSince1970 { + self.dateReadEpoch = Int(timeInterval) + } + } + } + + public var hasBeenRead: Bool { + get { + switch self.read ?? "" { + case "0": return false + case "1": return true + default: break + } + + switch self.dateRead { + case nil: return false + default: return true + } + } + + set(value) { + self.read = "1" + self.dateRead = Date() + } + } + + public var recipientsString: [String] { + guard let recipients = self.recipients else { + return [] + } + + return recipients.map(\.name) + } + + /// Returns the CoreData entity. + /// - Parameter context: Context to insert into + /// - Returns: CoreData entity + public func entity(context: NSManagedObjectContext) -> StoredMessage { + let entity: StoredMessage = StoredMessage(context: context) + entity.content = self.content + entity.dateSentEpoch = Int64(self.dateSentEpoch) + entity.folder = self.folder + entity.id = Int64(self.id) + entity.read = self.read + entity.sender = self.sender + entity.senderID = Int32(self.senderID) + entity.status = self.status + entity.title = self.title + + if let recipients = self.recipients { + let data = try? JSONEncoder().encode(recipients) + entity.recipients = data + } + + + if let dateReadEpoch = self.dateReadEpoch { + entity.dateReadEpoch = Int64(dateReadEpoch) + } + + return entity + } + } +} diff --git a/Modules/Vulcan/Sources/Vulcan/PKCS12.swift b/Modules/Vulcan/Sources/Vulcan/PKCS12.swift new file mode 100644 index 0000000..7ec3adf --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/PKCS12.swift @@ -0,0 +1,76 @@ +// +// PKCS12.swift +// vulcan +// +// Created by royal on 05/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import Foundation +import Security + +class PKCS12 { + let privateKey: SecKey + let publicKey: SecKey? + + enum PKCS12Error: Error { + case loadError(message: String) + } + + init(certificate: Data, password: String) throws { + let identityAndTrust = try PKCS12.identityAndTrust(data: certificate, password: password) + + self.privateKey = try PKCS12.privateKey(for: identityAndTrust.identity) + self.publicKey = PKCS12.publicKey(for: identityAndTrust.trust) + } + + class func identityAndTrust(data: Data, password: String) throws -> (identity: SecIdentity, trust: SecTrust) { + var importResult: CFArray? + + let status = SecPKCS12Import( + data as NSData, + [kSecImportExportPassphrase as String: password] as NSDictionary, + &importResult + ) + + guard (status == errSecSuccess) else { + throw NSError(domain: NSOSStatusErrorDomain, code: Int(status), userInfo: nil) + } + + guard let identityDictionaries = importResult as? [[String: Any]] else { + throw PKCS12.PKCS12Error.loadError(message: "Unable to load the certificate") + } + + let identity = identityDictionaries[0][kSecImportItemIdentity as String] as! SecIdentity + let trust = identityDictionaries[0][kSecImportItemTrust as String] as! SecTrust + + return (identity: identity, trust: trust) + } + + class func privateKey(for identity: SecIdentity) throws -> SecKey { + var privateKey: SecKey? + let status = SecIdentityCopyPrivateKey(identity, &privateKey) + + guard (status == errSecSuccess) else { + throw NSError(domain: NSOSStatusErrorDomain, code: Int(status), userInfo: nil) + } + + return privateKey! + } + + class func publicKey(for trust: SecTrust) -> SecKey? { + return SecTrustCopyKey(trust) + } + + public func signData(data: NSData) -> String? { + var signature: String? + var error: Unmanaged? + + guard let signedData = SecKeyCreateSignature(privateKey, .rsaSignatureMessagePKCS1v15SHA1, data as CFData, &error) as Data? else { + return nil + } + signature = signedData.base64EncodedString() + + return signature + } +} diff --git a/Modules/Vulcan/Sources/Vulcan/Vulcan.swift b/Modules/Vulcan/Sources/Vulcan/Vulcan.swift new file mode 100644 index 0000000..4238e98 --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/Vulcan.swift @@ -0,0 +1,2026 @@ +// +// Vulcan.swift +// Vulcan +// +// Created by royal on 06/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import SwiftUI +import Combine +import CoreData +import os +import UserNotifications +import KeychainAccess +import Network + +#if canImport(WidgetKit) +import WidgetKit +#endif + +@available (iOS 14, macOS 10.16, watchOS 7, tvOS 14, *) +/// Model that manages all of the Vulcan-related data. +public final class Vulcan: ObservableObject { + static public let shared: Vulcan = Vulcan() + + // MARK: - Private variables + + private let keychain: Keychain = Keychain(service: ("\(Bundle.main.bundleIdentifier ?? "vulcan")-\(Bundle.main.deviceName)")).label("vulcan Certificate (\(Bundle.main.deviceName))").synchronizable(false).accessibility(.afterFirstUnlock) + private let ud = UserDefaults.group + private let persistentContainer: NSPersistentContainer = CoreDataModel.shared.persistentContainer + private let monitor: NWPathMonitor = NWPathMonitor() + + private var cancellableSet: Set = [] + + private var endpointURL: String? { + get { return self.keychain["endpointURL"] } + set (value) { self.keychain["endpointURL"] = value } + } + + /// Used to manage the current data state. + public struct DataState { + fileprivate init(dictionary: Vulcan.DataState.Status = DataState.Status(), users: Vulcan.DataState.Status = DataState.Status(), schedule: Vulcan.DataState.Status = DataState.Status(), grades: Vulcan.DataState.Status = DataState.Status(), eotGrades: Vulcan.DataState.Status = DataState.Status()) { + self.dictionary = dictionary + self.users = users + self.schedule = schedule + self.grades = grades + self.eotGrades = eotGrades + } + + public struct Status { + fileprivate init(loading: Bool = false, lastFetched: Date? = nil, progress: Double? = nil) { + self.loading = loading + self.lastFetched = lastFetched + self.progress = progress + } + + public var loading: Bool = false + public var lastFetched: Date? + public var progress: Double? + + public var fetched: Bool { + return self.lastFetched != nil + } + } + + public var dictionary: DataState.Status = .init() + public var users: DataState.Status = .init() + + public var schedule: DataState.Status = .init() + public var grades: DataState.Status = .init() + public var eotGrades: DataState.Status = .init() + public var notes: DataState.Status = .init() + public var tasks: DataState.Status = .init() + public var messages: [Vulcan.MessageTag: DataState.Status] = [ + .deleted: .init(), + .received: .init(), + .sent: .init() + ] + } + + // MARK: - Public variables + + /// Notifiers + @Published public private(set) var scheduleDidChange: PassthroughSubject = PassthroughSubject() + + /// Data state + @Published public private(set) var dataState: DataState = DataState() + + /// Selected user + @Published public private(set) var currentUser: Vulcan.Student? + + /// Data + @Published public private(set) var users: [Vulcan.Student] = [] + @Published public private(set) var schedule: [Vulcan.Schedule] = [] + @Published public private(set) var grades: [Vulcan.SubjectGrades] = [] + @Published public private(set) var eotGrades: [Vulcan.EndOfTermGrade] = [] + @Published public private(set) var notes: [Vulcan.Note] = [] + @Published public private(set) var tasks: Vulcan.Tasks = Vulcan.Tasks(exams: [], homework: []) + @Published public private(set) var messages: [Vulcan.MessageTag: [Vulcan.Message]] = [:] + + // MARK: - init + /// Initializes, loads and sanity checks the data. + private init() { + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Init") + monitor.start(queue: .global(qos: .utility)) + + // If we have the certificate, we're logged in + if (self.keychain["CertificatePfx"] != nil) && (self.keychain["CertificatePfx"] != "") { + logger.debug("Logged in. Key: \(self.keychain["CertificateKey"] ?? "none", privacy: .private).") + } else { + logger.debug("Not logged in.") + self.logOut() + return + } + + // Load cached data + logger.info("Loading stored data...") + let context = self.persistentContainer.viewContext + + let studentFetchRequest: NSFetchRequest = StoredStudent.fetchRequest() + studentFetchRequest.predicate = NSPredicate(format: "id == %d", ud.integer(forKey: UserDefaults.AppKeys.userID.rawValue)) + if let storedStudents: [StoredStudent] = try? context.fetch(studentFetchRequest), + let storedStudent: StoredStudent = storedStudents.first { + self.currentUser = Vulcan.Student(from: storedStudent) + } + + if let dictionarySubjects: [DictionarySubject] = try? context.fetch(DictionarySubject.fetchRequest()), + let dictionaryEmployees: [DictionaryEmployee] = try? context.fetch(DictionaryEmployee.fetchRequest()) { + // Schedule + if let storedSchedule = try? context.fetch(StoredScheduleEvent.fetchRequest()) as? [StoredScheduleEvent] { + self.schedule = storedSchedule.grouped + .map { date, storedEvents in + let events: [Vulcan.ScheduleEvent] = storedEvents + .compactMap { entity in + guard var event = ScheduleEvent(from: entity) else { + return nil + } + + if let subject: DictionarySubject = dictionarySubjects.first(where: { $0.id == event.subjectID }) { + event.subject = subject + } + + if let employee: DictionaryEmployee = dictionaryEmployees.first(where: { $0.id == event.employeeID }), + let employeeName = employee.name, + let employeeSurname = employee.surname { + event.employee = employee + event.employeeFullName = "\(employeeName) \(employeeSurname)" + } + + if let dictionaryLessonTimes: [DictionaryLessonTime] = try? context.fetch(DictionaryLessonTime.fetchRequest()), + let lessonTime: DictionaryLessonTime = dictionaryLessonTimes.first(where: { $0.id == event.lessonTimeID }) { + event.dateStartsEpoch = TimeInterval(event.dateEpoch + Int(lessonTime.start) + 3600) + event.dateEndsEpoch = TimeInterval(event.dateEpoch + Int(lessonTime.end) + 3600) + } + + return event + } + .sorted { $0.lessonOfTheDay < $1.lessonOfTheDay } + + return Schedule(date: date, events: events) + } + .sorted { $0.date < $1.date } + } + + // Grades + if let storedGrades = try? context.fetch(StoredGrade.fetchRequest()) as? [StoredGrade] { + let dictionary = Dictionary(grouping: storedGrades, by: \.subjectID) + self.grades = dictionary + .compactMap { subjectID, grades in + guard let dictionarySubject: DictionarySubject = dictionarySubjects.first(where: { $0.id == subjectID }), + let subjectName: String = dictionarySubject.name, + let subjectCode: String = dictionarySubject.code, + let dEmployeeID = grades.first?.dEmployeeID, + let dictionaryEmployee: DictionaryEmployee = dictionaryEmployees.first(where: { $0.id == dEmployeeID }), + let employeeName: String = dictionaryEmployee.name, + let employeeSurname: String = dictionaryEmployee.surname, + let employeeCode: String = dictionaryEmployee.code + else { + return nil + } + + let subject: Vulcan.Subject = Vulcan.Subject(id: Int(dictionarySubject.id), name: subjectName, code: subjectCode, active: dictionarySubject.active, position: Int(dictionarySubject.position)) + let employee: Vulcan.Employee = Vulcan.Employee(id: Int(dictionaryEmployee.id), name: employeeName, surname: employeeSurname, code: employeeCode, active: dictionaryEmployee.active, teacher: dictionaryEmployee.teacher, loginID: Int(dictionaryEmployee.loginID)) + + let grades: [Vulcan.Grade] = storedGrades + .map { grade in + var grade = Grade(from: grade) + + if let categoryID = grade.categoryID, + let dictionaryGradeCategories: [DictionaryGradeCategory] = try? context.fetch(DictionaryGradeCategory.fetchRequest()) { + grade.category = dictionaryGradeCategories.first(where: { $0.id == categoryID }) + } + + return grade + } + .sorted { ($0.dateCreated, $0.entry ?? "") < ($1.dateCreated, $1.entry ?? "") } + .filter { $0.subjectID == subject.id } + + return Vulcan.SubjectGrades(subject: subject, employee: employee, grades: grades) + } + .sorted { $0.subject.name < $1.subject.name } + } + + // End of Term Grades + if let storedEndOfTermGrades = try? context.fetch(StoredEndOfTermGrade.fetchRequest()) as? [StoredEndOfTermGrade] { + self.eotGrades = storedEndOfTermGrades + .compactMap { grade in + var eotGrade = EndOfTermGrade(from: grade) + eotGrade?.subject = dictionarySubjects.first(where: { $0.id == grade.subjectID }) + + return eotGrade + } + .sorted { ($0.subject?.name ?? "") < ($1.subject?.name ?? "") } + } + + // Notes + if let storedNotes = try? context.fetch(StoredNote.fetchRequest()) as? [StoredNote] { + self.notes = storedNotes + .compactMap { note in + guard var note = Note(from: note) else { + return nil + } + + note.employee = dictionaryEmployees.first(where: { $0.id == note.employeeID }) + + if let categoryID = note.categoryID, + let dictionaryNoteCategories: [DictionaryNoteCategory] = try? context.fetch(DictionaryNoteCategory.fetchRequest()) { + note.category = dictionaryNoteCategories.first(where: { $0.id == categoryID }) + } + + return note + } + .sorted { $0.date < $1.date } + } + + // Exams + if let storedExams = try? context.fetch(StoredExam.fetchRequest()) as? [StoredExam] { + self.tasks.exams = storedExams + .compactMap { storedExam in + guard let exam = Exam(from: storedExam) else { + return nil + } + + exam.subject = dictionarySubjects.first(where: { $0.id == exam.subjectID }) + exam.employee = dictionaryEmployees.first(where: { $0.id == exam.employeeID }) + + return exam + } + .sorted { ($0.date, $0.subject?.name ?? "", $0.entry) < ($1.date, $1.subject?.name ?? "", $1.entry) } + } + + // Homework + if let storedHomework = try? context.fetch(StoredHomework.fetchRequest()) as? [StoredHomework] { + self.tasks.homework = storedHomework + .compactMap { storedHomework in + guard let homework = Homework(from: storedHomework) else { + return nil + } + + homework.subject = dictionarySubjects.first(where: { $0.id == homework.subjectID }) + homework.employee = dictionaryEmployees.first(where: { $0.id == homework.employeeID }) + + return homework + } + .sorted { ($0.date, $0.subject?.name ?? "", $0.entry) < ($1.date, $1.subject?.name ?? "", $1.entry) } + } + + // Messages + if let storedMessages = try? context.fetch(StoredMessage.fetchRequest()) as? [StoredMessage] { + let sentMessages: [Vulcan.Message] = storedMessages + .filter { $0.folder == "Wyslane" && $0.status == "Widoczna" } + .compactMap { entity in + let message = Vulcan.Message(from: entity) + message?.tag = .sent + + return message + } + .sorted { $0.dateSent > $1.dateSent } + + let receivedMessages: [Vulcan.Message] = storedMessages + .filter { $0.folder == "Odebrane" && $0.status == "Widoczna" } + .compactMap { entity in + let message = Vulcan.Message(from: entity) + message?.tag = .received + + return message + } + .sorted { $0.dateSent > $1.dateSent } + + let deletedMessages: [Vulcan.Message] = storedMessages + .filter { $0.status == "Usunieta" } + .compactMap { entity in + let message = Vulcan.Message(from: entity) + message?.tag = .deleted + + return message + } + .sorted { $0.dateSent > $1.dateSent } + + self.messages[.sent] = sentMessages + self.messages[.received] = receivedMessages + self.messages[.deleted] = deletedMessages + } + + logger.info("Done!") + } else { + logger.error("Couldn't fetch dictionary!") + } + + // Logged-in specific code + if self.ud.bool(forKey: UserDefaults.AppKeys.isLoggedIn.rawValue) { + // Refresh users + self.getUsers() + } + } + + // MARK: - Base functions + + /// Register new device and save received certificate. + /// - Parameters: + /// - token: 7 alphanumeric all-caps characters, which first three of them are the endpoint ID + /// - symbol: Alphanumeric, lower-caps school symbol + /// - pin: 6 numbers + /// - completionHandler: Callback + public func login(token: String, symbol: String, pin: Int, completionHandler: @escaping (Bool, Error?) -> ()) { + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Login") + logger.debug("Logging in...") + + // Apple Review + if (token == "applepark" && symbol == "infiniteloop" && pin == 000941) { + let user: Vulcan.Student = Vulcan.Student(classificationPeriodID: 1, periodLevel: 1, periodNumber: 1, periodDateFrom: 1, periodDateTo: 1, reportingUnitID: 1, reportingUnitShort: "AAPL", reportingUnitName: "Apple", reportingUnitSymbol: "AAPL", unitID: 1, unitName: "Apple", unitShort: "AAPL", unitSymbol: "AAPL", unitCode: "AAPL", userRole: "", userLogin: "johnappleseed@apple.com", userLoginID: 1, username: "JohnAppleseed", id: 1, branchID: 1, name: "John", secondName: "", surname: "Appleseed", nickname: nil, userGender: 1, position: 1, loginID: nil) + self.setUser(user) + completionHandler(true, nil) + return + } + + // Endpoint request + let endpointPublisher = URLSession.shared.dataTaskPublisher(for: URL(string: "http://komponenty.vulcan.net.pl/UonetPlusMobile/RoutingRules.txt")!) + .mapError { $0 as Error } + .eraseToAnyPublisher() + + // Firebase request + var firebaseRequest: URLRequest = URLRequest(url: URL(string: "https://android.googleapis.com/checkin")!) + firebaseRequest.httpMethod = "POST" + firebaseRequest.setValue("application/json", forHTTPHeaderField: "Content-type") + firebaseRequest.setValue("gzip", forHTTPHeaderField: "Accept-Encoding") + + let firebaseRequestBody: [String: Any] = [ + "locale": "pl_PL", + "digest": "", + "checkin": [ + "iosbuild": [ + "model": Bundle.main.modelName, + "os_version": Bundle.main.systemVersion + ], + "last_checkin_msec": 0, + "user_number": 0, + "type": 2 + ], + "time_zone": "Europe/Warsaw", + "user_serial_number": 0, + "id": 0, + "logging_id": 0, + "version": 2, + "security_token": 0, + "fragment": 0 + ] + firebaseRequest.httpBody = try? JSONSerialization.data(withJSONObject: firebaseRequestBody) + + let firebasePublisher = URLSession.shared.dataTaskPublisher(for: firebaseRequest) + .receive(on: DispatchQueue.global(qos: .background)) + .mapError { $0 as Error } + .tryCompactMap { value -> AnyPublisher in + guard let dictionary: [String: Any] = try? JSONSerialization.jsonObject(with: value.data, options: []) as? [String: Any] else { + throw APIError.error(reason: "Error serializing JSON") + } + + var request: URLRequest = URLRequest(url: URL(string: "https://fcmtoken.googleapis.com/register")!) + request.httpMethod = "POST" + request.setValue("AidLogin \(dictionary["android_id"] as? Int ?? 0):\(dictionary["security_token"] as? Int ?? 0)", forHTTPHeaderField: "Authorization") + request.setValue("gzip", forHTTPHeaderField: "Accept-Encoding") + + let body: String = "device=\(dictionary["android_id"] as? Int ?? 0)&app=pl.vulcan.UonetMobileModulUcznia&sender=987828170337&X-subtype=987828170337&appid=dLIDwhjvE58&gmp_app_id=1:987828170337:ios:6b65a4ad435fba7f" + request.httpBody = body.data(using: .utf8) + + return URLSession.shared.dataTaskPublisher(for: request) + .receive(on: DispatchQueue.global(qos: .background)) + .mapError { $0 as Error } + .map { $0.data } + .eraseToAnyPublisher() + } + .flatMap { $0 } + .mapError { $0 } + .eraseToAnyPublisher() + + Publishers.Zip(endpointPublisher, firebasePublisher) + .receive(on: DispatchQueue.main) + .tryMap { (endpoints, firebaseToken) -> String in + // Find endpointURL + let lines = String(data: endpoints.data, encoding: .utf8)?.split { $0.isNewline } + var endpointURL: String? + + // Parse lines + lines?.forEach { (line) in + let items = line.split(separator: ",") + if (token.starts(with: items[0])) { + // We found our URL + endpointURL = String(items[1]) + return + } + } + + guard let finalEndpointURL: String = endpointURL else { + throw APIError.error(reason: "No endpoint URL found") + } + + // Get Firebase token + let token: String? = String(data: firebaseToken, encoding: .utf8)?.components(separatedBy: "token=").last + if (token == nil) { + logger.error("Token empty! Response: \"\(firebaseToken.base64EncodedString(), privacy: .private)\"") + } + logger.debug("Token: \(firebaseToken.count)B") + self.keychain["FirebaseToken"] = token + + // return finalEndpointURL + return finalEndpointURL + } + .tryCompactMap { url -> AnyPublisher in + // Start configuring request + var request: URLRequest = URLRequest(url: URL(string: "\(url)/\(symbol)/mobile-api/Uczen.v3.UczenStart/Certyfikat")!) + request.httpMethod = "POST" + + guard let firebaseToken: String = self.keychain["FirebaseToken"] else { + throw APIError.error(reason: "No FirebaseToken") + } + + // Headers + request.setValue("RegisterDevice", forHTTPHeaderField: "RequestMobileType") + request.setValue("MobileUserAgent", forHTTPHeaderField: "User-Agent") + request.setValue("application/json", forHTTPHeaderField: "Content-Type") + request.setValue("gzip", forHTTPHeaderField: "Accept-Encoding") + + // Body + let timeNow: UInt64 = UInt64(floor(NSDate().timeIntervalSince1970)) + + let body: [String: Any] = [ + "RequestId": UUID().uuidString, + "TimeKey": (timeNow - 1), + "RemoteMobileTimeKey": timeNow, + "RemoteMobileAppVersion": "20.4.1.358", + "RemoteMobileAppName": "VULCAN-iOS-ModulUcznia", + "AppVersion": Bundle.main.buildVersion, + "DeviceId": UUID().uuidString, + "DeviceName": "vulcan @ \(Bundle.main.deviceName)", + "DeviceNameUser": Bundle.main.deviceName, + "DeviceDescription": "", + "DeviceSystemType": Bundle.main.systemName, + "DeviceSystemVersion": Bundle.main.systemVersion, + "TokenKey": token, + "PIN": String(pin), + "FirebaseTokenKey": firebaseToken + ] + let bodyData = try? JSONSerialization.data(withJSONObject: body) + request.httpBody = bodyData + + // Send the request and pass it + return URLSession.shared.dataTaskPublisher(for: request) + .receive(on: DispatchQueue.main) + .mapError { $0 as Error } + .map { $0.data } + .eraseToAnyPublisher() + } + .flatMap { $0 } + .tryMap { data -> [String: Any]? in + // Parse certificate + guard let json: [String: Any] = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { + throw APIError.error(reason: "Error serializing JSON") + } + + // Check for errors + if (json["IsError"] as? Bool ?? true) { + logger.error("IsError!") + logger.debug("\(json)") + throw APIError.error(reason: json["Message"] as? String ?? "Unknown") + } + + return json["TokenCert"] as? [String: Any] + } + .sink(receiveCompletion: { (completion) in + logger.info("Completion: \(String(describing: completion))") + switch (completion) { + case .finished: + self.ud.setValue(true, forKey: UserDefaults.AppKeys.isLoggedIn.rawValue) + logger.debug("Finished logging in!") + completionHandler(true, nil) + self.getUsers() + case .failure(let error): + logger.error("Error logging in: \(error.localizedDescription)") + completionHandler(false, error) + self.logOut() + } + }, receiveValue: { certificate in + guard let certificate: [String: Any] = certificate else { + logger.debug("`certificate` isn't a dictionary! Returning.") + return + } + + // Purge all saved data + self.logOut() + + // Save certificate + self.keychain["CertificatePfx"] = certificate["CertyfikatPfx"] as? String + self.keychain["CertificateKey"] = certificate["CertyfikatKlucz"] as? String + self.keychain["CertificateCreated"] = certificate["CertyfikatDataUtworzenia"] as? String + self.keychain["Username"] = certificate["UzytkownikNazwa"] as? String + self.endpointURL = certificate["AdresBazowyRestApi"] as? String + + logger.debug("Parsed certificate! Key: \(self.keychain["CertificateKey"] ?? "", privacy: .sensitive).") + }) + .store(in: &cancellableSet) + } + + /// Logs out, removing all stored data. + public func logOut() { + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Logout") + logger.debug("Logging out!") + + // Keychain + do { + logger.debug("Removing Keychain...") + try self.keychain.removeAll() + logger.debug("Done!") + } catch { + logger.error("Error removing Keychain: \(error.localizedDescription)") + } + + // Variables + ud.removeObject(forKey: UserDefaults.AppKeys.isLoggedIn.rawValue) + ud.removeObject(forKey: UserDefaults.AppKeys.userID.rawValue) + ud.removeObject(forKey: UserDefaults.AppKeys.showAllScheduleEvents.rawValue) + ud.removeObject(forKey: UserDefaults.AppKeys.readMessageOnOpen.rawValue) + ud.removeObject(forKey: UserDefaults.AppKeys.dictionaryLastFetched.rawValue) + + // CoreData + CoreDataModel.shared.clearDatabase() + + logger.debug("Finished logging out.") + } + + /// Sets the default user + /// - Parameter user: Selected user + /// - Parameter force: Force dictionary update + public func setUser(_ user: Vulcan.Student, force: Bool = false) { + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Users") + logger.debug("Setting default user with ID \(user.id, privacy: .sensitive) (\(user.loginID ?? -1, privacy: .sensitive) : \(user.userLoginID, privacy: .sensitive)).") + + ud.setValue(true, forKey: UserDefaults.AppKeys.isLoggedIn.rawValue) + ud.setValue(user.id, forKey: UserDefaults.AppKeys.userID.rawValue) + self.currentUser = user + self.getDictionary(force: force) + } + + /// Fetches and saves the dictionary. + /// - Parameter force: Ignore the saved dictionary? + public func getDictionary(force: Bool = false) { + if (self.dataState.dictionary.loading) { + return + } + + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Dictionary") + + // Return if no user/no endpoint URL + guard let user: Vulcan.Student = self.currentUser, let endpointURL: String = self.endpointURL else { + logger.error("Not logged in") + return + } + + let lastFetched: Date = Date(timeIntervalSince1970: TimeInterval(ud.integer(forKey: UserDefaults.AppKeys.dictionaryLastFetched.rawValue))) + let shouldUpdate: Bool = (lastFetched < (Calendar.autoupdatingCurrent.date(byAdding: .month, value: -1, to: Date()) ?? Date().startOfMonth)) || force + + // Should we update? + if (!shouldUpdate) { + logger.debug("Dictionary available - not updating. Date: \(lastFetched) (Age: \(Date(timeInterval: -(Date() - lastFetched), since: Date()).timestampString ?? "Unknown")).") + return + } + + logger.debug("Updating dictionary...") + + let request: URLRequest = URLRequest(url: URL(string: "\(endpointURL)\(user.reportingUnitSymbol)/mobile-api/Uczen.v3.Uczen/Slowniki")!) + self.dataState.dictionary.loading = true + + do { + try self.request(request) + .receive(on: DispatchQueue.main) + .tryMap { data -> [String: Any]? in + guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], + let data = json["Data"] as? [String: Any] else { + throw APIError.error(reason: "Error serializing JSON") + } + + return data + } + .sink(receiveCompletion: { completion in + logger.debug("Finished: \(String(describing: completion))") + self.dataState.dictionary.loading = false + switch (completion) { + case .finished: + break + case .failure(let error): + logger.error("\(error.localizedDescription)") + } + }, receiveValue: { dictionary in + guard let dictionary: [String: Any] = dictionary else { + logger.error("Error serializing data") + return + } + + let context = self.persistentContainer.viewContext + + // Teachers + Employees + if let teachersDictionary: [[String: Any]] = dictionary["Nauczyciele"] as? [[String: Any]], + let employeesDictionary: [[String: Any]] = dictionary["Pracownicy"] as? [[String: Any]], + let data: Data = try? JSONSerialization.data(withJSONObject: (teachersDictionary + employeesDictionary), options: []) { + let decoded: [Vulcan.Employee]? = try? JSONDecoder().decode([Vulcan.Employee].self, from: data) + if let decoded = decoded?.uniques { + let deleteRequest = NSBatchDeleteRequest(fetchRequest: DictionaryEmployee.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for item in decoded { + let object = DictionaryEmployee(context: context) + object.code = item.code + object.id = Int64(item.id) + object.name = item.name + object.surname = item.surname + + if let loginID = item.loginID { object.loginID = Int32(loginID) } + if let active = item.active { object.active = active } + if let teacher = item.teacher { object.teacher = teacher } + } + } + } + + // Subjects + if let rawDictionary: [[String: Any]] = dictionary["Przedmioty"] as? [[String: Any]], + let data: Data = try? JSONSerialization.data(withJSONObject: rawDictionary, options: []) { + let decoded: [Vulcan.Subject]? = try? JSONDecoder().decode([Vulcan.Subject].self, from: data) + if let decoded = decoded { + let deleteRequest = NSBatchDeleteRequest(fetchRequest: DictionarySubject.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for item in decoded { + let object = DictionarySubject(context: context) + object.active = item.active + object.code = item.code + object.id = Int64(item.id) + object.name = item.name + object.position = Int16(item.position) + } + } + } + + // Lesson times + if let rawDictionary: [[String: Any]] = dictionary["PoryLekcji"] as? [[String: Any]], + let data: Data = try? JSONSerialization.data(withJSONObject: rawDictionary, options: []) { + let decoded: [Vulcan.LessonTime]? = try? JSONDecoder().decode([Vulcan.LessonTime].self, from: data) + if let decoded = decoded { + let deleteRequest = NSBatchDeleteRequest(fetchRequest: DictionaryLessonTime.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for item in decoded { + let object = DictionaryLessonTime(context: context) + object.end = Int32(item.end) + object.id = Int64(item.id) + object.number = Int16(item.number) + object.start = Int32(item.start) + } + } + } + + // Grade categories + if let rawDictionary: [[String: Any]] = dictionary["KategorieOcen"] as? [[String: Any]], + let data: Data = try? JSONSerialization.data(withJSONObject: rawDictionary, options: []) { + let decoded: [Vulcan.GradeCategory]? = try? JSONDecoder().decode([Vulcan.GradeCategory].self, from: data) + if let decoded = decoded { + let deleteRequest = NSBatchDeleteRequest(fetchRequest: DictionaryGradeCategory.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for item in decoded { + let object = DictionaryGradeCategory(context: context) + object.code = item.code + object.id = Int64(item.id) + object.name = item.name + } + } + } + + // Note categories + if let rawDictionary: [[String: Any]] = dictionary["KategorieUwag"] as? [[String: Any]], + let data: Data = try? JSONSerialization.data(withJSONObject: rawDictionary, options: []) { + let decoded: [Vulcan.NoteCategory]? = try? JSONDecoder().decode([Vulcan.NoteCategory].self, from: data) + if let decoded = decoded { + let deleteRequest = NSBatchDeleteRequest(fetchRequest: DictionaryNoteCategory.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for item in decoded { + let object = DictionaryNoteCategory(context: context) + object.active = item.active + object.id = Int64(item.id) + object.name = item.name + } + } + } + + // Presence categories + if let rawDictionary: [[String: Any]] = dictionary["KategorieFrekwencji"] as? [[String: Any]], + let data: Data = try? JSONSerialization.data(withJSONObject: rawDictionary, options: []) { + let decoded: [Vulcan.PresenceCategory]? = try? JSONDecoder().decode([Vulcan.PresenceCategory].self, from: data) + if let decoded = decoded { + let deleteRequest = NSBatchDeleteRequest(fetchRequest: DictionaryPresenceCategory.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for item in decoded { + let object = DictionaryPresenceCategory(context: context) + object.justified = item.justified + object.exempt = item.exempt + object.id = Int64(item.id) + object.late = item.late + object.name = item.name + object.position = Int16(item.position) + object.present = item.present + object.removed = item.removed + } + } + } + + // Presence types + if let rawDictionary: [[String: Any]] = dictionary["TypyFrekwencji"] as? [[String: Any]], + let data: Data = try? JSONSerialization.data(withJSONObject: rawDictionary, options: []) { + let decoded: [Vulcan.PresenceType]? = try? JSONDecoder().decode([Vulcan.PresenceType].self, from: data) + if let decoded = decoded { + let deleteRequest = NSBatchDeleteRequest(fetchRequest: DictionaryPresenceType.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for item in decoded { + let object = DictionaryPresenceType(context: context) + object.active = item.active + object.categoryID = Int32(item.categoryID) + object.id = Int64(item.id) + object.isDefault = item.isDefault + object.name = item.name + object.symbol = item.symbol + } + } + } + + // Save + CoreDataModel.shared.saveContext(force: true) + self.ud.setValue(Int(Date().timeIntervalSince1970), forKey: UserDefaults.AppKeys.dictionaryLastFetched.rawValue) + }) + .store(in: &cancellableSet) + } catch { + logger.error("\(error.localizedDescription)") + self.dataState.dictionary.loading = false + } + } + + // MARK: - Data functions + + /// Get and parse available users. + /// - Parameter completionHandler: Callback + public func getUsers(completionHandler: @escaping (Error?) -> () = { _ in }) { + // Return if already pending + if (self.dataState.users.loading) { + completionHandler(nil) + return + } + + // Return if no endpoint URL + guard let endpointURL: String = self.endpointURL else { + completionHandler(APIError.error(reason: "No endpoint")) + return + } + + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Users") + logger.debug("Requesting users...") + + let request: URLRequest = URLRequest(url: URL(string: "\(endpointURL)mobile-api/Uczen.v3.UczenStart/ListaUczniow")!) + self.dataState.users.loading = true + + do { + try self.request(request) + .receive(on: DispatchQueue.main) + .tryMap { data in + guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], + let objects = json["Data"] as? [[String: Any]] else { + throw APIError.error(reason: "Error serializing JSON") + } + + return try JSONSerialization.data(withJSONObject: objects, options: []) + } + .decode(type: [Vulcan.Student].self, decoder: JSONDecoder()) + .sink(receiveCompletion: { (completion) in + self.dataState.users.loading = false + switch completion { + case .finished: + self.dataState.users.lastFetched = Date() + completionHandler(nil) + if let user: Vulcan.Student = self.users.first(where: { $0.id == self.ud.integer(forKey: UserDefaults.AppKeys.userID.rawValue) }) { + self.setUser(user) + } else if (self.users.count == 1), let user: Vulcan.Student = self.users.first { + self.setUser(user) + } + case .failure(let error): + logger.error("\(error.localizedDescription)") + completionHandler(error) + } + }, receiveValue: { users in + logger.debug("Received \(users.count) user(s).") + self.users = users + + let context = self.persistentContainer.viewContext + let deleteRequest = NSBatchDeleteRequest(fetchRequest: StoredStudent.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for user in users { + _ = user.entity(context: context) + } + + CoreDataModel.shared.saveContext() + }) + .store(in: &cancellableSet) + } catch { + logger.error("\(error.localizedDescription)") + self.dataState.users.loading = false + completionHandler(error) + } + } + + /// Gets selected user's schedule. + /// - Parameter isPersistent: Should data be preserved? + /// - Parameter startDate: From this date + /// - Parameter endDate: To this date + /// - Parameter completionHandler: Callback + public func getSchedule(isPersistent: Bool = true, from startDate: Date, to endDate: Date, completionHandler: @escaping (Error?) -> () = { _ in }) { + // Return if no user + guard let user: Vulcan.Student = self.currentUser else { + completionHandler(APIError.error(reason: "Not logged in")) + return + } + + // Return if already pending + if (self.dataState.schedule.loading) { + completionHandler(nil) + return + } + + // Return if no endpoint URL + guard let endpointURL: String = self.endpointURL else { + completionHandler(APIError.error(reason: "No endpoint")) + return + } + + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Schedule") + logger.debug("Getting schedule of user with ID \(user.userLoginID, privacy: .private) from \(startDate.formattedString(format: "yyyy-MM-dd")) to \(endDate.formattedString(format: "yyyy-MM-dd")) (persistent: \(isPersistent))...") + self.dataState.schedule.loading = true + + var tempSchedule = self.schedule + + var request: URLRequest = URLRequest(url: URL(string: "\(endpointURL)\(user.reportingUnitSymbol)/mobile-api/Uczen.v3.Uczen/PlanLekcjiZeZmianami")!) + + let body: [String: Any] = [ + "DataPoczatkowa": startDate.formattedString(format: "yyyy-MM-dd"), + "DataKoncowa": endDate.formattedString(format: "yyyy-MM-dd"), + "IdOddzial": user.unitID, + "IdOkresKlasyfikacyjny": user.classificationPeriodID, + "IdUczen": user.id, + "LoginId": user.userLoginID + ] + let bodyData = try? JSONSerialization.data(withJSONObject: body) + request.httpBody = bodyData + + do { + try self.request(request) + .receive(on: DispatchQueue.main) + .tryMap { data in + guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], + let objects = json["Data"] as? [[String: Any]] else { + throw APIError.error(reason: "Error serializing JSON") + } + + return try JSONSerialization.data(withJSONObject: objects, options: []) + } + .decode(type: [Vulcan.ScheduleEvent].self, decoder: JSONDecoder()) + .sink(receiveCompletion: { (completion) in + self.dataState.schedule.loading = false + switch completion { + case .finished: + self.schedule = tempSchedule + self.dataState.schedule.lastFetched = Date() + self.scheduleDidChange.send(isPersistent) + completionHandler(nil) + + if self.ud.bool(forKey: UserDefaults.AppKeys.enableScheduleNotifications.rawValue) { + self.schedule + .flatMap(\.events) + .filter { $0.dateStarts != nil && $0.dateStarts ?? $0.date >= Date() } + .filter { $0.isUserSchedule } + .forEach(self.addScheduleEventNotification) + } + case .failure(let error): + logger.error("\(error.localizedDescription)") + completionHandler(error) + } + }, receiveValue: { events in + logger.debug("Received \(events.count) event(s).") + + let context = self.persistentContainer.viewContext + guard let dictionarySubjects: [DictionarySubject] = try? context.fetch(DictionarySubject.fetchRequest()), + let dictionaryEmployees: [DictionaryEmployee] = try? context.fetch(DictionaryEmployee.fetchRequest()), + let dictionaryLessonTimes: [DictionaryLessonTime] = try? context.fetch(DictionaryLessonTime.fetchRequest()) else { + logger.error("Couldn't fetch entities!") + return + } + + tempSchedule = Dictionary(grouping: events.sorted { $0.lessonOfTheDay < $1.lessonOfTheDay }, by: \.date) + .compactMap { date, events in + let events = events + .map { event -> Vulcan.ScheduleEvent in + var event = event + + if let subject: DictionarySubject = dictionarySubjects.first(where: { $0.id == event.subjectID }) { + event.subject = subject + } + + if let employee: DictionaryEmployee = dictionaryEmployees.first(where: { $0.id == event.employeeID }), + let employeeName = employee.name, + let employeeSurname = employee.surname { + event.employee = employee + event.employeeFullName = "\(employeeName) \(employeeSurname)" + } + + if let lessonTime: DictionaryLessonTime = dictionaryLessonTimes.first(where: { $0.id == event.lessonTimeID }) { + event.dateStartsEpoch = TimeInterval(event.dateEpoch + Int(lessonTime.start) + 3600) + event.dateEndsEpoch = TimeInterval(event.dateEpoch + Int(lessonTime.end) + 3600) + } + + return event + } + .sorted { $0.lessonOfTheDay < $1.lessonOfTheDay } + + return Vulcan.Schedule(date: date, events: events) + } + .sorted { $0.date < $1.date } + + if isPersistent { + let context = self.persistentContainer.viewContext + let events = tempSchedule.flatMap(\.events) + + do { + let oneMonthAgo: Date = Calendar.autoupdatingCurrent.date(byAdding: .month, value: -1, to: Date()) ?? Date().startOfMonth + let oneMonthInFuture: Date = Calendar.autoupdatingCurrent.date(byAdding: .month, value: 1, to: Date()) ?? Date().endOfMonth + + let fetchRequest: NSFetchRequest = StoredScheduleEvent.fetchRequest() + if let startPeriod = events.first?.date.startOfDay, + let endPeriod = events.last?.date.endOfDay { + fetchRequest.predicate = NSPredicate( + format: "(dateEpoch >= %i AND dateEpoch <= %i) OR (dateEpoch <= %i OR dateEpoch >= %i)", + Int(startPeriod.timeIntervalSince1970), + Int(endPeriod.timeIntervalSince1970), + Int(oneMonthAgo.timeIntervalSince1970), + Int(oneMonthInFuture.timeIntervalSince1970) + ) + } else { + fetchRequest.predicate = NSPredicate(format: "dateEpoch <= %i OR dateEpoch >= %i", Int(oneMonthAgo.timeIntervalSince1970), Int(oneMonthInFuture.timeIntervalSince1970)) + } + + try context.execute(NSBatchDeleteRequest(fetchRequest: fetchRequest)) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for event in tempSchedule.flatMap(\.events) { + _ = event.entity(context: context) + } + + CoreDataModel.shared.saveContext() + } + }) + .store(in: &cancellableSet) + } catch { + logger.error("\(error.localizedDescription)") + self.dataState.schedule.loading = false + completionHandler(error) + } + } + + /// Gets selected user's grades. + /// - Parameter isPersistent: Should data be preserved? + /// - Parameter completionHandler: Callback + public func getGrades(isPersistent: Bool = true, completionHandler: @escaping (Error?) -> () = { _ in }) { + // Return if no user + guard let user: Vulcan.Student = self.currentUser else { + completionHandler(APIError.error(reason: "Not logged in")) + return + } + + // Return if already pending + if (self.dataState.grades.loading) { + completionHandler(nil) + return + } + + // Return if no endpoint URL + guard let endpointURL: String = self.endpointURL else { + completionHandler(APIError.error(reason: "No endpoint")) + return + } + + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Grades") + logger.debug("Getting grades of user with ID \(user.userLoginID, privacy: .private)...") + self.dataState.grades.loading = true + + var tempGrades = self.grades + + var request: URLRequest = URLRequest(url: URL(string: "\(endpointURL)\(user.reportingUnitSymbol)/mobile-api/Uczen.v3.Uczen/Oceny")!) + + let body: [String: Any] = [ + "IdOkresKlasyfikacyjny": user.classificationPeriodID, + "IdUczen": user.id + ] + let bodyData = try? JSONSerialization.data(withJSONObject: body) + request.httpBody = bodyData + + do { + try self.request(request) + .receive(on: DispatchQueue.main) + .tryMap { data in + guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], + let objects = json["Data"] as? [[String: Any]] else { + throw APIError.error(reason: "Error serializing JSON") + } + + return try JSONSerialization.data(withJSONObject: objects, options: []) + } + .decode(type: [Vulcan.Grade].self, decoder: JSONDecoder()) + .sink(receiveCompletion: { (completion) in + self.dataState.grades.loading = false + switch completion { + case .finished: + self.grades = tempGrades + self.dataState.grades.lastFetched = Date() + completionHandler(nil) + case .failure(let error): + logger.error("\(error.localizedDescription)") + completionHandler(error) + } + }, receiveValue: { grades in + logger.debug("Received \(grades.count) grade(s).") + + let context = self.persistentContainer.viewContext + guard let dictionarySubjects: [DictionarySubject] = try? context.fetch(DictionarySubject.fetchRequest()), + let dictionaryEmployees: [DictionaryEmployee] = try? context.fetch(DictionaryEmployee.fetchRequest()), + let dictionaryGradeCategories: [DictionaryGradeCategory] = try? context.fetch(DictionaryGradeCategory.fetchRequest()) else { + logger.error("Couldn't fetch entities!") + return + } + + let dictionary = Dictionary(grouping: grades, by: \.subjectID) + tempGrades = dictionary + .compactMap { subjectID, grades in + guard let dictionarySubject: DictionarySubject = dictionarySubjects.first(where: { $0.id == subjectID }), + let subjectName: String = dictionarySubject.name, + let subjectCode: String = dictionarySubject.code, + let dEmployeeID = grades.first?.dEmployeeID, + let dictionaryEmployee: DictionaryEmployee = dictionaryEmployees.first(where: { $0.id == dEmployeeID }), + let employeeName: String = dictionaryEmployee.name, + let employeeSurname: String = dictionaryEmployee.surname, + let employeeCode: String = dictionaryEmployee.code + else { + return nil + } + + let subject: Vulcan.Subject = Vulcan.Subject(id: Int(dictionarySubject.id), name: subjectName, code: subjectCode, active: dictionarySubject.active, position: Int(dictionarySubject.position)) + let employee: Vulcan.Employee = Vulcan.Employee(id: Int(dictionaryEmployee.id), name: employeeName, surname: employeeSurname, code: employeeCode, active: dictionaryEmployee.active, teacher: dictionaryEmployee.teacher, loginID: Int(dictionaryEmployee.loginID)) + + let grades: [Vulcan.Grade] = grades + .map { grade -> Vulcan.Grade in + var grade = grade + + if let categoryID = grade.categoryID { + grade.category = dictionaryGradeCategories.first(where: { $0.id == categoryID }) + } + + return grade + } + .sorted { ($0.dateCreated, $0.entry ?? "") < ($1.dateCreated, $1.entry ?? "") } + + let subjectGrades = Vulcan.SubjectGrades(subject: subject, employee: employee, grades: grades) + + if let currentSubjectGrades = self.grades.first(where: { $0.subject.id == subject.id })?.grades { + subjectGrades.hasNewItems = grades.sorted(by: { ($0.dateCreated, $0.entry ?? "") < ($1.dateCreated, $1.entry ?? "") }) != currentSubjectGrades.sorted(by: { ($0.dateCreated, $0.entry ?? "") < ($1.dateCreated, $1.entry ?? "") }) + } else { + subjectGrades.hasNewItems = true + } + + return subjectGrades + } + .sorted { $0.subject.name < $1.subject.name } + + if isPersistent { + let context = self.persistentContainer.viewContext + let deleteRequest = NSBatchDeleteRequest(fetchRequest: StoredGrade.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for grade in grades { + _ = grade.entity(context: context) + } + + CoreDataModel.shared.saveContext() + } + }) + .store(in: &cancellableSet) + } catch { + logger.error("\(error.localizedDescription)") + self.dataState.grades.loading = false + completionHandler(error) + } + } + + /// Gets selected user's final grades. + /// - Parameter completionHandler: Callback + public func getEndOfTermGrades(completionHandler: @escaping (Error?) -> () = { _ in }) { + // Return if no user + guard let user: Vulcan.Student = self.currentUser else { + completionHandler(APIError.error(reason: "Not logged in")) + return + } + + // Return if already pending + if (self.dataState.eotGrades.loading) { + completionHandler(nil) + return + } + + // Return if no endpoint URL + guard let endpointURL: String = self.endpointURL else { + completionHandler(APIError.error(reason: "No endpoint")) + return + } + + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "EOTGrades") + logger.debug("Getting end of term grades of user with ID \(user.userLoginID, privacy: .private)...") + self.dataState.eotGrades.loading = true + + var tempEOTGrades = self.eotGrades + + var request: URLRequest = URLRequest(url: URL(string: "\(endpointURL)\(user.reportingUnitSymbol)/mobile-api/Uczen.v3.Uczen/OcenyPodsumowanie")!) + + let body: [String: Any] = [ + "IdOkresKlasyfikacyjny": user.classificationPeriodID, + "IdUczen": user.id, + ] + let bodyData = try? JSONSerialization.data(withJSONObject: body) + request.httpBody = bodyData + + do { + try self.request(request) + .receive(on: DispatchQueue.main) + .tryMap { data -> ([Vulcan.EndOfTermGrade], [Vulcan.EndOfTermGrade], [Vulcan.EndOfTermPoints]) in + guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], + let objects: [String: Any] = json["Data"] as? [String: Any] else { + throw APIError.error(reason: "Error serializing JSON") + } + + guard let expectedObjects: [[String: Any]] = objects["OcenyPrzewidywane"] as? [[String: Any]], + let expectedData: Data = try? JSONSerialization.data(withJSONObject: expectedObjects, options: []), + let finalObjects: [[String: Any]] = objects["OcenyKlasyfikacyjne"] as? [[String: Any]], + let finalData: Data = try? JSONSerialization.data(withJSONObject: finalObjects, options: []), + let pointsObjects: [[String: Any]] = objects["SrednieOcen"] as? [[String: Any]], + let pointsData: Data = try? JSONSerialization.data(withJSONObject: pointsObjects, options: []) + else { + throw APIError.error(reason: "Error serializing JSON") + } + + let decoder: JSONDecoder = JSONDecoder() + return ( + try decoder.decode([Vulcan.EndOfTermGrade].self, from: expectedData), + try decoder.decode([Vulcan.EndOfTermGrade].self, from: finalData), + try decoder.decode([Vulcan.EndOfTermPoints].self, from: pointsData)) + } + .sink(receiveCompletion: { (completion) in + self.dataState.eotGrades.loading = false + switch completion { + case .finished: + self.eotGrades = tempEOTGrades + self.dataState.eotGrades.lastFetched = Date() + completionHandler(nil) + case .failure(let error): + logger.error("\(error.localizedDescription)") + completionHandler(error) + } + }, receiveValue: { expected, final, points in + logger.debug("Received \(expected.count) expected, \(final.count) final grade(s) and \(points.count) points object(s).") + + let context = self.persistentContainer.viewContext + guard let dictionarySubjects: [DictionarySubject] = try? context.fetch(DictionarySubject.fetchRequest()) else { + logger.error("Couldn't fetch entities!") + return + } + + let expectedGrades: [EndOfTermGrade] = expected + .map { grade in + var grade = grade + grade.subject = dictionarySubjects.first(where: { $0.id == grade.subjectID }) + grade.type = .expected + + return grade + } + .sorted { $0.subject?.name ?? "" < $1.subject?.name ?? "" } + + let finalGrades: [EndOfTermGrade] = final + .map { grade in + var grade = grade + grade.subject = dictionarySubjects.first(where: { $0.id == grade.subjectID }) + grade.type = .final + + return grade + } + .sorted { $0.subject?.name ?? "" < $1.subject?.name ?? "" } + + tempEOTGrades = (expectedGrades + finalGrades).sorted { ($0.type ?? .unknown) < ($1.type ?? .unknown) } + + do { + try context.execute(NSBatchDeleteRequest(fetchRequest: StoredEndOfTermGrade.fetchRequest())) + try context.execute(NSBatchDeleteRequest(fetchRequest: StoredEndOfTermPoints.fetchRequest())) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for grade in self.eotGrades { + _ = grade.entity(context: context) + } + + for subjectPoints in points { + _ = subjectPoints.entity(context: context) + } + + CoreDataModel.shared.saveContext() + }) + .store(in: &cancellableSet) + } catch { + logger.error("\(error.localizedDescription)") + self.dataState.eotGrades.loading = false + completionHandler(error) + } + } + + /// Gets selected user's notes. + /// - Parameter completionHandler: Callback + public func getNotes(completionHandler: @escaping (Error?) -> () = { _ in }) { + // Return if no user + guard let user: Vulcan.Student = self.currentUser else { + completionHandler(APIError.error(reason: "Not logged in")) + return + } + + // Return if already pending + if (self.dataState.notes.loading) { + completionHandler(nil) + return + } + + // Return if no endpoint URL + guard let endpointURL: String = self.endpointURL else { + completionHandler(APIError.error(reason: "No endpoint")) + return + } + + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Notes") + logger.debug("Getting notes of user with ID \(user.userLoginID, privacy: .private)...") + self.dataState.notes.loading = true + + var tempNotes = self.notes + + var request: URLRequest = URLRequest(url: URL(string: "\(endpointURL)\(user.reportingUnitSymbol)/mobile-api/Uczen.v3.Uczen/UwagiUcznia")!) + + let body: [String: Any] = [ + "IdOkresKlasyfikacyjny": user.classificationPeriodID, + "IdUczen": user.id, + ] + let bodyData = try? JSONSerialization.data(withJSONObject: body) + request.httpBody = bodyData + + do { + try self.request(request) + .receive(on: DispatchQueue.main) + .tryMap { data in + guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], + let objects = json["Data"] as? [[String: Any]] else { + throw APIError.error(reason: "Error serializing JSON") + } + + return try JSONSerialization.data(withJSONObject: objects, options: []) + } + .decode(type: [Vulcan.Note].self, decoder: JSONDecoder()) + .sink(receiveCompletion: { (completion) in + self.dataState.notes.loading = false + switch completion { + case .finished: + self.notes = tempNotes + self.dataState.notes.lastFetched = Date() + completionHandler(nil) + case .failure(let error): + logger.error("\(error.localizedDescription)") + completionHandler(error) + } + }, receiveValue: { notes in + logger.debug("Received \(notes.count) note(s).") + + let context = self.persistentContainer.viewContext + guard let dictionaryEmployees: [DictionaryEmployee] = try? context.fetch(DictionaryEmployee.fetchRequest()), + let dictionaryNoteCategories: [DictionaryNoteCategory] = try? context.fetch(DictionaryNoteCategory.fetchRequest()) else { + logger.error("Couldn't fetch entities!") + return + } + + tempNotes = notes + .map { note in + var note = note + note.employee = dictionaryEmployees.first(where: { $0.id == note.employeeID }) + if let categoryID = note.categoryID, + let category = dictionaryNoteCategories.first(where: { $0.id == categoryID }) { + note.category = category + } + + return note + } + .sorted { $0.date < $1.date } + + let deleteRequest = NSBatchDeleteRequest(fetchRequest: StoredNote.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for note in notes { + _ = note.entity(context: context) + } + + CoreDataModel.shared.saveContext() + }) + .store(in: &cancellableSet) + } catch { + logger.error("\(error.localizedDescription)") + self.dataState.notes.loading = false + completionHandler(error) + } + } + + /// Gets selected user's tasks. + /// - Parameters: + /// - isPersistent: Should data be preserved? + /// - startDate: From this date + /// - endDate: To this date + /// - completionHandler: Callback + public func getTasks(isPersistent: Bool = true, from startDate: Date, to endDate: Date, completionHandler: @escaping (Error?) -> () = { _ in }) { + // Return if no user + guard let user: Vulcan.Student = self.currentUser else { + completionHandler(APIError.error(reason: "Not logged in")) + return + } + + // Return if already pending + if (self.dataState.tasks.loading) { + completionHandler(nil) + return + } + + // Return if no endpoint URL + guard let endpointURL: String = self.endpointURL else { + completionHandler(APIError.error(reason: "No endpoint")) + return + } + + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Tasks") + logger.debug("Getting tasks from \(startDate.formattedString(format: "yyyy-MM-dd")) to \(endDate.formattedString(format: "yyyy-MM-dd")) (persistent: \(isPersistent))...") + self.dataState.tasks.loading = true + + var tempTasks = self.tasks + + let body: [String: Any] = [ + "DataPoczatkowa": startDate.formattedString(format: "yyyy-MM-dd"), + "DataKoncowa": endDate.formattedString(format: "yyyy-MM-dd"), + "IdOddzial": user.branchID, + "IdOkresKlasyfikacyjny": user.classificationPeriodID, + "IdUczen": user.id, + ] + let bodyData = try? JSONSerialization.data(withJSONObject: body) + + var examsRequest: URLRequest = URLRequest(url: URL(string: "\(endpointURL)\(user.reportingUnitSymbol)/mobile-api/Uczen.v3.Uczen/Sprawdziany")!) + examsRequest.httpBody = bodyData + + var homeworkRequest: URLRequest = URLRequest(url: URL(string: "\(endpointURL)\(user.reportingUnitSymbol)/mobile-api/Uczen.v3.Uczen/ZadaniaDomowe")!) + homeworkRequest.httpBody = bodyData + + do { + let examsPublisher = try self.request(examsRequest) + let homeworkPublisher = try self.request(homeworkRequest) + + Publishers.Zip(examsPublisher, homeworkPublisher) + .receive(on: DispatchQueue.main) + .tryMap { examsResponse, homeworkResponse -> ([Vulcan.Exam], [Vulcan.Homework]) in + let decoder: JSONDecoder = JSONDecoder() + let error = APIError.error(reason: "Error serializing JSON") + + // Exams + guard let examsJSON = try JSONSerialization.jsonObject(with: examsResponse, options: []) as? [String: Any], + let examsObject = examsJSON["Data"] as? [[String: Any]], + let examsData = try? JSONSerialization.data(withJSONObject: examsObject, options: []), + let exams = try? decoder.decode([Vulcan.Exam].self, from: examsData) else { + throw error + } + + // Homework + guard let homeworkJSON = try JSONSerialization.jsonObject(with: homeworkResponse, options: []) as? [String: Any], + let homeworkObject = homeworkJSON["Data"] as? [[String: Any]], + let homeworkData = try? JSONSerialization.data(withJSONObject: homeworkObject, options: []), + let homework = try? decoder.decode([Vulcan.Homework].self, from: homeworkData) else { + throw error + } + + return (exams, homework) + } + .sink(receiveCompletion: { completion in + self.dataState.tasks.loading = false + switch completion { + case .finished: + self.tasks = tempTasks + self.dataState.tasks.lastFetched = Date() + completionHandler(nil) + + if self.ud.bool(forKey: UserDefaults.AppKeys.enableTaskNotifications.rawValue) { + tempTasks.exams + .filter { $0.date >= Date() } + .forEach { task in + self.addTaskNotification(task, isBigType: task.isBigType) + } + + tempTasks.homework + .filter { $0.date >= Date() } + .forEach { task in + self.addTaskNotification(task) + } + } + case .failure(let error): + logger.error("\(error.localizedDescription)") + completionHandler(error) + } + }, receiveValue: { exams, homework in + logger.debug("Received \(exams.count) exam and \(homework.count) homework task(s).") + + let context = self.persistentContainer.viewContext + guard let dictionarySubjects: [DictionarySubject] = try? context.fetch(DictionarySubject.fetchRequest()), + let dictionaryEmployees: [DictionaryEmployee] = try? context.fetch(DictionaryEmployee.fetchRequest()) else { + logger.error("Couldn't fetch entities!") + return + } + + let exams: [Vulcan.Exam] = exams + .map { exam in + exam.subject = dictionarySubjects.first(where: { $0.id == exam.subjectID }) + exam.employee = dictionaryEmployees.first(where: { $0.id == exam.employeeID }) + + return exam + } + .sorted { ($0.date, $0.subject?.name ?? "", $0.entry) < ($1.date, $1.subject?.name ?? "", $1.entry) } + + let homework: [Vulcan.Homework] = homework + .map { task in + task.subject = dictionarySubjects.first(where: { $0.id == task.subjectID }) + task.employee = dictionaryEmployees.first(where: { $0.id == task.employeeID }) + + return task + } + .sorted { ($0.date, $0.subject?.name ?? "", $0.entry) < ($1.date, $1.subject?.name ?? "", $1.entry) } + + tempTasks = Vulcan.Tasks(exams: exams, homework: homework) + + if isPersistent { + do { + // let oneMonthAgo: Date = Calendar.autoupdatingCurrent.date(byAdding: .month, value: -1, to: Date()) ?? Date().startOfMonth + // let oneMonthInFuture: Date = Calendar.autoupdatingCurrent.date(byAdding: .month, value: 1, to: Date()) ?? Date().endOfMonth + + let examsFetchRequest: NSFetchRequest = StoredExam.fetchRequest() + // examsFetchRequest.predicate = NSPredicate(format: "dateEpoch <= %i OR dateEpoch >= %i", Int(oneMonthAgo.timeIntervalSince1970), Int(oneMonthInFuture.timeIntervalSince1970)) + + let homeworkFetchRequest: NSFetchRequest = StoredHomework.fetchRequest() + // homeworkFetchRequest.predicate = NSPredicate(format: "dateEpoch <= %i OR dateEpoch >= %i", Int(oneMonthAgo.timeIntervalSince1970), Int(oneMonthInFuture.timeIntervalSince1970)) + + try context.execute(NSBatchDeleteRequest(fetchRequest: examsFetchRequest)) + try context.execute(NSBatchDeleteRequest(fetchRequest: homeworkFetchRequest)) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for exam in exams { + _ = exam.entity(context: context) + } + + for task in homework { + _ = task.entity(context: context) + } + + CoreDataModel.shared.saveContext() + } + }) + .store(in: &cancellableSet) + } catch { + logger.error("\(error.localizedDescription)") + self.dataState.tasks.loading = false + completionHandler(error) + } + } + + /// Gets selected user's messages with a specified tag. + /// - Parameters: + /// - tag: Messages tag + /// - isPersistent: Should data be preserved? + /// - startDate: From this date + /// - endDate: To this date + /// - completionHandler: Callback + public func getMessages(tag: Vulcan.MessageTag, isPersistent: Bool = true, from startDate: Date, to endDate: Date, completionHandler: @escaping (Error?) -> () = { _ in }) { + // Return if no user + guard let user: Vulcan.Student = self.currentUser else { + completionHandler(APIError.error(reason: "Not logged in")) + return + } + + // Return if already pending + if (self.dataState.messages[tag]?.loading ?? true) { + completionHandler(nil) + return + } + + // Return if no endpoint URL + guard let endpointURL: String = self.endpointURL else { + completionHandler(APIError.error(reason: "No endpoint")) + return + } + + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Messages") + logger.debug("Getting messages of user with ID \(user.userLoginID, privacy: .private) with tag \"\(tag.rawValue)\" from \(startDate.formattedString(format: "yyyy-MM-dd")) to \(endDate.formattedString(format: "yyyy-MM-dd")) (persistent: \(isPersistent))...") + self.dataState.messages[tag]?.loading = true + + var tempMessages = self.messages[tag] ?? [] + + var tagEndpoint: String + switch (tag) { + case .received: tagEndpoint = "WiadomosciOdebrane" + case .deleted: tagEndpoint = "WiadomosciUsuniete" + case .sent: tagEndpoint = "WiadomosciWyslane" + } + + var request: URLRequest = URLRequest(url: URL(string: "\(endpointURL)\(user.reportingUnitSymbol)/mobile-api/Uczen.v3.Uczen/\(tagEndpoint)")!) + + let body: [String: Any] = [ + "DataPoczatkowa": Int(startDate.timeIntervalSince1970), + "DataKoncowa": Int(endDate.timeIntervalSince1970), + "LoginId": user.userLoginID, + "IdUczen": user.id, + ] + let bodyData = try? JSONSerialization.data(withJSONObject: body) + request.httpBody = bodyData + + do { + try self.request(request) + .receive(on: DispatchQueue.main) + .tryMap { data in + guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any], + let objects = json["Data"] as? [[String: Any]] else { + throw APIError.error(reason: "Error serializing JSON") + } + + return try JSONSerialization.data(withJSONObject: objects, options: []) + } + .decode(type: [Vulcan.Message].self, decoder: JSONDecoder()) + .sink(receiveCompletion: { (completion) in + self.dataState.messages[tag]?.loading = false + switch completion { + case .finished: + self.messages[tag] = tempMessages + self.dataState.messages[tag]?.lastFetched = Date() + completionHandler(nil) + case .failure(let error): + logger.error("\(error.localizedDescription)") + completionHandler(error) + } + }, receiveValue: { messages in + logger.debug("Received \(messages.count) message(s).") + + let messages = messages + .map { message -> Vulcan.Message in + message.tag = tag + return message + } + .sorted { $0.dateSent > $1.dateSent } + + tempMessages = messages + + if isPersistent { + let context = self.persistentContainer.viewContext + + do { + let oneMonthAgo: Date = Calendar.autoupdatingCurrent.date(byAdding: .month, value: -1, to: Date()) ?? Date().startOfMonth + let oneMonthInFuture: Date = Calendar.autoupdatingCurrent.date(byAdding: .month, value: 1, to: Date()) ?? Date().endOfMonth + + let fetchRequest: NSFetchRequest = StoredMessage.fetchRequest() + fetchRequest.predicate = NSPredicate(format: "dateSentEpoch <= %i OR dateSentEpoch >= %i", Int(oneMonthAgo.timeIntervalSince1970), Int(oneMonthInFuture.timeIntervalSince1970)) + + switch (tag) { + case .deleted: fetchRequest.predicate = NSPredicate(format: "status == %@", "Usunieta") + case .received: fetchRequest.predicate = NSPredicate(format: "status == %@ AND folder == %@", "Widoczna", "Odebrane") + case .sent: fetchRequest.predicate = NSPredicate(format: "status == %@ AND folder == %@", "Widoczna", "Wyslane") + } + + try context.execute(NSBatchDeleteRequest(fetchRequest: fetchRequest)) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for message in messages { + _ = message.entity(context: context) + } + + CoreDataModel.shared.saveContext() + } + }) + .store(in: &cancellableSet) + } catch { + logger.error("\(error.localizedDescription)") + self.dataState.messages[tag]?.loading = false + completionHandler(error) + } + } + + /// Moves a message to specified folder. + /// - Parameters: + /// - message: Message + /// - folder: Folder to move the message to + /// - completionHandler: Callback + public func moveMessage(message: Vulcan.Message, to folder: Vulcan.MessageFolder, completionHandler: @escaping (Error?) -> () = { _ in }) { + // Return if no user + guard let user: Vulcan.Student = self.currentUser else { + completionHandler(APIError.error(reason: "Not logged in")) + return + } + + // Return if no endpoint URL + guard let endpointURL: String = self.endpointURL else { + completionHandler(APIError.error(reason: "No endpoint")) + return + } + + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Messages") + logger.debug("Moving a message with ID \(message.id, privacy: .sensitive) to folder \"\(folder.rawValue)\"...") + + var request: URLRequest = URLRequest(url: URL(string: "\(endpointURL)\(user.reportingUnitSymbol)/mobile-api/Uczen.v3.Uczen/ZmienStatusWiadomosci")!) + + let body: [String: Any] = [ + "WiadomoscId": message.id, + "FolderWiadomosci": message.folder, + "Status": folder.rawValue, + "LoginId": user.userLoginID, + "IdUczen": user.id, + ] + + let bodyData = try? JSONSerialization.data(withJSONObject: body) + request.httpBody = bodyData + + do { + try self.request(request) + .receive(on: DispatchQueue.main) + .tryMap { data -> [String: Any] in + guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { + throw APIError.error(reason: "Error serializing JSON") + } + + return json + } + .sink(receiveCompletion: { completion in + switch completion { + case .finished: + completionHandler(nil) + case .failure(let error): + logger.error("\(error.localizedDescription)") + completionHandler(error) + } + }, receiveValue: { response in + let success: Bool = (response["Status"] as? String ?? "").lowercased() == "ok" + logger.debug("Received a response with status \"\(response["Status"] as? String ?? "")\".") + + if success { + switch folder { + case .deleted: + self.messages[message.tag ?? .received]?.removeAll(where: { $0.id == message.id }) + let message = message + message.folder = folder.rawValue + message.tag = .deleted + self.messages[.deleted]?.append(message) + case .read: self.messages.flatMap(\.value).first(where: { $0.id == message.id })?.hasBeenRead = true + } + + completionHandler(nil) + } else { + completionHandler(APIError.error(reason: response["Status"] as? String ?? "Unknown error")) + } + }) + .store(in: &cancellableSet) + } catch { + logger.error("\(error.localizedDescription)") + completionHandler(error) + } + } + + /// Sends a new message to specified recipients. + /// - Parameters: + /// - recipients: Recipients + /// - title: Message title + /// - content: Message content + /// - completionHandler: Callback + public func sendMessage(to recipients: [Vulcan.Recipient], title: String, content: String, completionHandler: @escaping (Error?) -> () = { _ in }) { + // Return if no user + guard let user: Vulcan.Student = self.currentUser else { + completionHandler(APIError.error(reason: "Not logged in")) + return + } + + // Return if no endpoint URL + guard let endpointURL: String = self.endpointURL else { + completionHandler(APIError.error(reason: "No endpoint")) + return + } + + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Messages") + logger.debug("Sending a message with title \(title, privacy: .sensitive) to recipients with ID(s) \(recipients.map(\.id))...") + + var request: URLRequest = URLRequest(url: URL(string: "\(endpointURL)\(user.reportingUnitSymbol)/mobile-api/Uczen.v3.Uczen/DodajWiadomosc")!) + + let body: [String: Any] = [ + "NadawcaWiadomosci": "\(user.surname) \(user.name)", + "Tytul": title, + "Tresc": content, + "Adresaci": recipients.map { recipient in + [ + "LoginId": recipient.id, + "Nazwa": recipient.name + ] + }, + "LoginId": user.userLoginID, + "IdUczen": user.id, + + ] + + let bodyData = try? JSONSerialization.data(withJSONObject: body) + request.httpBody = bodyData + + do { + try self.request(request) + .receive(on: DispatchQueue.main) + .tryMap { data -> [String: Any] in + guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { + throw APIError.error(reason: "Error serializing JSON") + } + + return json + } + .sink(receiveCompletion: { completion in + switch completion { + case .finished: + completionHandler(nil) + case .failure(let error): + logger.error("\(error.localizedDescription)") + completionHandler(error) + } + }, receiveValue: { response in + let success: Bool = (response["Status"] as? String ?? "").lowercased() == "ok" + logger.debug("Received a response with status \"\(response["Status"] as? String ?? "")\".") + + completionHandler(success ? nil : APIError.error(reason: response["Status"] as? String ?? "Unknown error")) + }) + .store(in: &cancellableSet) + } catch { + logger.error("\(error.localizedDescription)") + completionHandler(error) + } + } + + // MARK: - Utilities + + /// Create and send API HTTP request. + /// - Parameters: + /// - request: URLRequest, modified inside + /// - sign: Should we sign the data? + /// - Returns: AnyPublisher + private func request(_ request: URLRequest, sign: Bool = true) throws -> AnyPublisher { + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Request") + + // Check reachability + if (self.monitor.currentPath.status != .satisfied) { + logger.warning("Not reachable!") + throw APIError.error(reason: "Not reachable") + } + + // Modify request + var modifiedRequest: URLRequest = request + + // Headers + modifiedRequest.setValue("MobileUserAgent", forHTTPHeaderField: "User-Agent") + modifiedRequest.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type") + modifiedRequest.setValue("close", forHTTPHeaderField: "Connection") + modifiedRequest.setValue("gzip", forHTTPHeaderField: "Accept-Encoding") + + // Body + modifiedRequest.httpMethod = "POST" + let timeNow: UInt64 = UInt64(floor(NSDate().timeIntervalSince1970)) + var body: [String: Any] = [ + "RemoteMobileTimeKey": timeNow, + "TimeKey": (timeNow - 1), + "RequestId": UUID().uuidString, + "RemoteMobileAppVersion": "20.4.1.358", + "RemoteMobileAppName": "VULCAN-iOS-ModulUcznia" + ] + + // Merge request bodies + if let httpBody: Data = request.httpBody, + let oldRequestBody: [String: Any] = try? JSONSerialization.jsonObject(with: httpBody, options: []) as? [String: Any] { + body = body.merging(oldRequestBody) { (_, new) in new } + } + + let bodyData = try? JSONSerialization.data(withJSONObject: body) + modifiedRequest.httpBody = bodyData + + if sign { + let requestParametersData: NSData = NSData(data: bodyData ?? Data()) + + let password = "CE75EA598C7743AD9B0B7328DED85B06" + guard let certificate: String = self.keychain["CertificatePfx"], + let decodedCert: Data = Data(base64Encoded: certificate) else { + throw APIError.error(reason: "Error reading certificate") + } + + do { + let cert = try PKCS12(certificate: decodedCert, password: password) + if let dataSignature: String = cert.signData(data: requestParametersData) { + modifiedRequest.setValue(dataSignature, forHTTPHeaderField: "RequestSignatureValue") + modifiedRequest.setValue(self.keychain["CertificateKey"] ?? "", forHTTPHeaderField: "RequestCertificateKey") + } + } catch { + logger.error("Error importing certificate: \(error.localizedDescription)") + } + } + + // Send the request and pass it on + return URLSession.shared.dataTaskPublisher(for: modifiedRequest) + .mapError { $0 as Error } + .map { $0.data } + .eraseToAnyPublisher() + } + + /// Schedules a task for supplied event. + /// - Parameter event: Event to be notified about + public func addScheduleEventNotification(_ event: Vulcan.ScheduleEvent) { + let logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Notifications") + logger.debug("Registering a new notification of event with title \"\(event.subjectName, privacy: .sensitive)\".") + + guard let dateStarts = event.dateStarts else { + logger.debug("No `event.dateStarts`! Returning.") + return + } + + let content = UNMutableNotificationContent() + content.title = event.subjectName + + if let employeeName = event.employee?.name, + let employeeSurname = event.employee?.surname { + content.subtitle = "\(employeeName) \(employeeSurname)" + } else { + content.subtitle = "\(event.employeeID)" + } + + if let dateEnds = event.dateEnds { + content.body = "\(event.room) • \(dateStarts.formattedDateString(timeStyle: .short)) - \(dateEnds.formattedDateString(timeStyle: .short))" + } + + content.sound = UNNotificationSound.default + content.categoryIdentifier = "ScheduleNotification" + content.targetContentIdentifier = content.categoryIdentifier + content.threadIdentifier = content.categoryIdentifier + + let identifier: String = "\(content.categoryIdentifier):\(event.dateStarts?.timeIntervalSinceReferenceDate ?? event.date.timeIntervalSinceReferenceDate):\(event.group ?? -1):\(event.subjectID)" + + let triggerDate: DateComponents + let schedule = self.schedule + .flatMap(\.events) + .filter { $0.dateStarts ?? $0.date >= Date() } + .filter { $0.isUserSchedule } + + if let itemIndex = schedule.firstIndex(of: event), + (itemIndex - 1) >= 0, + let dateEnds = schedule[itemIndex - 1].dateEnds, + Calendar.autoupdatingCurrent.isDate(schedule[itemIndex - 1].date, inSameDayAs: event.date) { + triggerDate = Calendar.autoupdatingCurrent.dateComponents([.year, .month, .day, .hour, .minute], from: dateEnds) + } else { + let date: Date = Calendar.autoupdatingCurrent.date(byAdding: .minute, value: -5, to: dateStarts) ?? dateStarts + triggerDate = Calendar.autoupdatingCurrent.dateComponents([.year, .month, .day, .hour, .minute], from: date) + } + + let trigger: UNCalendarNotificationTrigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false) + let request: UNNotificationRequest = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) + + UNUserNotificationCenter.current().add(request) { error in + if let error = error { + logger.warning("Couldn't add a notification with ID \(identifier, privacy: .sensitive): \(error.localizedDescription)") + } + } + } + + /// Schedules a task for supplied event. + /// - Parameter task: Task to be notified about + /// - Parameter type: Type of exam + public func addTaskNotification(_ task: VulcanTask, isBigType: Bool? = nil) { + let logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Notifications") + logger.debug("Registering a new notification of task with entry \"\(task.entry, privacy: .sensitive)\".") + + let content = UNMutableNotificationContent() + + switch (task.tag) { + case .exam: + if let isBigType = isBigType { + content.title = "\(NSLocalizedString("Tomorrow", comment: "")): \(NSLocalizedString(isBigType ? "EXAM_BIG" : "EXAM_SMALL", comment: ""))" + } else { + content.title = "\(NSLocalizedString("Tomorrow", comment: "")): \(NSLocalizedString(task.tag.rawValue, comment: ""))" + } + case .homework: content.title = NSLocalizedString("TASK_TOMORROW : TAG_HOMEWORK", comment: "") + } + + if let subjectName = task.subject?.name { + content.subtitle = subjectName + } else { + content.subtitle = "\(task.subjectID)" + } + + + content.body = task.entry + content.sound = UNNotificationSound.default + content.categoryIdentifier = "TaskNotification" + content.targetContentIdentifier = content.categoryIdentifier + content.threadIdentifier = content.categoryIdentifier + + let date: Date + if let dayBefore: Date = Calendar.autoupdatingCurrent.date(byAdding: .day, value: -1, to: task.date), + let finalDate: Date = Calendar.autoupdatingCurrent.date(byAdding: .hour, value: 9, to: dayBefore) { + date = finalDate + } else { + date = task.date + } + + let triggerDate: DateComponents = Calendar.autoupdatingCurrent.dateComponents([.year, .month, .day, .hour, .minute], from: date) + let trigger: UNCalendarNotificationTrigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false) + let identifier: String = "\(content.categoryIdentifier):\(task.date.timeIntervalSinceReferenceDate):\(task.entry)" + let request: UNNotificationRequest = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) + + UNUserNotificationCenter.current().add(request) { error in + if let error = error { + logger.warning("Couldn't add a notification with ID \(identifier, privacy: .sensitive): \(error.localizedDescription)") + } + } + } +} diff --git a/Modules/Vulcan/Sources/Vulcan/VulcanStore.xcdatamodeld/Model.xcdatamodel/contents b/Modules/Vulcan/Sources/Vulcan/VulcanStore.xcdatamodeld/Model.xcdatamodel/contents new file mode 100644 index 0000000..e42e7a2 --- /dev/null +++ b/Modules/Vulcan/Sources/Vulcan/VulcanStore.xcdatamodeld/Model.xcdatamodel/contents @@ -0,0 +1,227 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Modules/Vulcan/Tests/LinuxMain.swift b/Modules/Vulcan/Tests/LinuxMain.swift new file mode 100644 index 0000000..785bc1c --- /dev/null +++ b/Modules/Vulcan/Tests/LinuxMain.swift @@ -0,0 +1,7 @@ +import XCTest + +import VulcanTests + +var tests = [XCTestCaseEntry]() +tests += VulcanTests.allTests() +XCTMain(tests) diff --git a/Modules/Vulcan/Tests/VulcanTests/VulcanTests.swift b/Modules/Vulcan/Tests/VulcanTests/VulcanTests.swift new file mode 100644 index 0000000..4922263 --- /dev/null +++ b/Modules/Vulcan/Tests/VulcanTests/VulcanTests.swift @@ -0,0 +1,15 @@ +import XCTest +@testable import Vulcan + +final class VulcanTests: XCTestCase { + func testExample() { + // This is an example of a functional test case. + // Use XCTAssert and related functions to verify your tests produce the correct + // results. + XCTAssertEqual(Vulcan().text, "Hello, World!") + } + + static var allTests = [ + ("testExample", testExample), + ] +} diff --git a/Modules/Vulcan/Tests/VulcanTests/XCTestManifests.swift b/Modules/Vulcan/Tests/VulcanTests/XCTestManifests.swift new file mode 100644 index 0000000..73b895b --- /dev/null +++ b/Modules/Vulcan/Tests/VulcanTests/XCTestManifests.swift @@ -0,0 +1,9 @@ +import XCTest + +#if !canImport(ObjectiveC) +public func allTests() -> [XCTestCaseEntry] { + return [ + testCase(VulcanTests.allTests), + ] +} +#endif diff --git a/README.md b/README.md new file mode 100644 index 0000000..7f47375 --- /dev/null +++ b/README.md @@ -0,0 +1,48 @@ +

+vulcan Logo
+

vulcan

+

Open-source UONET+ app for Apple devices.

+

+ +## Installation +Compile using Xcode, sideload .ipa from [releases](https://github.com/rrroyal/vulcan/releases) or [register for TestFlight](https://form.typeform.com/to/Mqh3AvAx). + +## Functionality +### UONET+ +- [x] Grades +- [x] Schedule +- [x] Tasks +- [x] Messages +- [x] Notes +- [ ] QR code logging in +- [ ] Message attachements + +### Core +- [x] iOS app +- [x] iPadOS app +- [x] watchOS app (kinda) +- [ ] macOS app +- [x] Widgets +- [x] Siri shortcuts/intents +- [x] Notifications - [**read below**](#what-about-notifications) + +## FAQ +### Why the app isn't in the App Store? +Uploading apps on the App Store requires being a member of the [Apple Developer Program](https://developer.apple.com/programs/), which costs 99$ per year. If someone is generous enough to pay for that, I'm more than happy to upload the app to the App Store. + +### What about notifications? +App will remind you about your next lessons or tasks. Unfortunately, as of right now I'm unable to add real-time notifications about new messages, grades etc. + +## Technical stuff +- There's no analytics, ads, weird libraries or other bullshit. +- The app is built with [SwiftUI](https://developer.apple.com/xcode/swiftui/), [Combine](https://developer.apple.com/documentation/combine) and CoreData. The interface may sometimes be glitchy - please report every bug you've encountered to me! +- API is based on [uonet-api-docs](https://gitlab.com/erupcja/uonet-api-docs) and my own analysis. App will be migrating to the new API soon, providing further functionality (lucky number, etc). + +## Credits +- [kishikawakatsumi/KeychainAccess](https://github.com/kishikawakatsumi/KeychainAccess) +- [erupcja/uonet-api-docs](https://gitlab.com/erupcja/uonet-api-docs) + +## License +[GPL v3.0](LICENSE) + +[![Build Status](https://app.bitrise.io/app/96fcd2c4966a42d2/status.svg?token=tyQy2iKlWi_0yMeQtq2X7g&branch=main)](https://app.bitrise.io/app/96fcd2c4966a42d2) \ No newline at end of file diff --git a/Shared/Assets.xcassets/AccentColor.colorset/Contents.json b/Shared/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000..fa4df1c --- /dev/null +++ b/Shared/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.252", + "green" : "0.307", + "red" : "0.921" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.249", + "green" : "0.339", + "red" : "0.923" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.140", + "green" : "0.202", + "red" : "0.790" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.339", + "green" : "0.364", + "red" : "0.924" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/Contents.json b/Shared/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..13e9f6c --- /dev/null +++ b/Shared/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,182 @@ +{ + "images" : [ + { + "filename" : "icon_20pt@2x.png", + "idiom" : "iphone", + "scale" : "2x", + "size" : "20x20" + }, + { + "filename" : "icon_20pt@3x.png", + "idiom" : "iphone", + "scale" : "3x", + "size" : "20x20" + }, + { + "filename" : "icon_29pt.png", + "idiom" : "iphone", + "scale" : "1x", + "size" : "29x29" + }, + { + "filename" : "icon_29pt@2x.png", + "idiom" : "iphone", + "scale" : "2x", + "size" : "29x29" + }, + { + "filename" : "icon_29pt@3x.png", + "idiom" : "iphone", + "scale" : "3x", + "size" : "29x29" + }, + { + "filename" : "icon_40pt@2x.png", + "idiom" : "iphone", + "scale" : "2x", + "size" : "40x40" + }, + { + "filename" : "icon_60pt@2x.png", + "idiom" : "iphone", + "scale" : "3x", + "size" : "40x40" + }, + { + "filename" : "icon_60pt@2x.png", + "idiom" : "iphone", + "scale" : "2x", + "size" : "60x60" + }, + { + "filename" : "icon_60pt@3x.png", + "idiom" : "iphone", + "scale" : "3x", + "size" : "60x60" + }, + { + "filename" : "icon_20pt.png", + "idiom" : "ipad", + "scale" : "1x", + "size" : "20x20" + }, + { + "filename" : "icon_20pt@2x.png", + "idiom" : "ipad", + "scale" : "2x", + "size" : "20x20" + }, + { + "filename" : "icon_29pt.png", + "idiom" : "ipad", + "scale" : "1x", + "size" : "29x29" + }, + { + "filename" : "icon_29pt@2x.png", + "idiom" : "ipad", + "scale" : "2x", + "size" : "29x29" + }, + { + "filename" : "icon_20pt@2x.png", + "idiom" : "ipad", + "scale" : "1x", + "size" : "40x40" + }, + { + "filename" : "icon_40pt@2x.png", + "idiom" : "ipad", + "scale" : "2x", + "size" : "40x40" + }, + { + "filename" : "icon_76pt.png", + "idiom" : "ipad", + "scale" : "1x", + "size" : "76x76" + }, + { + "filename" : "icon_76pt@2x.png", + "idiom" : "ipad", + "scale" : "2x", + "size" : "76x76" + }, + { + "filename" : "icon_83.5@2x.png", + "idiom" : "ipad", + "scale" : "2x", + "size" : "83.5x83.5" + }, + { + "filename" : "Icon.png", + "idiom" : "ios-marketing", + "scale" : "1x", + "size" : "1024x1024" + }, + { + "filename" : "Icon-mac_16pt.png", + "idiom" : "mac", + "scale" : "1x", + "size" : "16x16" + }, + { + "filename" : "Icon-mac_16pt@2x.png", + "idiom" : "mac", + "scale" : "2x", + "size" : "16x16" + }, + { + "filename" : "Icon-mac_16pt@2x.png", + "idiom" : "mac", + "scale" : "1x", + "size" : "32x32" + }, + { + "filename" : "Icon-mac_32pt@2x.png", + "idiom" : "mac", + "scale" : "2x", + "size" : "32x32" + }, + { + "filename" : "Icon-mac_128pt.png", + "idiom" : "mac", + "scale" : "1x", + "size" : "128x128" + }, + { + "filename" : "Icon-mac_128pt@2x.png", + "idiom" : "mac", + "scale" : "2x", + "size" : "128x128" + }, + { + "filename" : "Icon-mac_128pt@2x.png", + "idiom" : "mac", + "scale" : "1x", + "size" : "256x256" + }, + { + "filename" : "Icon-mac_256pt@2x.png", + "idiom" : "mac", + "scale" : "2x", + "size" : "256x256" + }, + { + "filename" : "Icon-mac_256pt@2x.png", + "idiom" : "mac", + "scale" : "1x", + "size" : "512x512" + }, + { + "filename" : "Icon-mac_1024pt.png", + "idiom" : "mac", + "scale" : "2x", + "size" : "512x512" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_1024pt.png b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_1024pt.png new file mode 100644 index 0000000..dcea441 Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_1024pt.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_128pt.png b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_128pt.png new file mode 100644 index 0000000..9953de2 Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_128pt.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_128pt@2x.png b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_128pt@2x.png new file mode 100644 index 0000000..c29f65d Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_128pt@2x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_16pt.png b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_16pt.png new file mode 100644 index 0000000..ff21eaa Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_16pt.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_16pt@2x.png b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_16pt@2x.png new file mode 100644 index 0000000..bf2f259 Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_16pt@2x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_256pt@2x.png b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_256pt@2x.png new file mode 100644 index 0000000..37f9cfc Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_256pt@2x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_32pt@2x.png b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_32pt@2x.png new file mode 100644 index 0000000..36081b3 Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/Icon-mac_32pt@2x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/Icon.png b/Shared/Assets.xcassets/AppIcon.appiconset/Icon.png new file mode 100644 index 0000000..b8129b8 Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/Icon.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_20pt.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_20pt.png new file mode 100644 index 0000000..d01bf3c Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_20pt.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png new file mode 100644 index 0000000..bae4527 Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_20pt@2x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png new file mode 100644 index 0000000..5b21dcf Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_20pt@3x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_29pt.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_29pt.png new file mode 100644 index 0000000..fb203c5 Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_29pt.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png new file mode 100644 index 0000000..701c912 Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_29pt@2x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png new file mode 100644 index 0000000..4eedee5 Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_29pt@3x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png new file mode 100644 index 0000000..d006681 Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_40pt@2x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png new file mode 100644 index 0000000..29aa1a5 Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_60pt@2x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png new file mode 100644 index 0000000..704e35a Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_60pt@3x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_76pt.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_76pt.png new file mode 100644 index 0000000..f1a399e Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_76pt.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png new file mode 100644 index 0000000..4f2fe7b Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_76pt@2x.png differ diff --git a/Shared/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png b/Shared/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png new file mode 100644 index 0000000..c4ff70e Binary files /dev/null and b/Shared/Assets.xcassets/AppIcon.appiconset/icon_83.5@2x.png differ diff --git a/Shared/Assets.xcassets/Contents.json b/Shared/Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/Shared/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Assets.xcassets/vulcan.imageset/Contents.json b/Shared/Assets.xcassets/vulcan.imageset/Contents.json new file mode 100644 index 0000000..f10c6fa --- /dev/null +++ b/Shared/Assets.xcassets/vulcan.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "filename" : "Vulcan.png", + "idiom" : "universal", + "scale" : "1x" + }, + { + "filename" : "Vulcan@2x.png", + "idiom" : "universal", + "scale" : "2x" + }, + { + "filename" : "Vulcan@3x.png", + "idiom" : "universal", + "scale" : "3x" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Assets.xcassets/vulcan.imageset/Vulcan.png b/Shared/Assets.xcassets/vulcan.imageset/Vulcan.png new file mode 100644 index 0000000..5893d15 Binary files /dev/null and b/Shared/Assets.xcassets/vulcan.imageset/Vulcan.png differ diff --git a/Shared/Assets.xcassets/vulcan.imageset/Vulcan@2x.png b/Shared/Assets.xcassets/vulcan.imageset/Vulcan@2x.png new file mode 100644 index 0000000..043f1e1 Binary files /dev/null and b/Shared/Assets.xcassets/vulcan.imageset/Vulcan@2x.png differ diff --git a/Shared/Assets.xcassets/vulcan.imageset/Vulcan@3x.png b/Shared/Assets.xcassets/vulcan.imageset/Vulcan@3x.png new file mode 100644 index 0000000..4a0e047 Binary files /dev/null and b/Shared/Assets.xcassets/vulcan.imageset/Vulcan@3x.png differ diff --git a/Shared/Colors.xcassets/ColorSchemes/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Contents.json new file mode 100644 index 0000000..6e96565 --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Default/0.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Default/0.colorset/Contents.json new file mode 100644 index 0000000..d3e2fea --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Default/0.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.574", + "green" : "0.557", + "red" : "0.557" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.574", + "green" : "0.557", + "red" : "0.557" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.439", + "green" : "0.424", + "red" : "0.424" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.697", + "green" : "0.681", + "red" : "0.681" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Default/1.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Default/1.colorset/Contents.json new file mode 100644 index 0000000..ee6349e --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Default/1.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.240", + "green" : "0.305", + "red" : "0.920" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.272", + "green" : "0.332", + "red" : "0.921" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.145", + "green" : "0.163", + "red" : "0.774" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.403", + "green" : "0.449", + "red" : "0.928" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Default/2.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Default/2.colorset/Contents.json new file mode 100644 index 0000000..5d50f38 --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Default/2.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.218", + "green" : "0.604", + "red" : "0.942" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.235", + "green" : "0.639", + "red" : "0.945" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.116", + "green" : "0.256", + "red" : "0.725" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.344", + "green" : "0.715", + "red" : "0.955" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Default/3.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Default/3.colorset/Contents.json new file mode 100644 index 0000000..9c7fa73 --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Default/3.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.275", + "green" : "0.808", + "red" : "0.968" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.291", + "green" : "0.845", + "red" : "0.973" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.121", + "green" : "0.368", + "red" : "0.591" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.319", + "green" : "0.838", + "red" : "0.972" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Default/4.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Default/4.colorset/Contents.json new file mode 100644 index 0000000..22ace74 --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Default/4.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.960", + "green" : "0.775", + "red" : "0.470" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.982", + "green" : "0.814", + "red" : "0.505" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.626", + "green" : "0.437", + "red" : "0.191" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.983", + "green" : "0.831", + "red" : "0.540" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Default/5.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Default/5.colorset/Contents.json new file mode 100644 index 0000000..550588b --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Default/5.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.966", + "green" : "0.471", + "red" : "0.211" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.967", + "green" : "0.510", + "red" : "0.232" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.833", + "green" : "0.249", + "red" : "0.104" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.971", + "green" : "0.605", + "red" : "0.353" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Default/6.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Default/6.colorset/Contents.json new file mode 100644 index 0000000..9e833b7 --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Default/6.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.809", + "green" : "0.336", + "red" : "0.343" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.869", + "green" : "0.361", + "red" : "0.368" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.616", + "green" : "0.204", + "red" : "0.211" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.968", + "green" : "0.478", + "red" : "0.488" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Default/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Default/Contents.json new file mode 100644 index 0000000..6e96565 --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Default/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/0.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/0.colorset/Contents.json new file mode 100644 index 0000000..d3e2fea --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/0.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.574", + "green" : "0.557", + "red" : "0.557" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.574", + "green" : "0.557", + "red" : "0.557" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.439", + "green" : "0.424", + "red" : "0.424" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.697", + "green" : "0.681", + "red" : "0.681" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/1.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/1.colorset/Contents.json new file mode 100644 index 0000000..ee6349e --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/1.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.240", + "green" : "0.305", + "red" : "0.920" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.272", + "green" : "0.332", + "red" : "0.921" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.145", + "green" : "0.163", + "red" : "0.774" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.403", + "green" : "0.449", + "red" : "0.928" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/2.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/2.colorset/Contents.json new file mode 100644 index 0000000..ea2cbae --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/2.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.841", + "green" : "0.343", + "red" : "0.642" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.919", + "green" : "0.375", + "red" : "0.700" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.648", + "green" : "0.281", + "red" : "0.503" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.974", + "green" : "0.573", + "red" : "0.814" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/3.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/3.colorset/Contents.json new file mode 100644 index 0000000..9c7fa73 --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/3.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.275", + "green" : "0.808", + "red" : "0.968" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.291", + "green" : "0.845", + "red" : "0.973" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.121", + "green" : "0.368", + "red" : "0.591" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.319", + "green" : "0.838", + "red" : "0.972" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/4.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/4.colorset/Contents.json new file mode 100644 index 0000000..550588b --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/4.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.966", + "green" : "0.471", + "red" : "0.211" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.967", + "green" : "0.510", + "red" : "0.232" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.833", + "green" : "0.249", + "red" : "0.104" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.971", + "green" : "0.605", + "red" : "0.353" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/5.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/5.colorset/Contents.json new file mode 100644 index 0000000..6efb90f --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/5.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.402", + "green" : "0.771", + "red" : "0.396" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.405", + "green" : "0.809", + "red" : "0.408" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.274", + "green" : "0.534", + "red" : "0.271" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.419", + "green" : "0.848", + "red" : "0.425" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/6.colorset/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/6.colorset/Contents.json new file mode 100644 index 0000000..3df6a5f --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/6.colorset/Contents.json @@ -0,0 +1,78 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.435", + "green" : "0.958", + "red" : "0.767" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.499", + "green" : "0.994", + "red" : "0.839" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.356", + "green" : "0.860", + "red" : "0.638" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + }, + { + "appearance" : "contrast", + "value" : "high" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.477", + "green" : "0.995", + "red" : "0.878" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/Contents.json b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/Contents.json new file mode 100644 index 0000000..6e96565 --- /dev/null +++ b/Shared/Colors.xcassets/ColorSchemes/Dzienniczek+/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/Shared/Colors.xcassets/Contents.json b/Shared/Colors.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/Shared/Colors.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Shared/Data/AppDelegate.swift b/Shared/Data/AppDelegate.swift new file mode 100644 index 0000000..07ea9c4 --- /dev/null +++ b/Shared/Data/AppDelegate.swift @@ -0,0 +1,155 @@ +// +// AppDelegate.swift +// vulcan +// +// Created by royal on 25/06/2020. +// + +#if canImport(UIKit) +import UIKit +#endif + +import Combine +import BackgroundTasks +import os +import Vulcan +import WidgetKit + +class AppDelegate: NSObject, UIApplicationDelegate { + // MARK: - App Lifecycle + private let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "AppDelegate") + + private var cancellableSet: [AnyCancellable] = [] + + /// Called when app is launched + func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil) -> Bool { + // WatchConnectivity session + WatchSessionManager.shared.startSession() + + // Networking + AppState.networking.monitor.start(queue: .global()) + + // UserNotifications + let notifications: Notifications = Notifications.shared + notifications.notificationCenter.delegate = notifications + + // Background fetch + BGTaskScheduler.shared.register(forTaskWithIdentifier: "dev.niepostek.vulcan.refreshData", using: nil) { (task) in + self.handleAppRefresh(task) + } + + // Listeners + Vulcan.shared.$currentUser + .sink { user in + let watchData: [String: Any] = [ + "type": "Vulcan", + "data": [ + "currentUser": try? JSONEncoder().encode(user) + ] + ] + + try? WatchSessionManager.shared.sendData(watchData) + } + .store(in: &cancellableSet) + + Vulcan.shared.scheduleDidChange + .sink { isPersistent in + if !isPersistent { + return + } + + // Widgets + WidgetCenter.shared.reloadTimelines(ofKind: "NextUpWidget") + WidgetCenter.shared.reloadTimelines(ofKind: "NowWidget") + + // Watch + let watchData: [String: Any] = [ + "type": "Vulcan", + "data": [ + "schedule": try? JSONEncoder().encode(Vulcan.shared.schedule) + ] + ] + + try? WatchSessionManager.shared.sendData(watchData) + } + .store(in: &cancellableSet) + + return true + } + + /// Registered for APNs + func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { + let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() + logger.info("Successfuly registered for APNs. Device token: \(token, privacy: .private).") + } + + /// Failed to register for APNs + func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { + logger.warning("Failed to register for APNs: \(error.localizedDescription)") + } + + // MARK: - Helper functions + + /// Sets the currently visible shortcuts + /// - Parameter visible: Should shortcuts be visible? + public func setShortcuts(visible: Bool) { + if visible { + let shortcutGradesItem = UIApplicationShortcutItem(type: "shortcutGrades", localizedTitle: "Grades".localized, localizedSubtitle: nil, icon: UIApplicationShortcutIcon(systemImageName: "rosette"), userInfo: nil) + let shortcutScheduleItem = UIApplicationShortcutItem(type: "shortcutSchedule", localizedTitle: "Schedule".localized, localizedSubtitle: nil, icon: UIApplicationShortcutIcon(systemImageName: "calendar"), userInfo: nil) + let shortcutTasksItem = UIApplicationShortcutItem(type: "shortcutTasks", localizedTitle: "Tasks".localized, localizedSubtitle: nil, icon: UIApplicationShortcutIcon(systemImageName: "doc.on.clipboard.fill"), userInfo: nil) + let shortcutMessagesItem = UIApplicationShortcutItem(type: "shortcutMessages", localizedTitle: "Messages".localized, localizedSubtitle: nil, icon: UIApplicationShortcutIcon(systemImageName: "text.bubble.fill"), userInfo: nil) + UIApplication.shared.shortcutItems = [shortcutGradesItem, shortcutScheduleItem, shortcutTasksItem, shortcutMessagesItem] + } else { + UIApplication.shared.shortcutItems = [] + } + } + + // MARK: - Background refresh + /// Schedules a background refresh task + public func scheduleBackgroundRefresh() { + logger.debug("Scheduling app refresh.") + do { + let request = BGAppRefreshTaskRequest(identifier: "dev.niepostek.vulcan.refreshData") + request.earliestBeginDate = Date(timeIntervalSinceNow: 60 * 60) + try BGTaskScheduler.shared.submit(request) + } catch { + logger.warning("Error scheduling: \(error.localizedDescription)") + } + } + + /// Executed when app is launched by background refresh. + /// - Parameter task: Task to execute + func handleAppRefresh(_ task: BGTask) { + if (!UserDefaults.group.bool(forKey: UserDefaults.AppKeys.isLoggedIn.rawValue)) { + task.setTaskCompleted(success: true) + return + } + + logger.notice("Refreshing in the background...") + + let queue = OperationQueue() + queue.maxConcurrentOperationCount = 6 + queue.addOperation { Vulcan.shared.getGrades() } + + if let startOfWeek: Date = Date().startOfWeek, + let endOfWeek: Date = Date().endOfWeek { + queue.addOperation { Vulcan.shared.getSchedule(isPersistent: true, from: startOfWeek, to: endOfWeek) } + } + + queue.addOperation { Vulcan.shared.getTasks(isPersistent: true, from: Date().startOfMonth, to: Date().startOfMonth) } + queue.addOperation { Vulcan.shared.getMessages(tag: .received, isPersistent: true, from: Date().startOfMonth, to: Date().endOfMonth) } + queue.addOperation { Vulcan.shared.getEndOfTermGrades() } + + task.expirationHandler = { + self.logger.warning("Refresh expired!") + queue.cancelAllOperations() + } + + let lastOperation = queue.operations.last + lastOperation?.completionBlock = { + task.setTaskCompleted(success: !(lastOperation?.isCancelled ?? false)) + } + + self.scheduleBackgroundRefresh() + } +} diff --git a/Shared/Data/AppState.swift b/Shared/Data/AppState.swift new file mode 100644 index 0000000..68570f8 --- /dev/null +++ b/Shared/Data/AppState.swift @@ -0,0 +1,92 @@ +// +// AppState.swift +// vulcan +// +// Created by royal on 24/06/2020. +// + +import SwiftUI +import Combine +import Network +import BackgroundTasks +import NotificationCenter +import os + +final class AppState: ObservableObject { + static public var shared: AppState = AppState() + static public var networking: AppState.Networking = AppState.Networking() + + private let logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).AppState", category: "AppState") + + private init() { + logger.debug("Initialized") + AppState.networking.monitor.start(queue: .global(qos: .background)) + + NotificationCenter.default.addObserver(self, selector: #selector(powerStateChanged), name: .NSProcessInfoPowerStateDidChange, object: nil) + } + + // MARK: - Networking + /// Networking + public class Networking { + private var launchedBefore: Bool = false + + fileprivate init() { + // self.monitor.start(queue: .global()) + self.monitor.pathUpdateHandler = { (path) in + // Publish + self.notificationPublisher.send(path.status == .satisfied) + + if (self.monitor.queue == nil || !self.launchedBefore) { + return + } + + // Check if connection is reachable + /* if (path.status == .satisfied) { + // Yes - send a notification about it + let notificationData: NotificationData = NotificationData( + autodismisses: true, + dismissable: true, + style: .normal, + icon: "wifi", + title: "CONNECTION_AVAILABLE_TITLE", + subtitle: "CONNECTION_AVAILABLE_SUBTITLE", + expandedText: nil + ) + AppState.notifications.sendNotification(notificationData) + } else { + // No - send a notification about it + let notificationData: NotificationData = NotificationData( + autodismisses: true, + dismissable: true, + style: .normal, + icon: "wifi.slash", + title: "NO_CONNECTION_TITLE", + subtitle: "NO_CONNECTION_SUBTITLE", + expandedText: nil + ) + AppState.notifications.sendNotification(notificationData) + } */ + } + } + + public var notificationPublisher = PassthroughSubject() + public let monitor: NWPathMonitor = NWPathMonitor() + public var isReachable: Bool? { + get { + if (self.monitor.queue == nil) { + return nil + } + + return monitor.currentPath.status == .satisfied + } + } + } + + // MARK: Other + @Published public var isLowPowerModeEnabled: Bool = ProcessInfo.processInfo.isLowPowerModeEnabled + @objc func powerStateChanged(_ notification: Notification) { + DispatchQueue.main.async { + self.isLowPowerModeEnabled = ProcessInfo.processInfo.isLowPowerModeEnabled + } + } +} diff --git a/Shared/Data/Notifications.swift b/Shared/Data/Notifications.swift new file mode 100644 index 0000000..062f9cf --- /dev/null +++ b/Shared/Data/Notifications.swift @@ -0,0 +1,51 @@ +// +// Notifications.swift +// vulcan +// +// Created by royal on 09/07/2020. +// + +import UIKit +import Foundation +import UserNotifications +import os + +final class Notifications: NSObject, UNUserNotificationCenterDelegate { + public static var shared: Notifications = Notifications() + public var notificationCenter: UNUserNotificationCenter = UNUserNotificationCenter.current() + + public let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Vulcan", category: "Notifications") + + private override init() { + super.init() + } + + // MARK: - Delegate functions + + func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { + completionHandler([.banner]) + } + + func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { + completionHandler() + } + + // MARK: - Helper functions + + /// Requests the authorization for notifications. + func requestAuthorization() { + let options: UNAuthorizationOptions = [.alert, .sound, .badge, .announcement] + + notificationCenter.requestAuthorization(options: options) { (allowed, error) in + if !allowed { + self.logger.warning("User declined the authorization prompt. Error: \(error?.localizedDescription ?? "none")") + return + } + + DispatchQueue.main.async { + self.logger.debug("Registering for APNs.") + UIApplication.shared.registerForRemoteNotifications() + } + } + } +} diff --git a/Shared/Data/SettingsModel.swift b/Shared/Data/SettingsModel.swift new file mode 100644 index 0000000..d7b4848 --- /dev/null +++ b/Shared/Data/SettingsModel.swift @@ -0,0 +1,88 @@ +// +// SettingsModel.swift +// vulcan +// +// Created by royal on 15/03/2020. +// + +import SwiftUI +import Foundation +import Combine +import os +import Vulcan + +/// Model containing user settings data +final class SettingsModel: ObservableObject { + static public let shared: SettingsModel = SettingsModel() + + // MARK: App data + @AppStorage(UserDefaults.AppKeys.launchedBefore.rawValue, store: .group) public var launchedBefore: Bool = false + @AppStorage(UserDefaults.AppKeys.isLoggedIn.rawValue, store: .group) public var isLoggedIn: Bool = false + + // MARK: User + @AppStorage(UserDefaults.AppKeys.showAllScheduleEvents.rawValue, store: .group) public var showAllScheduleEvents: Bool = false + @AppStorage(UserDefaults.AppKeys.readMessageOnOpen.rawValue, store: .group) public var readMessageOnOpen: Bool = true + + // MARK: Notifications + @AppStorage(UserDefaults.AppKeys.enableScheduleNotifications.rawValue, store: .group) public var enableScheduleNotifications: Bool = false + @AppStorage(UserDefaults.AppKeys.enableTaskNotifications.rawValue, store: .group) public var enableTaskNotifications: Bool = false + + // MARK: Interface + @AppStorage(UserDefaults.AppKeys.filterSchedule.rawValue, store: .group) public var filterSchedule: Bool = false + @AppStorage(UserDefaults.AppKeys.colorizeGrades.rawValue, store: .group) public var colorizeGrades: Bool = true + @AppStorage(UserDefaults.AppKeys.colorScheme.rawValue, store: .group) public var colorScheme: String = "Default" + @AppStorage(UserDefaults.AppKeys.hapticFeedback.rawValue, store: .group) public var hapticFeedback: Bool = true + + @Published public var updatesAvailable: Bool = false + private var cancellableSet: Set = [] + private let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Settings", category: "Settings") + + // MARK: - init + private init() { + // self.checkForUpdates() + } + + // MARK: - Public functions + /// Resets the app' UserDefaults + public func resetSettings() { + logger.info("Resetting settings...") + UserDefaults.standard.removePersistentDomain(forName: Bundle.main.groupIdentifier) + Vulcan.shared.logOut() + logger.info("Done resetting!") + } + + /// Fetches the newest release on GitHub. + /* public func checkForUpdates() { + let currentVersion: String = Bundle.main.buildVersion + let repoURL: URL = URL(string: "https://api.github.com/repos/rrroyal/vulcan/releases/latest")! + + var request: URLRequest = URLRequest(url: repoURL) + request.httpMethod = "GET" + + // Check latest release + logger.info("Checking latest release on GitHub (Local version: \(currentVersion))...") + URLSession.shared.dataTaskPublisher(for: request) + .receive(on: DispatchQueue.main) + .mapError { $0 as Error } + .map { $0.data } + .sink(receiveCompletion:{ (completion) in + switch (completion) { + case .failure: self.logger.error("(Settings) Completion error: \(String(describing: completion))"); break + case .finished: break + } + }, receiveValue: { (data) in + do { + let json: JSON = try JSON(data: data) + if (json["tag_name"].stringValue.dropFirst() > currentVersion && !json["draft"].boolValue && json["target_commitish"].stringValue == "master") { + self.logger.notice("New release available: \(json["tag_name"]).") + self.updatesAvailable = true + } else { + self.logger.info("Already on latest version.") + } + } catch { + self.logger.error("Error serializing JSON: \(error.localizedDescription)") + } + }) + .store(in: &cancellableSet) + } */ +} diff --git a/Shared/Data/WatchSessionManager.swift b/Shared/Data/WatchSessionManager.swift new file mode 100644 index 0000000..eb17589 --- /dev/null +++ b/Shared/Data/WatchSessionManager.swift @@ -0,0 +1,263 @@ +// +// WatchSessionManager.swift +// WatchKit Extension +// +// Created by royal on 08/09/2020. +// + +import Foundation +import os +import WatchConnectivity +import Vulcan + +@available (iOS 14, watchOS 7, *) +public final class WatchSessionManager: NSObject, WCSessionDelegate { + static public let shared = WatchSessionManager() + public let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).WatchConnectivity", category: "WatchConnectivity") + public let ud: UserDefaults = UserDefaults.group + + private override init() { + super.init() + } + + #if os(iOS) + var initData: [String: Any] { + get { + [ + "type": "UserDefaults", + "data": [ + UserDefaults.AppKeys.isLoggedIn.rawValue: ud.bool(forKey: UserDefaults.AppKeys.isLoggedIn.rawValue), + UserDefaults.AppKeys.colorScheme.rawValue: ud.string(forKey: UserDefaults.AppKeys.colorScheme.rawValue) ?? "Default", + UserDefaults.AppKeys.colorizeGrades.rawValue: ud.bool(forKey: UserDefaults.AppKeys.colorizeGrades.rawValue), + ] + ] + } + } + #endif + + // MARK: - Delegate functions + + /// Current session + public let session: WCSession? = WCSession.isSupported() ? WCSession.default : nil + + /// Valid session + public var validSession: WCSession? { + // paired - the user has to have their device paired to the watch + // watchAppInstalled - the user must have your watch app installed + + #if os(iOS) + if let session = session, session.isPaired && session.isWatchAppInstalled { + return session + } + #elseif os(watchOS) + if let session = session { + return session + } + #endif + return nil + } + + /// Starts the WCSession + public func startSession() { + session?.delegate = self + session?.activate() + } + + /// Called after session is started + /// - Parameters: + /// - session: Current session + /// - activationState: Session' activation state + /// - error: Error + public func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { + self.logger.info("Session started.") + + #if os(iOS) + do { + try self.sendData(initData) + try self.updateApplicationContext(schedule: Vulcan.shared.schedule, grades: Vulcan.shared.grades, eotGrades: Vulcan.shared.eotGrades, tasks: Vulcan.shared.tasks, receivedMessages: Vulcan.shared.messages[.received] ?? []) + } catch { + self.logger.error("Error sending UserDefaults! Error: \(error.localizedDescription)") + } + #endif + } + + /// Called when the app received a message from the counterpart + /// - Parameters: + /// - session: Current session + /// - message: Received message + /// - replyHandler: Code to run on a reply + public func session(_ session: WCSession, didReceiveMessage message: [String: Any], replyHandler: @escaping ([String: Any]) -> Void) { + // Handle the request + self.logger.info("Received a message!") + replyHandler(["receivedData": true]) + + // Prevent loop + if (message["receivedData"] as? Bool ?? false == true) { + return + } + + // Handle message + self.handleMessage(message) + } + + /// Called when the app received an applicationContext from the counterpart + /// - Parameters: + /// - session: Current session + /// - applicationContext: Received context + public func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String: Any]) { + if (applicationContext["receivedData"] as? Bool ?? false == true) { + return + } + + handleMessage(applicationContext) + } + + // MARK: - Helper functions + + /// Send the data to the Watch counterpart. + /// - Parameter data: Data to send + /// - Throws: Error + public func sendData(_ data: [String: Any]) throws { + if let session = validSession { + self.logger.info("Sending data...") + + do { + if session.isReachable { + self.logger.info("Sending message! Reachable: \(session.isReachable).") + session.sendMessage(data, replyHandler: { (reply) in + self.logger.info("Reply: \(reply)") + if (reply["receivedData"] as? Bool ?? true == true) { + return + } + }, errorHandler: { (error) in + self.logger.error("Error sending a message: \(error.localizedDescription).") + }) + } else { + self.logger.warning("Session not reachable!") + } + } + + self.logger.info("Done sending data!") + } else { + self.logger.warning("No session!") + } + } + + /// Updates application context + /// - Parameters: + /// - schedule: `[Vulcan.Schedule]` + /// - grades: `[Vulcan.SubjectGrades]` + /// - eotGrades: `[Vulcan.EndOfTermGrade]` + /// - tasks: `Vulcan.Tasks` + /// - receivedMessages: `[Vulcan.Message]` + /// - Throws: Error + public func updateApplicationContext(schedule: [Vulcan.Schedule], grades: [Vulcan.SubjectGrades], eotGrades: [Vulcan.EndOfTermGrade], tasks: Vulcan.Tasks = Vulcan.Tasks(exams: [], homework: []), receivedMessages: [Vulcan.Message]) throws { + self.logger.info("Updating application context...") + + let encoder: JSONEncoder = JSONEncoder() + let data: [String: Any] = [ + "type": "Vulcan", + "data": [ + "schedule": try encoder.encode(schedule), + "grades": try encoder.encode(grades), + "eotGrades": try encoder.encode(eotGrades), + "tasks": try encoder.encode(tasks), + "receivedMessages": try encoder.encode(receivedMessages) + ] + ] + + try self.sendData(data) + } + + /// Handles the received message. + /// - Parameter message: Received message + public func handleMessage(_ message: [String: Any]) { + guard let type: String = message["type"] as? String else { + self.logger.warning("Unknown message: \(message)") + return + } + + switch type { + #if os(iOS) + // Request + case "Request": + if let requestedData = message["requestedData"] as? String, + requestedData == "initData" { + try? self.sendData(initData) + } + #endif + + #if os(watchOS) + // UserDefaults + case "UserDefaults": + if let data = message["data"] as? [String: Any] { + for (key, value) in data { + logger.debug("Setting \"\(key, privacy: .sensitive)\" to \"\(String(describing: value), privacy: .sensitive)\"!") + ud.setValue(value, forKey: key) + } + } + + // Vulcan + case "Vulcan": + guard let data = message["data"] as? [String: Any] else { + return + } + + // Current user + if let data = data["currentUser"] as? Data, + let user = try? JSONDecoder().decode(Vulcan.Student.self, from: data) { + VulcanStore.shared.setUser(user) + } + + // Schedule + if let data = data["schedule"] as? Data, + let schedule = try? JSONDecoder().decode([Vulcan.Schedule].self, from: data) { + VulcanStore.shared.setSchedule(schedule) + } + + // Grades + if let data = data["grades"] as? Data, + let grades = try? JSONDecoder().decode([Vulcan.SubjectGrades].self, from: data) { + VulcanStore.shared.setGrades(grades) + } + + // EOT Grades + if let data = data["eotGrades"] as? Data, + let eotGrades = try? JSONDecoder().decode([Vulcan.EndOfTermGrade].self, from: data) { + VulcanStore.shared.setEOTGrades(eotGrades) + } + + // Tasks + if let data = data["tasks"] as? Data, + let tasks = try? JSONDecoder().decode(Vulcan.Tasks.self, from: data) { + VulcanStore.shared.setTasks(tasks) + } + + // Received Messages + if let data = data["receivedMessages"] as? Data, + let messages = try? JSONDecoder().decode([Vulcan.Message].self, from: data) { + VulcanStore.shared.setMessages(messages, tag: .received) + } + #endif + + // Default + default: break + } + } +} + +#if os(iOS) +public extension WatchSessionManager { + /// Called when session became inactive + /// - Parameter session: Current session + func sessionDidBecomeInactive(_ session: WCSession) { + self.logger.info("(WatchSessionManager) Session inactive.") + } + + /// Called when session deactivated + /// - Parameter session: Current session + func sessionDidDeactivate(_ session: WCSession) { + self.logger.info("(WatchSessionManager) Session deactivated.") + } +} +#endif diff --git a/Shared/Extensions+Modifiers/Bundle.swift b/Shared/Extensions+Modifiers/Bundle.swift new file mode 100644 index 0000000..b9f6f8f --- /dev/null +++ b/Shared/Extensions+Modifiers/Bundle.swift @@ -0,0 +1,35 @@ +// +// Bundle.swift +// vulcan +// +// Created by royal on 04/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import Foundation + +extension Bundle { + public var buildVersion: String { + return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown" + } + + public var buildNumber: String { + return Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "Unknown" + } + + public var colorSchemes: [String] { + return ["Default", "Dzienniczek+"] + } + + public var appIcons: [String] { + return ["AppIcon"] + } + + public var currentAppIcon: String { + return "AppIcon" + } + + public var groupIdentifier: String { + return "group.dev.niepostek.vulcanGroup" + } +} diff --git a/Shared/Extensions+Modifiers/Date.swift b/Shared/Extensions+Modifiers/Date.swift new file mode 100644 index 0000000..84c7dd7 --- /dev/null +++ b/Shared/Extensions+Modifiers/Date.swift @@ -0,0 +1,109 @@ +// +// Date.swift +// vulcan +// +// Created by royal on 05/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import Foundation + +extension Date { + public static func - (lhs: Date, rhs: Date) -> TimeInterval { + return lhs.timeIntervalSinceReferenceDate - rhs.timeIntervalSinceReferenceDate + } + + public func formattedString(format: String) -> String { + let dateFormatter = DateFormatter() + dateFormatter.dateFormat = format + dateFormatter.locale = Locale.autoupdatingCurrent + + return dateFormatter.string(from: self) + } + + public func formattedDateString(timeStyle: DateFormatter.Style = .none, dateStyle: DateFormatter.Style = .none, context: DateFormatter.Context = .unknown, hideDate: Bool = false) -> String { + let dateFormatter = DateFormatter() + dateFormatter.timeStyle = timeStyle + dateFormatter.dateStyle = (hideDate && self >= Date().startOfDay) ? .none : dateStyle + dateFormatter.locale = Calendar.autoupdatingCurrent.locale + dateFormatter.timeZone = Calendar.autoupdatingCurrent.timeZone + dateFormatter.formattingContext = context + + return dateFormatter.string(from: self) + } + + public var relativeString: String { + let dateFormatter = DateFormatter() + dateFormatter.timeStyle = .none + dateFormatter.dateStyle = .long + dateFormatter.doesRelativeDateFormatting = true + return dateFormatter.string(from: self) + } + + public var timestampString: String? { + let formatter = DateComponentsFormatter() + formatter.unitsStyle = .abbreviated + formatter.maximumUnitCount = 2 + formatter.allowedUnits = [.year, .month, .day, .hour, .minute, .second] + + guard let timeString = formatter.string(from: self, to: Date()) else { + return nil + } + + let formatString = NSLocalizedString("%@", comment: "") + return String(format: formatString, timeString) + } + + public var localizedTime: String { + let dateFormatter = DateFormatter() + dateFormatter.dateStyle = .none + dateFormatter.timeStyle = .short + return dateFormatter.string(from: self) + } + + public func startOfTheYear(offset: Int = 0) -> Date? { + let currentYear = Calendar.autoupdatingCurrent.component(.year, from: self) + return Calendar.autoupdatingCurrent.date(from: DateComponents(year: currentYear + offset, month: 1, day: 1)) + } + + public func endOfTheYear(offset: Int = 0) -> Date? { + let currentYear = Calendar.autoupdatingCurrent.component(.year, from: self) + return Calendar.autoupdatingCurrent.date(from: DateComponents(year: currentYear + offset, month: 12, day: 31)) + } + + public var startOfDay: Date { + return Calendar.autoupdatingCurrent.startOfDay(for: self) + } + + public var endOfDay: Date { + var components = DateComponents() + components.day = 1 + components.second = -1 + return Calendar.autoupdatingCurrent.date(byAdding: components, to: startOfDay)! + } + + public var startOfWeek: Date? { + let calendar = Calendar(identifier: .gregorian) + guard let sunday = calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil } + return calendar.date(byAdding: .day, value: 1, to: sunday) + } + + public var endOfWeek: Date? { + let calendar = Calendar(identifier: .gregorian) + guard let sunday = calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil } + return calendar.date(byAdding: .day, value: 7, to: sunday) + } + + public var startOfMonth: Date { + let calendar = Calendar(identifier: .gregorian) + let components = calendar.dateComponents([.year, .month], from: self) + return calendar.date(from: components)! + } + + public var endOfMonth: Date { + var components = DateComponents() + components.month = 1 + components.second = -1 + return Calendar(identifier: .gregorian).date(byAdding: components, to: self.startOfMonth)! + } +} diff --git a/Shared/Extensions+Modifiers/DeviceInfo.swift b/Shared/Extensions+Modifiers/DeviceInfo.swift new file mode 100644 index 0000000..4870a75 --- /dev/null +++ b/Shared/Extensions+Modifiers/DeviceInfo.swift @@ -0,0 +1,59 @@ +// +// DeviceInfo.swift +// vulcan +// +// Created by royal on 05/04/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +#if os(watchOS) +import WatchKit +#elseif os(OSX) +import AppKit +#else +import UIKit +#endif + +struct DeviceInfo { + static var supportsHapticsOrVibration: Bool { + #if os(macOS) + return false + #elseif os(iOS) + return UIDevice.current.userInterfaceIdiom == .phone + #elseif os(watchOS) + return true + #endif + } + + static var modelName: String { + #if os(watchOS) + return WKInterfaceDevice.current().model + #else + return UIDevice.current.model + #endif + } + + static var deviceName: String { + #if os(watchOS) + return WKInterfaceDevice.current().name + #else + return UIDevice.current.name + #endif + } + + static var systemName: String { + #if os(watchOS) + return WKInterfaceDevice.current().systemName + #else + return UIDevice.current.systemName + #endif + } + + static var systemVersion: String { + #if os(watchOS) + return WKInterfaceDevice.current().systemVersion + #else + return UIDevice.current.systemVersion + #endif + } +} diff --git a/Shared/Extensions+Modifiers/String.swift b/Shared/Extensions+Modifiers/String.swift new file mode 100644 index 0000000..6e5f28b --- /dev/null +++ b/Shared/Extensions+Modifiers/String.swift @@ -0,0 +1,51 @@ +// +// String.swift +// vulcan +// +// Created by royal on 24/06/2020. +// + +import Foundation + +extension String { + /// Returns strings of the URLs in the current string. + var urls: [URL] { + var urls : [URL] = [] + do { + let detector = try NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue) + detector.enumerateMatches(in: self, options: [], range: NSMakeRange(0, self.count), using: { (result, _, _) in + if let match = result, let url = match.url { + urls.append(url) + } + }) + } catch { + // AppState.logger.info(error.localizedDescription) + } + + return urls + } + + var base64Decoded: String? { + guard let data = Data(base64Encoded: self) else { + return nil + } + + return String(data: data, encoding: .utf8) + } + + var base64Encoded: String { + return Data(self.utf8).base64EncodedString() + } + + var localized: String { + return NSLocalizedString(self, tableName: nil, bundle: Bundle.main, value: "", comment: "") + } + + func capitalingFirstLetter() -> String { + return prefix(1).capitalized + dropFirst() + } + + var isReallyEmpty: Bool { + self.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + } +} diff --git a/Shared/Extensions+Modifiers/View+.swift b/Shared/Extensions+Modifiers/View+.swift new file mode 100644 index 0000000..23ccdaf --- /dev/null +++ b/Shared/Extensions+Modifiers/View+.swift @@ -0,0 +1,29 @@ +// +// View.swift +// vulcan +// +// Created by royal on 06/07/2020. +// + +import SwiftUI +import Combine + +// MARK: - List +extension List { + @ViewBuilder + func sidebarListStyle(horizontalSizeClass: UserInterfaceSizeClass?) -> some View { + #if os(iOS) + if (horizontalSizeClass == .compact) { + self + .listStyle(InsetGroupedListStyle()) + } else { + self + .listStyle(SidebarListStyle()) + } + #else + self + .listStyle(SidebarListStyle()) + .frame(minWidth: 900, maxWidth: .infinity, minHeight: 500, maxHeight: .infinity) + #endif + } +} diff --git a/Shared/Extensions+Modifiers/View.swift b/Shared/Extensions+Modifiers/View.swift new file mode 100644 index 0000000..9247ab8 --- /dev/null +++ b/Shared/Extensions+Modifiers/View.swift @@ -0,0 +1,99 @@ +// +// View.swift +// Harbour +// +// Created by royal on 15/03/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import SwiftUI +import Combine + +// MARK: - View +extension View { + func buttonModifier(color: Color, solid: Bool = true) -> some View { + return self + .padding() + .frame(minWidth: 0, maxWidth: .infinity, alignment: .center) + .background(solid ? color : color.opacity(0.2)) + .foregroundColor(solid ? Color.white : color) + .font(.headline) + .cornerRadius(12) + } + + @ViewBuilder + func coloredGrade(scheme: String, colorize: Bool, grade: Double?) -> some View { + if let double: Double = grade { + self + .coloredGrade(scheme: scheme, colorize: colorize, grade: Int(double)) + } else { + self + .foregroundColor(Color.primary) + } + } + + func coloredGrade(scheme: String, colorize: Bool, grade: Int?) -> some View { + if colorize { + return self + .foregroundColor(Color("ColorSchemes/\(scheme)/\(grade ?? 0)", bundle: Bundle(identifier: "Colors"))) + } else { + return self + .foregroundColor(Color.primary) + } + } + + @ViewBuilder + func loadingOverlay(_ loading: Bool, fadeAmount: Double = 0.9) -> some View { + if (loading) { + self + .opacity(loading ? 1 - fadeAmount : 1) + .overlay(ProgressView()) + } else { + self + } + } + + func navigationBarButton(edge: Edge.Set) -> some View { + return self + .padding([.vertical, edge == .leading ? .trailing : .leading]) + .padding(edge, 5) + .font(.system(size: 20)) + } + + /// Makes the view full width. + func fullWidth() -> some View { + return self.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .center) + } +} + +// MARK: - Text +extension Text { + func bold(_ useBold: Bool = true) -> Text { + if (useBold) { + return self.bold() + } else { + return self + } + } + + func sectionTitle() -> some View { + return self + .font(.title2) + .bold() + .opacity(1) + .foregroundColor(Color.primary) + .textCase(.none) + } +} + +// MARK: - ForEach +extension ForEach where Content: View { + @ViewBuilder + func onDelete(enabled: Bool, perform action: @escaping (IndexSet) -> Void) -> some View { + if (enabled) { + self.onDelete(perform: action) + } else { + self + } + } +} diff --git a/Shared/LaunchScreen.storyboard b/Shared/LaunchScreen.storyboard new file mode 100644 index 0000000..e251d30 --- /dev/null +++ b/Shared/LaunchScreen.storyboard @@ -0,0 +1,50 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/Shared/Localization/en.lproj/Localizable.strings b/Shared/Localization/en.lproj/Localizable.strings new file mode 100644 index 0000000..c05b91f --- /dev/null +++ b/Shared/Localization/en.lproj/Localizable.strings @@ -0,0 +1,196 @@ +/* + Localizable.strings + vulcan + en_US + + Created by royal on 31/05/2020. + Copyright © 2020 shameful. All rights reserved. +*/ + +"Error!" = "Error!"; +"Not reachable" = "Not reachable"; +"Today" = "Today"; +"Tomorrow" = "Tomorrow"; +"Lessons" = "Lessons"; + +// MARK: Vulcan.swift +"No endpoint URL found" = "No endpoint URL found. Make sure the provided token is correct."; +"Tomorrow: %@" = "Tomorrow: %@"; + +// MARK: ContentView.swift +"Home" = "Home"; +"Grades" = "Grades"; +"Schedule" = "Schedule"; +"Tasks" = "Tasks"; +"Messages" = "Messages"; +"NO_CONNECTION_TITLE" = "No internet connection!"; +"NO_CONNECTION_SUBTITLE" = "Only cached data is available."; +"Nothing selected" = "Nothing selected"; + +// MARK: OnboardingView.swift +"Welcome to" = "Welcome to"; +"ONBOARDING_FUNCTION1_TITLE" = "Make use of the platform"; +"ONBOARDING_FUNCTION1_DESCRIPTION" = "Widgets,  Watch app, dark mode - you name it."; +"ONBOARDING_FUNCTION2_TITLE" = "Get reminded"; +"ONBOARDING_FUNCTION2_DESCRIPTION" = "App will remind you about the next classes, new messages, grades, etc."; +"ONBOARDING_FUNCTION3_TITLE" = "Made by a student"; +"ONBOARDING_FUNCTION3_DESCRIPTION" = "Us, scholars, know better what we need."; +"Continue" = "Continue"; + +// MARK: SetupView.swift +"Log in" = "Log in"; +"SETUP_TITLE" = "Setup"; +"Token" = "Token"; +"Symbol" = "Symbol"; +"PIN" = "PIN"; +"Fill all fields!" = "Fill all fields!"; +"Logging in..." = "Logging in..."; +"Error logging in" = "Error logging in"; +"Go back" = "Go back"; +"Nevermind" = "Nevermind"; + +// MARK: HomeView.swift +"User" = "User"; +"HELLO : %s" = "Hi, %@!"; +"GOOD_MORNING : %@" = "Good morning, %@!"; +"GOOD_AFTERNOON : %@" = "Good afternoon, %@!"; +"GOOD_EVENING : %@" = "Good evening, %@!"; +"DATE_CURRENTLY : %@" = "It's currently %@."; + +"Current lesson" = "Current lesson"; +"Next lesson" = "Next lesson"; +"No lessons for now ☺️" = "No lessons for now ☺️"; +"New grades" = "New grades"; +"Exams" = "Exams"; +"Homework" = "Homework"; +"New messages" = "New messages"; + +"User details" = "User details"; +"Not logged in" = "Not logged in"; + +"No grades" = "No grades"; + +"Nothing in the near future" = "Nothing in the near future"; +"No new messages" = "No new messages"; + +"Your summary for today" = "Your summary for today"; + +// MARK: GradesView.swift +"See your grades" = "See your grades"; + +// MARK: ScheduleView.swift +"No lessons for this week 😊" = "No lessons for this week 😊"; +"No lessons for this day 😊" = "No lessons for this day 😊"; +"Displays your schedule in app." = "Displays your schedule in app."; + +// MARK: TasksView.swift +"No tasks" = "No tasks"; +"TASKS_FOLDER_TITLE" = "Choose a category"; +"Add to reminders" = "Add to reminders"; +"Add to calendar" = "Add to calendar"; +"TAG_EXAM" = "Exam"; +"TAG_HOMEWORK" = "Homework"; +"No exams for this month 😊" = "No exams for this month 😊"; +"No homework for this month 😊" = "No homework for this month 😊"; +"Displays your upcoming exams and homework" = "Displays your upcoming exams and homework"; + +// MARK: MessagesView.swift +"No messages found" = "No messages found"; +"Unknown" = "Unknown"; +"Reply" = "Reply"; +"Mark as read" = "Mark as read"; +"Copy" = "Copy"; +"Delete" = "Delete"; +"MESSAGES_FOLDER_TITLE" = "Choose a folder"; +"Received" = "Received"; +"Sent" = "Sent"; +"Deleted" = "Deleted"; +"MESSAGES : %@" = "Messages (%@)"; +"Filter" = "Filter"; +"All" = "All"; +"New" = "New"; +"See your received messages" = "See your received messages"; + +// MARK: SettingsView.swift +"General" = "General"; +"Settings" = "Settings"; +"Libraries" = "Libraries"; +"Default" = "Default"; + +"SETTINGS_LOGGEDIN : %@" = "Logged in as %@"; +"Log out" = "Log out"; +"Show all" = "Show all"; +"Notifications" = "Notifications"; +"SETTINGS_SCHEDULEALLEVENTS" = "Show all groups"; +"SETTINGS_SCHEDULEALLEVENTS_TOOLTIP" = "If enabled, you will see the schedule of your whole class."; +"SETTINGS_READMESSAGEONOPEN" = "Read messages on open"; +"SETTINGS_READMESSAGEONOPEN_TOOLTIP" = "Messages will be marked as read after they were opened."; +"SETTINGS_SCHEDULENOTIFICATIONS" = "Schedule notifications"; +"SETTINGS_SCHEDULENOTIFICATIONS_TOOLTIP" = "App will remind you about the next lesson at the end of the previous one."; +"SETTINGS_TASKNOTIFICATIONS" = "Tasks notifications"; +"SETTINGS_TASKNOTIFICATIONS_TOOLTIP" = "App will remind you about tasks day before."; +"Interface" = "Interface"; +"SETTINGS_FILTERSCHEDULE" = "Show only the selected day"; +"SETTINGS_FILTERSCHEDULE_TOOLTIP" = "Schedule will only show the selected day, not the whole week."; +"SETTINGS_COLORIZEGRADES" = "Colorize grades"; +"SETTINGS_COLORIZEGRADES_TOOLTIP" = "Grade labels will be colored."; +"SETTINGS_HAPTICFEEDBACK" = "Haptic Feedback"; +"SETTINGS_HAPTICFEEDBACK_TOOLTIP" = "If you don't like Haptic Feedback as much as I do, you might want to turn this off."; + +"Other" = "Other"; +"Reset user settings" = "Reset user settings"; +"SETTINGS_RESET" = "Are you sure you want to reset?"; +"SETTINGS_RESET_TOOLTIP" = "All of your app data will be removed!"; +"SETTINGS_RESETTED" = "Resetted! Restart?"; +"Done!" = "Done!"; +"Yes" = "Yes"; +"No" = "No"; +"Reset" = "Reset"; +"New update available!" = "New update available!"; + +"Color Scheme" = "Color Scheme"; +"App Icon" = "App Icon"; +"AppIcon" = "Default"; + +"Made with ❤️ (and ☕️) by @rrroyal" = "Made with ❤️ (and ☕️) by @rrroyal"; +"Version %@ (Build %@)" = "Version %@ (Build %@)"; + +// MARK: GradesDetailView.swift +"No description" = "No description"; +"Average" = "Average"; +"Anticipated" = "Anticipated"; +"Final" = "Final"; + +// MARK: ComposeMessageView.swift +"Title" = "Title"; +"Choose a recipient..." = "Choose a recipient..."; +"Message content..." = "Message content..."; +"Recipients" = "Recipients"; +"Done" = "Done"; + +// MARK: MessageDetailView.swift +"Links" = "Links"; +"Search" = "Search"; + +// MARK: UsersView.swift +"Users" = "Users"; + +// MARK: UserDetailView.swift +"About" = "About"; +"Name" = "Name"; +"Second name" = "Second name"; +"Surname" = "Surname"; +"Nick" = "Nick"; +"Login ID" = "Login ID"; +"Department Code" = "Department Code"; +"Branch Name" = "Branch Name"; +"Branch Name (short)" = "Branch Name (short)"; +"Nothing found" = "Nothing found"; +"Anticipated grades" = "Anticipated grades"; +"Final grades" = "Final grades"; +"Notes" = "Notes"; + +// MARK: - TaskCell.swift +"No entry" = "No entry"; +"EXAM_BIG" = "Exam"; +"EXAM_SMALL" = "Quiz"; diff --git a/Shared/Localization/pl.lproj/Localizable.strings b/Shared/Localization/pl.lproj/Localizable.strings new file mode 100644 index 0000000..8728562 --- /dev/null +++ b/Shared/Localization/pl.lproj/Localizable.strings @@ -0,0 +1,196 @@ +/* + Localizable.strings + vulcan + pl_PL + + Created by royal on 31/05/2020. + Copyright © 2020 shameful. All rights reserved. +*/ + +"Error!" = "Błąd!"; +"Not reachable" = "Brak połączenia z serwerem."; +"Today" = "Dzisiaj"; +"Tomorrow" = "Jutro"; +"Lessons" = "Lekcje"; + +// MARK: Vulcan.swift +"No endpoint URL found" = "Nie znaleziono adresu URL. Sprawdź swój token."; +"Tomorrow: %@" = "Jutro: %@"; + +// MARK: ContentView.swift +"Home" = "Strona główna"; +"Grades" = "Oceny"; +"Schedule" = "Plan lekcji"; +"Tasks" = "Zadania"; +"Messages" = "Wiadomości"; +"NO_CONNECTION_TITLE" = "Brak połączenia z internetem!"; +"NO_CONNECTION_SUBTITLE" = "Tylko lokalnie zapisane dane są dostępne."; +"Nothing selected" = "Nic nie wybrano"; + +// MARK: OnboardingView.swift +"Welcome to" = "Witaj w"; +"ONBOARDING_FUNCTION1_TITLE" = "Korzystaj z platformy"; +"ONBOARDING_FUNCTION1_DESCRIPTION" = "Widgety, aplikacja na  Watch, ciemny motyw - jest tutaj wszystko."; +"ONBOARDING_FUNCTION2_TITLE" = "Powiadomienia"; +"ONBOARDING_FUNCTION2_DESCRIPTION" = "Aplikacja przypomni Ci o kolejnych zajęciach, nowych wiadomościach, ocenach, itp."; +"ONBOARDING_FUNCTION3_TITLE" = "Stworzone przez studenta"; +"ONBOARDING_FUNCTION3_DESCRIPTION" = "My, uczniowie, lepiej wiemy czego potrzebujemy."; +"Continue" = "Kontynuuj"; + +// MARK: SetupView.swift +"Log in" = "Zaloguj"; +"SETUP_TITLE" = "Logowanie"; +"Token" = "Token"; +"Symbol" = "Symbol"; +"PIN" = "PIN"; +"Fill all fields!" = "Wypełnij wszystkie pola!"; +"Logging in..." = "Loguje się..."; +"Error logging in" = "Błąd podczas logowania"; +"Go back" = "Wróć"; +"Nevermind" = "Nieważne"; + +// MARK: HomeView.swift +"User" = "Użytkownik"; +"HELLO : %s" = "Cześć, %@!"; +"GOOD_MORNING : %@" = "Dzień dobry, %@!"; +"GOOD_AFTERNOON : %@" = "Dzień dobry, %@!"; +"GOOD_EVENING : %@" = "Dobry wieczór, %@!"; +"DATE_CURRENTLY : %@" = "Jest %@."; + +"Current lesson" = "Bieżąca lekcja"; +"Next lesson" = "Następna lekcja"; +"No lessons for now ☺️" = "Brak lekcji w najbliższym czasie ☺️"; +"New grades" = "Nowe oceny"; +"Exams" = "Testy"; +"Homework" = "Zadania domowe"; +"New messages" = "Nowe wiadomości"; + +"User details" = "Dane użytkownika"; +"Not logged in" = "Nie zalogowano"; + +"No grades" = "Brak ocen"; + +"Nothing in the near future" = "Nic w najbliższym czasie"; +"No new messages" = "Brak nowych wiadomości"; + +"Your summary for today" = "Twoje dzisiejsze podsumowanie"; + +// MARK: GradesView.swift +"See your grades" = "Zobacz swoje oceny"; + +// MARK: ScheduleView.swift +"No lessons for this week 😊" = "Brak lekcji na ten tydzień 😊"; +"No lessons for this day 😊" = "Brak lekcji na ten dzień 😊"; +"Displays your schedule" = "Pokazuje Twój plan lekcji"; + +// MARK: TasksView.swift +"No tasks" = "Brak zadań"; +"TASKS_FOLDER_TITLE" = "Wybierz kategorię"; +"Add to reminders" = "Dodaj do przypomnień"; +"Add to calendar" = "Dodaj do kalendarza"; +"TAG_EXAM" = "Test"; +"TAG_HOMEWORK" = "Zadanie domowe"; +"No exams for this month 😊" = "Brak testów w tym miesiącu 😊"; +"No homework for this month 😊" = "Brak zadań domowych w tym miesiącu 😊"; +"Displays your upcoming exams and homework" = "Pokazuje Twoje najbliższe testy i zadania domowe"; + +// MARK: MessagesView.swift +"No messages found" = "Brak wiadomości"; +"Unknown" = "Nieznane"; +"Reply" = "Odpowiedz"; +"Mark as read" = "Przeczytano"; +"Copy" = "Kopiuj"; +"Delete" = "Usuń"; +"MESSAGES_FOLDER_TITLE" = "Wybierz folder"; +"Received" = "Odebrane"; +"Sent" = "Wysłane"; +"Deleted" = "Usunięte"; +"MESSAGES : %@" = "Wiadomości (%@)"; +"Filter" = "Filtrowanie"; +"All" = "Wszystko"; +"New" = "Nowa"; +"See your received messages" = "Zobacz swoje odebrane wiadomości"; + +// MARK: SettingsView.swift +"General" = "Ogólne"; +"Settings" = "Ustawienia"; +"Libraries" = "Biblioteki"; +"Default" = "Domyślny"; + +"SETTINGS_LOGGEDIN : %@" = "Zalogowano jako %@"; +"Log out" = "Wyloguj się"; +"Show all" = "Wszystkie"; +"Notifications" = "Powiadomienia"; +"SETTINGS_SCHEDULEALLEVENTS" = "Pokaż wszystkie grupy"; +"SETTINGS_SCHEDULEALLEVENTS_TOOLTIP" = "Jeśli włączone, będziesz widzieć plan lekcji całej klasy."; +"SETTINGS_READMESSAGEONOPEN" = "Czytaj wiadomości po otwarciu"; +"SETTINGS_READMESSAGEONOPEN_TOOLTIP" = "Wiadomości zostaną oznaczone jako przeczytane po ich otwarciu."; +"SETTINGS_SCHEDULENOTIFICATIONS" = "Powiadomienia o lekcjach"; +"SETTINGS_SCHEDULENOTIFICATIONS_TOOLTIP" = "Aplikacja przypomni ci o następnej lekcji na końcu poprzedniej."; +"SETTINGS_TASKNOTIFICATIONS" = "Powiadomienia o zadaniach"; +"SETTINGS_TASKNOTIFICATIONS_TOOLTIP" = "Aplikacja przypomni ci o zadaniach dzień wcześniej."; +"Interface" = "Interfejs"; +"SETTINGS_FILTERSCHEDULE" = "Pokazuj tylko wybrany dzień"; +"SETTINGS_FILTERSCHEDULE_TOOLTIP" = "Plan lekcji zamiast pokazywać cały tydzień będzie pokazywał tylko wybrany dzień."; +"SETTINGS_COLORIZEGRADES" = "Koloruj oceny"; +"SETTINGS_COLORIZEGRADES_TOOLTIP" = "Etykiety ocen będą kolorowe."; +"SETTINGS_HAPTICFEEDBACK" = "Haptic Feedback"; +"SETTINGS_HAPTICFEEDBACK_TOOLTIP" = "Jeśli nie lubisz Haptic Feedback'u tak bardzo jak ja, możesz go wyłączyć."; + +"Other" = "Inne"; +"Reset user settings" = "Resetuj"; +"SETTINGS_RESET" = "Na pewno?"; +"SETTINGS_RESET_TOOLTIP" = "Wszystkie dane aplikacji zostaną usunięte!"; +"SETTINGS_RESETTED" = "Zresetowano! Zrestartować aplikacje?"; +"Done!" = "Gotowe!"; +"Yes" = "Tak"; +"No" = "Nie"; +"Reset" = "Resetuj"; +"New update available!" = "Dostępna jest nowa wersja!"; + +"Color Scheme" = "Motyw"; +"App Icon" = "Ikona aplikacji"; +"AppIcon" = "Domyślna"; + +"Made with ❤️ (and ☕️) by @rrroyal" = "Zrobione z ❤️ (i ☕️) przez @rrroyal"; +"Version %@ (Build %@)" = "Wersja %@ (Numer %@)"; + +// MARK: GradesDetailView.swift +"No description" = "Brak opisu"; +"Average" = "Średnia"; +"Anticipated" = "Ocena proponowana"; +"Final" = "Ocena ostateczna"; + +// MARK: ComposeMessageView.swift +"Title" = "Tytuł"; +"Choose a recipient..." = "Wybierz adresatów..."; +"Message content..." = "Treść wiadomości..."; +"Recipients" = "Adresaci"; +"Done" = "Gotowe"; + +// MARK: MessageDetailView.swift +"Links" = "Odnośniki"; +"Search" = "Szukaj"; + +// MARK: UsersView.swift +"Users" = "Użytkownicy"; + +// MARK: UserDetailView.swift +"About" = "O użytkowniku"; +"Name" = "Imię"; +"Second name" = "Drugie imię"; +"Surname" = "Nazwisko"; +"Nick" = "Pseudonim"; +"Login ID" = "Login ID"; +"Department Code" = "Kod wydziału"; +"Branch Name" = "Nazwa wydziału"; +"Branch Name (short)" = "Krótka nazwa wydziału"; +"Nothing found" = "Nic nie znaleziono"; +"Anticipated grades" = "Oceny proponowane"; +"Final grades" = "Oceny ostateczne"; +"Notes" = "Uwagi"; + +// MARK: - TaskCell.swift +"No entry" = "Brak wpisu"; +"EXAM_BIG" = "Sprawdzian"; +"EXAM_SMALL" = "Kartkówka"; diff --git a/Shared/Other/Global.swift b/Shared/Other/Global.swift new file mode 100644 index 0000000..bef9045 --- /dev/null +++ b/Shared/Other/Global.swift @@ -0,0 +1,63 @@ +// +// Global.swift +// bitty +// +// Created by royal on 12/08/2020. +// + + +#if canImport(UIKit) +import UIKit +#endif + +import CoreHaptics +import AudioToolbox + +enum FeedbackStyle { + case error + case success + case warning + case light + case medium + case heavy + case soft + case rigid + case selectionChanged +} + +/// Generates a haptic feedback/vibration. +/// - Parameter style: Style of the feedback +func generateHaptic(_ style: FeedbackStyle) { + #if !os(OSX) + let hapticCapability = CHHapticEngine.capabilitiesForHardware() + let supportsHaptics = hapticCapability.supportsHaptics + + if (supportsHaptics) { + // Haptic Feedback + switch (style) { + case .error: UINotificationFeedbackGenerator().notificationOccurred(.error); break + case .success: UINotificationFeedbackGenerator().notificationOccurred(.success); break + case .warning: UINotificationFeedbackGenerator().notificationOccurred(.warning); break + case .light: UIImpactFeedbackGenerator(style: .light).impactOccurred(); break + case .medium: UIImpactFeedbackGenerator(style: .medium).impactOccurred(); break + case .heavy: UIImpactFeedbackGenerator(style: .heavy).impactOccurred(); break + case .soft: UIImpactFeedbackGenerator(style: .soft).impactOccurred(); break + case .rigid: UIImpactFeedbackGenerator(style: .rigid).impactOccurred(); break + case .selectionChanged: UISelectionFeedbackGenerator().selectionChanged(); break + } + } else { + // Older devices + switch (style) { + case .error: AudioServicesPlaySystemSound(1521); break + case .success: break + case .warning: break + case .light: AudioServicesPlaySystemSound(1519); break + case .medium: break + case .heavy: AudioServicesPlaySystemSound(1520); break + case .soft: break + case .rigid: break + case .selectionChanged: AudioServicesPlaySystemSound(1519); break + } + } + #endif +} diff --git a/Shared/Other/Tab.swift b/Shared/Other/Tab.swift new file mode 100644 index 0000000..691b1b7 --- /dev/null +++ b/Shared/Other/Tab.swift @@ -0,0 +1,15 @@ +// +// Tab.swift +// vulcan +// +// Created by royal on 26/06/2020. +// + +enum Tab { + case home + case grades + case schedule + case tasks + case messages + case settings +} diff --git a/Shared/Views/Components/Cells/FinalGradeCell.swift b/Shared/Views/Components/Cells/FinalGradeCell.swift new file mode 100644 index 0000000..9d2dfc5 --- /dev/null +++ b/Shared/Views/Components/Cells/FinalGradeCell.swift @@ -0,0 +1,32 @@ +// +// FinalGradeCell.swift +// vulcan +// +// Created by royal on 07/06/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import SwiftUI +import Vulcan + +struct FinalGradeCell: View { + let scheme: String + let colorize: Bool + let grade: Vulcan.EndOfTermGrade + + var body: some View { + HStack { + Text(grade.subject?.name ?? "Unknown subject (\(grade.subjectID))") + .bold() + .lineLimit(2) + .allowsTightening(true) + .minimumScaleFactor(0.9) + Spacer() + Text(grade.entry) + .bold() + .coloredGrade(scheme: scheme, colorize: colorize, grade: Int(grade.entry)) + .padding(.leading) + } + .padding(.vertical, 10) + } +} diff --git a/Shared/Views/Components/Cells/GradeCell.swift b/Shared/Views/Components/Cells/GradeCell.swift new file mode 100644 index 0000000..6531b03 --- /dev/null +++ b/Shared/Views/Components/Cells/GradeCell.swift @@ -0,0 +1,93 @@ +// +// GradeCell.swift +// vulcan +// +// Created by royal on 30/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import SwiftUI +import Vulcan + +struct GradeCell: View { + let scheme: String + let colorize: Bool + let grade: Vulcan.Grade + + var body: some View { + HStack { + // Grade entry + Text((grade.entry?.isEmpty ?? true) ? "..." : (grade.entry ?? "...")) + .font(.title) + .bold() + .padding(.trailing) + .opacity(grade.value == nil ? 0.5 : 1) + .coloredGrade(scheme: scheme, colorize: colorize, grade: grade.grade) + + // New grade indicator + /* if (!grade.seen) { + Image(systemName: "staroflife.fill") + .opacity(0.35) + } */ + + // Spacing + Spacer(minLength: 20) + + // Grade details + VStack(alignment: .trailing, spacing: 4) { + Group { + Group { + if let description = grade.description { + Text(LocalizedStringKey(description.isEmpty ? "No description" : description)) + } else { + Text(LocalizedStringKey("No description")) + } + } + .font(.headline) + .foregroundColor((grade.description?.isEmpty ?? true) ? Color.secondary : Color.primary) + + Group { + if let category = grade.category { + if let comment = grade.comment { + Text(comment) + } + + if let weight = grade.weight?.replacingOccurrences(of: ",", with: ".") { + Text("\(category.name ?? "Unknown category") • \(weight)") + } else { + Text(category.name ?? "Unknown category") + } + + Text(grade.dateCreated.formattedDateString(timeStyle: .none, dateStyle: .full, context: .beginningOfSentence)) + } else { + // Comment + if let comment = grade.comment { + Text(comment) + } + + // Weight, date + if let weight = grade.weight?.replacingOccurrences(of: ",", with: ".") { + Text("\(weight) • \(grade.dateCreated.formattedDateString(timeStyle: .none, dateStyle: .full, context: .beginningOfSentence))") + } else { + Text(grade.dateCreated.formattedDateString(timeStyle: .none, dateStyle: .full, context: .beginningOfSentence)) + } + } + } + .font(.callout) + .foregroundColor(.secondary) + } + .multilineTextAlignment(.trailing) + .allowsTightening(true) + .minimumScaleFactor(0.5) + .lineLimit(3) + } + } + .padding(.vertical, 10) + } +} + +/* struct GradeCell_Previews: PreviewProvider { + static var previews: some View { + GradeCell() + } +} */ diff --git a/Shared/Views/Components/Cells/MessageCell.swift b/Shared/Views/Components/Cells/MessageCell.swift new file mode 100644 index 0000000..1630068 --- /dev/null +++ b/Shared/Views/Components/Cells/MessageCell.swift @@ -0,0 +1,151 @@ +// +// MessageCell.swift +// vulcan +// +// Created by royal on 27/06/2020. +// + +import SwiftUI +import Vulcan +import AppNotifications + +struct MessageCell: View { + var message: Vulcan.Message + @Binding var isComposeSheetPresented: Bool + @Binding var messageToReply: Vulcan.Message? + + static let dateFormatter: DateFormatter = { + let formatter = DateFormatter() + formatter.dateStyle = .short + formatter.timeStyle = .short + formatter.locale = Locale.autoupdatingCurrent + formatter.doesRelativeDateFormatting = true + return formatter + }() + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + // Name & Surname, Date + HStack { + Group { + // Name & Surname + if ((message.tag ?? .received) == .sent) { + Text(message.recipientsString.joined(separator: ", ")) + .font(.headline) + } else { + Text(message.sender ?? "Unknown sender") + .font(.headline) + } + + Spacer() + + // Date + // Text(message.dateSent.formattedDateString(timeStyle: .short, dateStyle: .medium)) + Text(message.dateSent, formatter: Self.dateFormatter) + .multilineTextAlignment(.trailing) + .font(.callout) + .foregroundColor(Color(UIColor.gray)) + } + .lineLimit(1) + } + + // Title + Text(message.title) + .font(.body) + .multilineTextAlignment(.leading) + .lineLimit(2) + .allowsTightening(true) + .truncationMode(.tail) + + // Content + Text(message.content.trimmingCharacters(in: .whitespacesAndNewlines)) + .font(.callout) + .multilineTextAlignment(.leading) + .lineLimit(2) + .truncationMode(.tail) + .allowsTightening(true) + .foregroundColor(Color(UIColor.gray)) + } + .padding(.vertical, 10) + .opacity(message.hasBeenRead ? 0.5 : 1) + .onDrag { + var string: String = "" + string += "Od: \(message.sender ?? "Unknown sender")\n" + string += "Data: \(self.message.dateSent.formattedString(format: "yyyy-MM-dd HH:mm:ss"))\n\n" + string += self.message.content + return NSItemProvider(object: string.trimmingCharacters(in: .whitespacesAndNewlines) as NSString) + } + .contextMenu { + // Reply + Button(action: { + generateHaptic(.light) + messageToReply = message + isComposeSheetPresented = true + }) { + Text("Reply") + Spacer() + Image(systemName: "arrowshape.turn.up.left") + } + + // Mark as read - only visible if not read yet or message sender isn't us + if (!message.hasBeenRead && message.tag != .sent) { + Button(action: { + generateHaptic(.light) + Vulcan.shared.moveMessage(message: message, to: .read) { error in + if let error = error { + generateHaptic(.error) + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + }) { + Text("Mark as read") + Spacer() + Image(systemName: "envelope.open") + } + } + + // Copy + Button(action: { + var string: String = "" + if let sender = message.sender { + string += "Od: \(sender)\n" + } + string += "Data: \(message.dateSent.formattedString(format: "yyyy-MM-dd HH:mm:ss"))\n\n" + string += message.content + generateHaptic(.light) + UIPasteboard.general.string = string.trimmingCharacters(in: .whitespacesAndNewlines) + }) { + Text("Copy") + Spacer() + Image(systemName: "doc.on.doc") + } + + Divider() + + // Remove + if (message.tag == .received || message.tag == .sent) { + Button(action: { + generateHaptic(.medium) + Vulcan.shared.moveMessage(message: message, to: .deleted) { error in + if let error = error { + generateHaptic(.error) + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + }) { + Text("Delete") + Spacer() + Image(systemName: "trash") + } + .foregroundColor(Color.red) + .accentColor(Color.red) + } + } + } +} + +/* struct MessageCell_Previews: PreviewProvider { + static var previews: some View { + MessageCell() + } +} */ diff --git a/Shared/Views/Components/Cells/NoteCell.swift b/Shared/Views/Components/Cells/NoteCell.swift new file mode 100644 index 0000000..226dc83 --- /dev/null +++ b/Shared/Views/Components/Cells/NoteCell.swift @@ -0,0 +1,62 @@ +// +// NoteCell.swift +// vulcan +// +// Created by royal on 07/06/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import SwiftUI +import Vulcan + +struct NoteCell: View { + let note: Vulcan.Note + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Text(note.entry) + .font(.headline) + .allowsTightening(true) + .minimumScaleFactor(0.8) + .lineLimit(nil) + + if let employeeName = note.employee?.name, + let employeeSurname = note.employee?.surname { + Group { + if let categoryName = note.category?.name { + Text("\(employeeName) \(employeeSurname): \(categoryName) • \(note.date.formattedDateString(timeStyle: .none, dateStyle: .medium))") + } else { + Text("\(employeeName) \(employeeSurname) • \(note.date.formattedDateString(timeStyle: .none, dateStyle: .medium))") + } + } + .foregroundColor(.secondary) + .multilineTextAlignment(.leading) + .allowsTightening(true) + .minimumScaleFactor(0.9) + .lineLimit(5) + } + } + .padding(.vertical, 10) + .contextMenu { + // Copy + Button(action: { + var string: String = "" + string += "Od: \(note.employee?.name ?? "Unknown employee") \(note.employee?.surname ?? "")\n" + string += "Data: \(note.date.formattedString(format: "yyyy-MM-dd HH:mm:ss"))\n\n" + string += note.entry + generateHaptic(.light) + UIPasteboard.general.string = string.trimmingCharacters(in: .whitespacesAndNewlines) + }) { + Text("Copy") + Spacer() + Image(systemName: "doc.on.doc") + } + } + } +} + +/* struct NoteCell_Previews: PreviewProvider { + static var previews: some View { + NoteCell() + } +} */ diff --git a/Shared/Views/Components/Cells/ScheduleEventCell.swift b/Shared/Views/Components/Cells/ScheduleEventCell.swift new file mode 100644 index 0000000..fe1460d --- /dev/null +++ b/Shared/Views/Components/Cells/ScheduleEventCell.swift @@ -0,0 +1,78 @@ +// +// ScheduleEventCell.swift +// vulcan +// +// Created by royal on 07/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import SwiftUI +import Vulcan + +struct ScheduleEventCell: View { + let event: Vulcan.ScheduleEvent + let showAllScheduleEvents: Bool + + var body: some View { + VStack(alignment: .center, spacing: 4) { + // First row: Subject name and room + HStack(alignment: .center, spacing: 0) { + // Subject name + Text(event.subject?.name ?? event.subjectName) + .font(.headline) + .strikethrough(event.labelStrikethrough) + .underline(event.labelBold) + .allowsTightening(true) + .minimumScaleFactor(0.3) + .lineLimit(2) + + Spacer() + + // Room + Group { + if let division = event.divisionShort, + showAllScheduleEvents { + Text("\(event.room) (\(division))") + } else { + Text(event.room) + } + } + .font(.body) + .allowsTightening(true) + .minimumScaleFactor(0.75) + .lineLimit(1) + } + + // Second row: Time and teacher + HStack(alignment: .center, spacing: 0) { + // Time, teacher + Text("\(event.dateStarts?.localizedTime ?? "") - \(event.dateEnds?.localizedTime ?? "") • \(event.employee?.name ?? "Unknown") \(event.employee?.surname ?? "employee")") + .font(.callout) + .foregroundColor((event.dateStarts ?? Date(timeIntervalSince1970: 0) < Date() && event.dateEnds ?? Date(timeIntervalSince1970: 0) > Date()) ? Color.accentColor : Color.secondary) + .allowsTightening(true) + .minimumScaleFactor(0.75) + .lineLimit(1) + + Spacer() + } + + // Third row: Note + if let note = event.note, !note.isReallyEmpty { + HStack(alignment: .center, spacing: 0) { + Text(note) + .font(.callout) + .foregroundColor((event.dateStarts ?? Date(timeIntervalSince1970: 0) < Date() && event.dateEnds ?? Date(timeIntervalSince1970: 0) > Date()) ? Color.accentColor : Color.secondary) + .allowsTightening(true) + .minimumScaleFactor(0.75) + .lineLimit(3) + + Spacer() + } + } + } + .padding(.vertical, 10) + .foregroundColor((event.dateStarts ?? Date(timeIntervalSince1970: 0) < Date() && event.dateEnds ?? Date(timeIntervalSince1970: 0) > Date()) ? Color.accentColor : Color.primary) + .opacity((event.dateEnds ?? event.date < Date()) ? 0.5 : 1) + .id(event.id) + } +} diff --git a/Shared/Views/Components/Cells/TaskCell.swift b/Shared/Views/Components/Cells/TaskCell.swift new file mode 100644 index 0000000..c632e9a --- /dev/null +++ b/Shared/Views/Components/Cells/TaskCell.swift @@ -0,0 +1,69 @@ +// +// TaskCell.swift +// vulcan +// +// Created by royal on 26/06/2020. +// + +import SwiftUI +import Vulcan + +struct TaskCell: View { + let task: VulcanTask + let isBigType: Bool? + + var body: some View { + VStack(alignment: .leading, spacing: 4) { + Group { + if !task.entry.isReallyEmpty { + Text(task.entry) + } else { + Text("No entry") + .foregroundColor(.secondary) + } + } + .font(.headline) + .multilineTextAlignment(.leading) + .allowsTightening(true) + .lineLimit(nil) + + Group { + if let subjectName = task.subject?.name, + let employeeName = task.employee?.name, + let employeeSurname = task.employee?.surname { + Text("\(subjectName) - \(employeeName) \(employeeSurname)") + } + + if let isBigType = isBigType { + Text("\((isBigType ? "EXAM_BIG" : "EXAM_SMALL").localized) • \(task.date.relativeString)") + } else { + Text(task.date, style: .relative) + } + } + .font(.callout) + .foregroundColor(.secondary) + .multilineTextAlignment(.leading) + .allowsTightening(true) + .lineLimit(3) + } + .padding(.vertical, 10) + .opacity(task.date.endOfDay >= Date() ? 1 : 0.5) + .contextMenu { + // Reminders + Button(action: { + generateHaptic(.light) + task.addToReminders(isBigType: isBigType) + }) { + Label("Add to reminders", systemImage: "bell.fill") + } + + // Calendar + Button(action: { + generateHaptic(.light) + task.addToCalendar(isBigType: isBigType) + }) { + Label("Add to calendar", systemImage: "calendar.badge.plus") + } + } + } +} diff --git a/Shared/Views/Components/CloseButton.swift b/Shared/Views/Components/CloseButton.swift new file mode 100644 index 0000000..943a98f --- /dev/null +++ b/Shared/Views/Components/CloseButton.swift @@ -0,0 +1,35 @@ +// +// CloseButton.swift +// vulcan +// +// Created by royal on 27/06/2020. +// + +import SwiftUI + +struct CloseButton: View { + let action: () -> Void + + init(perform action: @escaping () -> Void) { + self.action = action + } + + var body: some View { + Circle() + .fill(Color(UIColor.systemGray5)) + .overlay( + Image(systemName: "xmark") + .font(.system(size: 16, weight: .semibold)) + .foregroundColor(Color(UIColor.systemGray)) + ) + .frame(width: 26, height: 26) + .onTapGesture(perform: action) + } +} + +struct CloseButton_Previews: PreviewProvider { + static var previews: some View { + CloseButton(perform: {}) + .previewLayout(.sizeThatFits) + } +} diff --git a/Shared/Views/Components/RefreshButton.swift b/Shared/Views/Components/RefreshButton.swift new file mode 100644 index 0000000..ac3a3e8 --- /dev/null +++ b/Shared/Views/Components/RefreshButton.swift @@ -0,0 +1,47 @@ +// +// RefreshButton.swift +// vulcan +// +// Created by royal on 25/06/2020. +// + +import SwiftUI + +struct RefreshButton: View { + internal init(loading: Bool, progressValue: Double? = nil, iconName: String, edge: Edge.Set, perform action: @escaping () -> Void) { + self.loading = loading + self.progressValue = progressValue + self.iconName = iconName + self.edge = edge + self.action = action + } + + var loading: Bool + var progressValue: Double? + var iconName: String + var edge: Edge.Set + var action: () -> Void + + var body: some View { + Group { + if loading { + ProgressView(value: progressValue) + } else { + Button(action: action) { + Image(systemName: iconName) + } + .keyboardShortcut("R", modifiers: .command) + } + } + // .transition(.opacity) + // .animation(.easeInOut) + // .frame(width: 22.5) + .navigationBarButton(edge: edge) + } +} + +/* struct RefreshButton_Previews: PreviewProvider { + static var previews: some View { + RefreshButton() + } +} */ diff --git a/Shared/Views/ContentView.swift b/Shared/Views/ContentView.swift new file mode 100644 index 0000000..8a66b33 --- /dev/null +++ b/Shared/Views/ContentView.swift @@ -0,0 +1,52 @@ +// +// ContentView.swift +// Shared +// +// Created by royal on 24/06/2020. +// + +import SwiftUI +import Vulcan + +/// Main view +struct ContentView: View { + @Binding var currentTab: Tab + + /* #if os(iOS) + @Environment(\.horizontalSizeClass) private var horizontalSizeClass + #endif */ + + @State private var isOnboardingVisible: Bool = !SettingsModel.shared.launchedBefore + @State private var isNotificationVisible: Bool = false + + @ViewBuilder var body: some View { + Group { + #if os(iOS) + /* if horizontalSizeClass == .compact { + AppTabNavigation(currentTab: $currentTab) + } else { + AppSidebarNavigation() + } */ + AppTabNavigation(currentTab: $currentTab) + #else + AppSidebarNavigation() + #endif + } + .sheet(isPresented: $isOnboardingVisible, onDismiss: { + SettingsModel.shared.launchedBefore = true + }) { + OnboardingView(isPresented: $isOnboardingVisible) + } + /* .onAppear { + if !SettingsModel.shared.launchedBefore { + isOnboardingVisible = true + } + } */ + } +} + +struct ContentView_Previews: PreviewProvider { + static var previews: some View { + ContentView(currentTab: .constant(.home)) + } +} diff --git a/Shared/Views/Details/ComposeMessageView.swift b/Shared/Views/Details/ComposeMessageView.swift new file mode 100644 index 0000000..6a6f112 --- /dev/null +++ b/Shared/Views/Details/ComposeMessageView.swift @@ -0,0 +1,202 @@ +// +// ComposeMessageView.swift +// vulcan +// +// Created by royal on 27/06/2020. +// + +import SwiftUI +import Vulcan + +fileprivate struct MessageRecipientsListView: View { + @Binding var isRecipientsSheetVisible: Bool + @Binding var messageRecipients: [Vulcan.Recipient] + + @State private var searchFilter: String = "" + @FetchRequest(entity: DictionaryEmployee.entity(), sortDescriptors: [NSSortDescriptor(key: "surname", ascending: true)]) var employees: FetchedResults + + private func isRecipient(_ recipient: DictionaryEmployee) -> Bool { + let code = Int(recipient.id) + let recipients = self.messageRecipients.map(\.id) + return recipients.contains(code) + } + + var body: some View { + NavigationView { + List { + Section { + TextField("Search", text: $searchFilter) + .labelsHidden() + } + + ForEach(searchFilter.isEmpty ? Array(employees) : employees.filter({ ($0.name ?? "").lowercased().contains(searchFilter.lowercased()) || ($0.surname ?? "").lowercased().contains(searchFilter.lowercased()) || ($0.code ?? "").lowercased().contains(searchFilter.lowercased()) })) { employee in + if let employeeSurname = employee.surname, + let employeeName = employee.name, + let employeeCode = employee.code { + HStack { + Text("\(employeeSurname) \(employeeName) (\(employeeCode))".trimmingCharacters(in: .whitespacesAndNewlines)) + Spacer() + Image(systemName: "checkmark") + .opacity(isRecipient(employee) ? 1 : 0) + .transition(.opacity) + .animation(.easeInOut(duration: 0.1)) + .foregroundColor(.accentColor) + } + .contentShape(Rectangle()) + .onTapGesture { + generateHaptic(.selectionChanged) + + if (isRecipient(employee)) { + guard let recipientsIndex = messageRecipients.map(\.id).firstIndex(of: Int(employee.id)) else { + return + } + + messageRecipients.remove(at: recipientsIndex) + return + } + + let recipient = Vulcan.Recipient(id: Int(employee.id), name: "\(employee.surname ?? "Unknown employee") \(employee.name ?? "") (\(employee.code ?? ""))") + messageRecipients.append(recipient) + } + } + } + } + .listStyle(InsetGroupedListStyle()) + .navigationTitle(Text("Recipients")) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button(action: { + isRecipientsSheetVisible = false + }) { + Text("Done") + } + } + } + } + } +} + +struct ComposeMessageView: View { + @Binding var isPresented: Bool + @Binding var message: Vulcan.Message? + + @State private var loading: Bool = false + @State private var isRecipientsSheetVisible: Bool = false + @State private var messageTitle: String = "" + @State private var messageContent: String = "" + @State private var messageRecipients: [Vulcan.Recipient] = [] + + private var messageRecipientsString: [String] { + self.messageRecipients + .map(\.name) + } + + /// Sends the message. + private func sendMessage() { + let title: String = messageTitle.trimmingCharacters(in: .whitespacesAndNewlines) + let content: String = messageContent.trimmingCharacters(in: .whitespacesAndNewlines) + + if (title.isEmpty || content.isEmpty || messageRecipients.isEmpty) { + return + } + + loading = true + generateHaptic(.light) + + Vulcan.shared.sendMessage(to: messageRecipients, title: messageTitle, content: messageContent) { error in + loading = false + + if error == nil { + generateHaptic(.success) + isPresented = false + } else { + generateHaptic(.error) + } + } + } + + var body: some View { + VStack(alignment: .leading) { + // Title and `send` button + HStack { + TextField("Title", text: $messageTitle) + .font(.title) + .allowsTightening(true) + .minimumScaleFactor(0.75) + + Spacer() + + Button(action: sendMessage) { + Image(systemName: "paperplane.fill") + .navigationBarButton(edge: .trailing) + } + .disabled(messageTitle.isEmpty || messageContent.isEmpty || messageRecipients.isEmpty || loading) + } + + // Recipients + HStack { + Image(systemName: "person.crop.circle") + + if (messageRecipientsString.isEmpty) { + Text("Choose a recipient...") + } else { + Text(messageRecipientsString.joined(separator: ", ").trimmingCharacters(in: .whitespacesAndNewlines)) + } + + Spacer() + } + .padding(.trailing) + .padding(.vertical, 5) + .contentShape(Rectangle()) + .foregroundColor(Color.accentColor) + .onTapGesture { + isRecipientsSheetVisible.toggle() + } + .onLongPressGesture { + generateHaptic(.selectionChanged) + messageRecipients.removeAll() + } + + // Message content + TextEditor(text: $messageContent) + .lineLimit(nil) + .multilineTextAlignment(.leading) + + Spacer() + } + .padding() + .contentShape(Rectangle()) + .sheet(isPresented: $isRecipientsSheetVisible) { + MessageRecipientsListView(isRecipientsSheetVisible: $isRecipientsSheetVisible, messageRecipients: $messageRecipients) + } + .loadingOverlay(loading) + .allowsHitTesting(!loading) + .onAppear { + // Message reply setup + if let message: Vulcan.Message = message { + messageTitle = "RE: \(message.title)".trimmingCharacters(in: .whitespacesAndNewlines) + + // Why the fuck is `senderID` different than `DictionaryEmployee.id`? + switch (message.tag) { + case .received, .deleted, .none: + messageRecipients = [Vulcan.Recipient(id: message.senderID, name: message.sender ?? "")] + case .sent: + messageRecipients = message.recipients ?? [] + } + + messageContent += "\n" + if let sender = message.sender { + messageContent += "\nOd: \(sender)" + } + messageContent += "\nData: \(message.dateSent.formattedString(format: "yyyy-MM-dd HH:mm:ss"))" + messageContent += "\n\n\(message.content.trimmingCharacters(in: .whitespacesAndNewlines))" + } + } + } +} + +/* struct ComposeMessageView_Previews: PreviewProvider { + static var previews: some View { + ComposeMessageView() + } +} */ diff --git a/Shared/Views/Details/GradesDetailView.swift b/Shared/Views/Details/GradesDetailView.swift new file mode 100644 index 0000000..fa1103a --- /dev/null +++ b/Shared/Views/Details/GradesDetailView.swift @@ -0,0 +1,149 @@ +// +// GradesDetailView.swift +// vulcan +// +// Created by royal on 18/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import SwiftUI +import Vulcan +import CoreData + +struct GradesDetailView: View { + @EnvironmentObject var vulcan: Vulcan + @EnvironmentObject var settings: SettingsModel + let subject: Vulcan.SubjectGrades + + @AppStorage(UserDefaults.AppKeys.colorScheme.rawValue, store: .group) var colorScheme: String = "Default" + @AppStorage(UserDefaults.AppKeys.colorizeGrades.rawValue, store: .group) var colorizeGrades: Bool = true + + private var average: String? { + let fetchRequest: NSFetchRequest = StoredEndOfTermPoints.fetchRequest() + fetchRequest.predicate = NSPredicate(format: "subjectID == %d", subject.id) + + if let fetchResults: [StoredEndOfTermPoints] = try? CoreDataModel.shared.persistentContainer.viewContext.fetch(fetchRequest) as? [StoredEndOfTermPoints], + let entity = fetchResults.first { + return entity.gradeAverage?.replacingOccurrences(of: ",", with: ".") + } + + return nil + } + + /// Refreshes the data + private func fetch() { + var shouldProvideErrorFeedback: Bool = false + vulcan.getGrades() { error in + if error != nil { + shouldProvideErrorFeedback = true + } + } + + vulcan.getEndOfTermGrades() { error in + if error != nil { + shouldProvideErrorFeedback = true + } + } + + if shouldProvideErrorFeedback { + generateHaptic(.error) + } + } + + /// Cell with average grade + private var averageCell: some View { + HStack { + Text("Average") + .bold() + Spacer() + Text(average ?? "") + .bold() + .coloredGrade(scheme: colorScheme, colorize: colorizeGrades, grade: Int(round(Float(average ?? "") ?? 0))) + } + .padding(.vertical, 10) + } + + /// Cell with anticipated grade + private var anticipatedGradeCell: some View { + HStack { + Text("Anticipated") + .bold() + Spacer() + Text(vulcan.eotGrades.expected.first(where: { $0.subjectID == subject.subject.id })?.entry ?? "") + .bold() + .coloredGrade(scheme: colorScheme, colorize: colorizeGrades, grade: Int(vulcan.eotGrades.expected.first(where: { $0.subjectID == subject.subject.id })?.entry ?? "")) + } + .padding(.vertical, 10) + } + + /// Cell with final grade + private var finalGradeCell: some View { + HStack { + Text("Final") + .bold() + Spacer() + Text(vulcan.eotGrades.final.first(where: { $0.subjectID == subject.subject.id })?.entry ?? "") + .bold() + .coloredGrade(scheme: colorScheme, colorize: colorizeGrades, grade: Int(vulcan.eotGrades.final.first(where: { $0.subjectID == subject.subject.id })?.entry ?? "")) + } + .padding(.vertical, 10) + } + + var body: some View { + List { + // Grades + Section { + ForEach(subject.grades) { (grade) in + GradeCell(scheme: colorScheme, colorize: colorizeGrades, grade: grade) + } + } + + // Final grades + if (average != nil || vulcan.eotGrades.expected.first(where: { $0.subjectID == subject.subject.id }) != nil || vulcan.eotGrades.final.first(where: { $0.subjectID == subject.subject.id }) != nil) { + Section { + if (average != nil) { + averageCell + } + + // Anticipated + if (vulcan.eotGrades.expected.first(where: { $0.subjectID == subject.subject.id }) != nil) { + anticipatedGradeCell + } + + // Final + if (vulcan.eotGrades.final.first(where: { $0.subjectID == subject.subject.id }) != nil) { + finalGradeCell + } + } + } + } + .listStyle(InsetGroupedListStyle()) + .navigationTitle(Text(subject.subject.name)) + .toolbar { + // Refresh button + ToolbarItem(placement: .navigationBarTrailing) { + RefreshButton(loading: vulcan.dataState.grades.loading || vulcan.dataState.eotGrades.loading, iconName: "arrow.clockwise", edge: .trailing) { + generateHaptic(.light) + fetch() + } + } + } + .onAppear { + vulcan.grades.first(where: { $0.subject.id == self.subject.id })?.hasNewItems = false + + if (AppState.networking.monitor.currentPath.isExpensive || vulcan.currentUser == nil) { + return + } + + if (!vulcan.dataState.eotGrades.fetched || (vulcan.dataState.eotGrades.lastFetched ?? Date(timeIntervalSince1970: 0)) > (Calendar.autoupdatingCurrent.date(byAdding: .minute, value: 5, to: Date()) ?? Date())) { + fetch() + } + } + } +} + +/* struct GradesDetailView_Previews: PreviewProvider { + static var previews: some View { + GradesDetailView() + } +} */ diff --git a/Shared/Views/Details/MessageDetailView.swift b/Shared/Views/Details/MessageDetailView.swift new file mode 100644 index 0000000..b7f570a --- /dev/null +++ b/Shared/Views/Details/MessageDetailView.swift @@ -0,0 +1,103 @@ +// +// MessageDetailView.swift +// vulcan +// +// Created by royal on 27/06/2020. +// + +import SwiftUI +import Vulcan +import AppNotifications + +struct MessageDetailView: View { + var message: Vulcan.Message + + @State private var isComposeSheetPresented: Bool = false + + var body: some View { + ScrollView { + VStack(alignment: .leading) { + VStack(alignment: .leading) { + if let messageSender = message.tag == .sent ? message.recipients?.map(\.name).joined(separator: ",") : message.sender { + Text(messageSender) + .font(.headline) + .multilineTextAlignment(.leading) + .lineLimit(nil) + } + + Text(message.dateSent.formattedDateString(timeStyle: .medium, dateStyle: .full, context: .beginningOfSentence)) + .foregroundColor(.secondary) + .multilineTextAlignment(.leading) + .lineLimit(nil) + } + .padding(.bottom, 20) + + // Content + HStack { + Text(message.content.trimmingCharacters(in: .whitespacesAndNewlines)) + .lineLimit(nil) + .multilineTextAlignment(.leading) + Spacer() + } + .contentShape(Rectangle()) + .onTapGesture { + generateHaptic(.light) + UIPasteboard.general.string = message.content + } + + Spacer() + + // URLs + if (message.content.urls.count > 0) { + VStack(alignment: .leading) { + Text("Links") + .font(.title) + .bold() + + ForEach(message.content.urls, id: \.self) { (url) in + LinkPreview(url: url) + .frame(minHeight: 50, idealHeight: 70, maxHeight: 80) + .id(url.absoluteString) + } + } + .padding(.top) + } + } + .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity) + .padding(.horizontal) + .padding(.bottom) + } + .frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity) + .navigationBarTitle(Text(message.title)) + .toolbar { + // Reply button + ToolbarItem(placement: .navigationBarTrailing) { + Button(action: { + isComposeSheetPresented = true + }) { + Image(systemName: "arrowshape.turn.up.left") + .navigationBarButton(edge: .trailing) + } + } + } + .sheet(isPresented: $isComposeSheetPresented) { + ComposeMessageView(isPresented: $isComposeSheetPresented, message: .constant(message)) + } + .onAppear { + if (SettingsModel.shared.readMessageOnOpen && Vulcan.shared.currentUser != nil && !message.hasBeenRead) { + Vulcan.shared.moveMessage(message: message, to: .read) { error in + if let error = error { + generateHaptic(.error) + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + } + } + } +} + +struct MessageDetailView_Previews: PreviewProvider { + static var previews: some View { + MessageDetailView(message: Vulcan.Message(id: 0, sender: nil, senderID: 0, recipients: nil, title: "title", content: "content", dateSentEpoch: 0, dateReadEpoch: nil, status: "", folder: "", read: nil)) + } +} diff --git a/Shared/Views/GradesView.swift b/Shared/Views/GradesView.swift new file mode 100644 index 0000000..083cf9c --- /dev/null +++ b/Shared/Views/GradesView.swift @@ -0,0 +1,114 @@ +// +// GradesView.swift +// vulcan +// +// Created by royal on 24/06/2020. +// + +import SwiftUI +import Vulcan +import AppNotifications +import CoreSpotlight +import CoreServices + +/// Grades view, showing subject NavigationLinks to grades. +struct GradesView: View { + @EnvironmentObject var vulcan: Vulcan + @EnvironmentObject var settings: SettingsModel + #if os(iOS) + @Environment(\.horizontalSizeClass) private var horizontalSizeClass + #endif + @State private var selection: Vulcan.SubjectGrades? + + /// Refreshes the data + private func fetch() { + var requestsError: Error? + + vulcan.getGrades() { error in + requestsError = error + } + + vulcan.getEndOfTermGrades() { error in + requestsError = error + } + + if let error = requestsError { + generateHaptic(.error) + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + + /// Sidebar ViewBuilder + @ViewBuilder var body: some View { + List(selection: $selection) { + if (vulcan.grades.count > 0) { + ForEach(vulcan.grades) { (subject) in + NavigationLink(destination: GradesDetailView(subject: subject), tag: subject, selection: $selection) { + HStack { + VStack(alignment: .leading, spacing: 5) { + Text(subject.subject.name) + .font(.headline) + Text("\(subject.employee.name) \(subject.employee.surname)") + .font(.callout) + .foregroundColor(.secondary) + } + .padding(.trailing) + + Spacer() + + if subject.hasNewItems { + Image(systemName: "staroflife.fill") + .padding(.trailing, 5) + } + } + .padding(.vertical, 10) + } + .tag(subject.id) + .id(subject.id) + } + } else { + Text("No grades") + .opacity(0.5) + .multilineTextAlignment(.center) + .fullWidth() + } + } + .listStyle(InsetGroupedListStyle()) + .navigationTitle("Grades") + .toolbar { + // Refresh button + ToolbarItem(placement: .primaryAction) { + RefreshButton(loading: vulcan.dataState.grades.loading || vulcan.dataState.eotGrades.loading, iconName: "arrow.clockwise", edge: .trailing) { + generateHaptic(.light) + fetch() + } + } + } + .userActivity("\(Bundle.main.bundleIdentifier ?? "vulcan").gradesActivity") { activity in + activity.title = "Grades".localized + activity.isEligibleForPrediction = true + activity.isEligibleForSearch = true + activity.keywords = ["Grades".localized, "vulcan"] + + let attributes = CSSearchableItemAttributeSet(itemContentType: kUTTypeItem as String) + attributes.contentDescription = "See your grades".localized + activity.contentAttributeSet = attributes + } + .onAppear { + if AppState.networking.monitor.currentPath.isExpensive || vulcan.currentUser == nil { + return + } + + let nextFetch: Date = Calendar.autoupdatingCurrent.date(byAdding: .minute, value: 5, to: vulcan.dataState.grades.lastFetched ?? Date(timeIntervalSince1970: 0)) ?? Date() + if nextFetch <= Date() { + fetch() + } + } + } +} + +struct GradesView_Previews: PreviewProvider { + static var previews: some View { + GradesView() + } +} diff --git a/Shared/Views/HomeView.swift b/Shared/Views/HomeView.swift new file mode 100644 index 0000000..d823054 --- /dev/null +++ b/Shared/Views/HomeView.swift @@ -0,0 +1,388 @@ +// +// HomeView.swift +// vulcan +// +// Created by royal on 24/06/2020. +// + +import SwiftUI +import Vulcan +import AppNotifications +import CoreSpotlight +import CoreServices + +/// Home view, containing dashboard for user +struct HomeView: View { + @EnvironmentObject private var vulcan: Vulcan + + @AppStorage(UserDefaults.AppKeys.colorScheme.rawValue, store: .group) private var colorScheme: String = "Default" + @AppStorage(UserDefaults.AppKeys.colorizeGrades.rawValue, store: .group) private var colorizeGrades: Bool = true + + @State private var isComposeSheetPresented: Bool = false + @State private var messageToReply: Vulcan.Message? + + // MARK: Variables + var helloString: LocalizedStringKey { + let hour: Int = Calendar.autoupdatingCurrent.component(.hour, from: Date()) + var helloString: LocalizedStringKey = "HELLO : \(vulcan.currentUser?.name ?? "User")" + + if (hour >= 4 && hour < 13) { + helloString = "GOOD_MORNING : \(vulcan.currentUser?.name ?? "User")" + } else if (hour >= 13 && hour < 18) { + helloString = "GOOD_AFTERNOON : \(vulcan.currentUser?.name ?? "User")" + } else if ((hour >= 18 && hour < 24) || (hour >= 0 && hour < 4)) { + helloString = "GOOD_EVENING : \(vulcan.currentUser?.name ?? "User")" + } + + return helloString + } + + var currentLesson: Vulcan.ScheduleEvent? { + vulcan.schedule + .flatMap(\.events) + .filter { $0.isUserSchedule } + .first(where: { $0.isCurrent ?? false }) + } + + var nextLesson: Vulcan.ScheduleEvent? { + vulcan.schedule + .flatMap(\.events) + .filter { $0.isUserSchedule } + .first(where: { + guard let dateStarts = $0.dateStarts else { + return false + } + + return dateStarts > Date() + }) + } + + var newExams: [Vulcan.Exam] { + vulcan.tasks.exams + .filter { $0.date.endOfDay >= Date() } + } + + var newHomework: [Vulcan.Homework] { + vulcan.tasks.homework + .filter { $0.date.endOfDay >= Date() } + } + + var newMessages: [Vulcan.Message] { + vulcan.messages[.received]?.filter({ !$0.hasBeenRead }) ?? [] + } + + // MARK: Views + /// Divider view + private var divider: some View { + VStack { + RoundedRectangle(cornerRadius: 2, style: .circular).fill(Color.primary).opacity(0.03) + .frame(minWidth: .zero, maxWidth: .infinity, minHeight: 2, maxHeight: 2) + } + } + + /// Section containing greeting and current/next schedule events. + private var generalSection: some View { + Section { + VStack(alignment: .leading) { + // Welcome message + VStack(alignment: .leading, spacing: 4) { + Text(helloString) + .font(.title2) + .bold() + .allowsTightening(true) + .minimumScaleFactor(0.9) + + Text("DATE_CURRENTLY : \(Date().formattedDateString(timeStyle: .none, dateStyle: .full))") + .font(.headline) + .foregroundColor(.secondary) + .allowsTightening(true) + .minimumScaleFactor(0.9) + } + + // Lessons + Group { + // Current lesson + if let lesson = currentLesson { + divider + + VStack(alignment: .leading, spacing: 0) { + Text("Current lesson") + .font(.headline) + .foregroundColor(.secondary) + .padding(.bottom, 2) + Text("\(lesson.subjectName) (\(lesson.room))") + .font(.headline) + .lineLimit(2) + .padding(.bottom, 2) + Text("\((lesson.dateStarts ?? lesson.date).localizedTime) - \((lesson.dateEnds ?? lesson.date).localizedTime) • \(lesson.employee?.name ?? "Unknown employee") \(lesson.employee?.surname ?? "")") + .font(.callout) + .foregroundColor(.secondary) + .lineLimit(2) + } + } + + // Next lesson + if let lesson = nextLesson { + divider + + VStack(alignment: .leading, spacing: 0) { + Text("Next lesson") + .font(.headline) + .foregroundColor(.secondary) + .padding(.bottom, 2) + + Text("\(lesson.subjectName) (\(lesson.room))") + .font(.headline) + .lineLimit(2) + .padding(.bottom, 2) + + Group { + if (Calendar.autoupdatingCurrent.isDateInToday(lesson.date)) { + Text("\((lesson.dateStarts ?? lesson.date).localizedTime) - \((lesson.dateEnds ?? lesson.date).localizedTime) • \(lesson.employee?.name ?? "Unknown employee") \(lesson.employee?.surname ?? "")") + } else { + Text("\((lesson.dateStarts ?? lesson.date).formattedString(format: "EEEE").capitalingFirstLetter()), \((lesson.dateStarts ?? lesson.date).localizedTime) - \((lesson.dateEnds ?? lesson.date).localizedTime) • \(lesson.employee?.name ?? "Unknown employee") \(lesson.employee?.surname ?? "")") + } + } + .font(.callout) + .foregroundColor(.secondary) + .lineLimit(2) + } + } + + // No lessons + if (currentLesson == nil && nextLesson == nil) { + divider + Text("No lessons for now ☺️") + .font(.headline) + .opacity(0.35) + .padding(.vertical, 5) + } + } + } + .padding(.vertical, 5) + } + } + + /// Section containing new exams. + private var examsSection: some View { + Section(header: Text("Exams").textCase(.none)) { + if (newExams.count > 0) { + ForEach(newExams) { (task) in + TaskCell(task: task, isBigType: task.isBigType) + } + } else { + Text("Nothing in the near future") + .opacity(0.5) + .multilineTextAlignment(.center) + .fullWidth() + } + } + + } + + /// Section containing new homework tasks. + private var homeworkSection: some View { + Section(header: Text("Homework").textCase(.none)) { + if (newHomework.count > 0) { + ForEach(newHomework) { (task) in + TaskCell(task: task, isBigType: nil) + } + } else { + Text("Nothing in the near future") + .opacity(0.5) + .multilineTextAlignment(.center) + .fullWidth() + } + } + + } + + /// Section containing unread messages. + private var messagesSection: some View { + Section(header: Text("New messages").textCase(.none)) { + if (newMessages.count > 0) { + ForEach(newMessages) { message in + NavigationLink(destination: MessageDetailView(message: message)) { + MessageCell(message: message, isComposeSheetPresented: $isComposeSheetPresented, messageToReply: $messageToReply) + } + } + } else { + Text("No new messages") + .opacity(0.5) + .multilineTextAlignment(.center) + .fullWidth() + } + } + + } + + /// Section containing anticipated grades. + private var anticipatedGradesSection: some View { + Section(header: Text("Anticipated grades").textCase(.none)) { + if (vulcan.eotGrades.expected.isEmpty) { + Text("No grades") + .opacity(0.5) + .multilineTextAlignment(.center) + .fullWidth() + } else { + ForEach(vulcan.eotGrades.expected, id: \.subjectID) { (grade) in + FinalGradeCell(scheme: colorScheme, colorize: colorizeGrades, grade: grade) + .id("anticipatedGrade:\(grade.subjectID)") + } + } + } + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) + .loadingOverlay(vulcan.dataState.eotGrades.loading) + .contentShape(Rectangle()) + .onTapGesture(count: 2) { + generateHaptic(.light) + vulcan.getEndOfTermGrades() { error in + if let error = error { + generateHaptic(.error) + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + } + } + + /// Section containing final grades. + private var finalGradesSection: some View { + Section(header: Text("Final grades").textCase(.none)) { + if (vulcan.eotGrades.final.isEmpty) { + Text("No grades") + .opacity(0.5) + .multilineTextAlignment(.center) + .fullWidth() + } else { + ForEach(vulcan.eotGrades.final, id: \.subjectID) { (grade) in + FinalGradeCell(scheme: colorScheme, colorize: colorizeGrades, grade: grade) + .id("finalGrade:\(grade.subjectID)") + } + } + } + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) + .loadingOverlay(vulcan.dataState.eotGrades.loading) + .contentShape(Rectangle()) + .onTapGesture(count: 2) { + generateHaptic(.light) + vulcan.getEndOfTermGrades() { error in + if let error = error { + generateHaptic(.error) + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + } + } + + /// Section containing user notes. + private var notesSection: some View { + Section(header: Text("Notes").textCase(.none)) { + if (vulcan.notes.isEmpty) { + Text("Nothing found") + .opacity(0.5) + .multilineTextAlignment(.center) + .fullWidth() + } else { + ForEach(vulcan.notes) { (note) in + NoteCell(note: note) + } + } + } + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) + .loadingOverlay(vulcan.dataState.notes.loading) + .contentShape(Rectangle()) + .onTapGesture(count: 2) { + generateHaptic(.light) + vulcan.getNotes() { error in + if let error = error { + generateHaptic(.error) + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + } + } + + /// View displayed when user is logged in. + private var loggedInView: some View { + List { + // General + generalSection + + // Tasks - Exams + examsSection + + // Tasks - Homework + homeworkSection + + // Messages + messagesSection + + // Anticipated grades + anticipatedGradesSection + + // Final grades + finalGradesSection + + // Notes + notesSection + } + .listStyle(InsetGroupedListStyle()) + .sheet(isPresented: $isComposeSheetPresented, content: { ComposeMessageView(isPresented: $isComposeSheetPresented, message: $messageToReply) }) + .userActivity("\(Bundle.main.bundleIdentifier ?? "vulcan").todayActivity") { activity in + activity.title = "Today".localized + activity.isEligibleForPrediction = true + activity.isEligibleForSearch = true + activity.keywords = ["Today".localized, "vulcan"] + + let attributes = CSSearchableItemAttributeSet(itemContentType: kUTTypeItem as String) + attributes.contentDescription = "Your summary for today.".localized + activity.contentAttributeSet = attributes + } + .onAppear { + if AppState.networking.monitor.currentPath.isExpensive || vulcan.currentUser == nil { + return + } + + // Notes + let notesNextFetch: Date = Calendar.autoupdatingCurrent.date(byAdding: .minute, value: 5, to: vulcan.dataState.notes.lastFetched ?? Date(timeIntervalSince1970: 0)) ?? Date() + if notesNextFetch <= Date() { + vulcan.getNotes() { error in + if let error = error { + generateHaptic(.error) + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + } + + // EOT Grades + let eotGradesNextFetch: Date = Calendar.autoupdatingCurrent.date(byAdding: .minute, value: 5, to: vulcan.dataState.eotGrades.lastFetched ?? Date(timeIntervalSince1970: 0)) ?? Date() + if eotGradesNextFetch <= Date() { + vulcan.getEndOfTermGrades() { error in + if let error = error { + generateHaptic(.error) + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + } + } + } + + var body: some View { + Group { + if (vulcan.currentUser != nil) { + loggedInView + } else { + Text("Not logged in") + .foregroundColor(.secondary) + } + } + .navigationTitle(Text("Home")) + // .navigationViewStyle(StackNavigationViewStyle()) + } +} + +struct HomeView_Previews: PreviewProvider { + static var previews: some View { + HomeView() + } +} diff --git a/Shared/Views/MessagesView.swift b/Shared/Views/MessagesView.swift new file mode 100644 index 0000000..e37c0c1 --- /dev/null +++ b/Shared/Views/MessagesView.swift @@ -0,0 +1,217 @@ +// +// MessagesView.swift +// vulcan +// +// Created by royal on 24/06/2020. +// + +import SwiftUI +import Vulcan +import AppNotifications +import CoreSpotlight +import CoreServices + +/// View containing the received, sent and deleted messages. +struct MessagesView: View { + @EnvironmentObject var vulcan: Vulcan + #if os(iOS) + @Environment(\.horizontalSizeClass) private var horizontalSizeClass + #endif + + @Binding var tag: Vulcan.MessageTag + + @State private var date: Date = Date() + @State private var selection: Vulcan.Message? + @State private var isComposeSheetPresented: Bool = false + @State private var messageToReply: Vulcan.Message? + + /// Loads the data for the current month. + private func fetch(timeIntervalSince1970: Double? = nil) { + if (vulcan.dataState.messages[tag]?.loading ?? true) { + return + } + + let previousDate: Date = self.date + let startDate: Date = self.date.startOfMonth + let endDate: Date = self.date.endOfMonth + + vulcan.getMessages(tag: tag, isPersistent: (self.date.startOfMonth == Date().startOfMonth), from: startDate, to: endDate) { error in + if let error = error { + generateHaptic(.error) + self.date = previousDate + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + } + + /// Removes the selected messages + /// - Parameter indexSet: Indexes of the messages + private func delete(indexSet: IndexSet) { + generateHaptic(.medium) + for index in indexSet { + if (index <= vulcan.messages.combined.filter({ $0.tag == self.tag }).count) { + let message: Vulcan.Message = vulcan.messages.combined.filter({ $0.tag == self.tag })[index] + vulcan.moveMessage(message: message, to: .deleted) { error in + if let error = error { + generateHaptic(.error) + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + } + } + } + + private func onAppear() { + if (AppState.networking.monitor.currentPath.isExpensive || vulcan.currentUser == nil) { + return + } + + if (!(vulcan.dataState.messages[tag]?.fetched ?? false) || (vulcan.dataState.messages[tag]?.lastFetched ?? Date(timeIntervalSince1970: 0)) > (Calendar.autoupdatingCurrent.date(byAdding: .minute, value: 5, to: Date()) ?? Date())) { + fetch() + } + } + + /// Date picker + private var datePicker: some View { + DatePicker("Date", selection: $date, displayedComponents: .date) + .datePickerStyle(CompactDatePickerStyle()) + .labelsHidden() + .onChange(of: date.timeIntervalSince1970, perform: fetch) + } + + /// Button used to change current messages folder. + private var folderButton: some View { + Menu(content: { + Section { + Button(action: { + messageToReply = nil + isComposeSheetPresented = true + }) { + Label("New", systemImage: "square.and.pencil") + } + } + + Section(header: Text("Folders")) { + // Received + Button(action: { + tag = .received + fetch() + }) { + Label("Received", systemImage: tag == .received ? "tray.fill" : "tray") + } + + // Sent + Button(action: { + tag = .sent + fetch() + }) { + Label("Sent", systemImage: tag == .sent ? "paperplane.fill" : "paperplane") + } + + // Deleted + Button(action: { + tag = .deleted + fetch() + }) { + Label("Deleted", systemImage: tag == .deleted ? "trash.fill" : "trash") + } + } + }) { + Image(systemName: "ellipsis.circle") + } + } + + /// Button used to refresh current messages. + private var refreshButton: some View { + RefreshButton(loading: (vulcan.dataState.messages[tag]?.loading ?? false), progressValue: vulcan.dataState.messages[tag]?.progress, iconName: "arrow.clockwise", edge: .trailing) { + generateHaptic(.light) + fetch() + } + } + + private var content: some View { + List { + if ((vulcan.messages[tag] ?? []).isEmpty) { + Text("No messages found") + .opacity(0.5) + .multilineTextAlignment(.center) + .fullWidth() + } else { + ForEach(vulcan.messages[tag] ?? []) { message in + NavigationLink(destination: MessageDetailView(message: message)) { + MessageCell(message: message, isComposeSheetPresented: $isComposeSheetPresented, messageToReply: $messageToReply) + } + } + .onDelete(enabled: (tag == .received || tag == .sent), perform: delete) + } + } + .listStyle(InsetGroupedListStyle()) + .onAppear { + if AppState.networking.monitor.currentPath.isExpensive || vulcan.currentUser == nil { + return + } + + let nextFetch: Date = Calendar.autoupdatingCurrent.date(byAdding: .minute, value: 5, to: vulcan.dataState.messages[tag]?.lastFetched ?? Date(timeIntervalSince1970: 0)) ?? Date() + if nextFetch <= Date() { + fetch() + } + } + } + + /// Sidebar ViewBuilder + @ViewBuilder var body: some View { + content + .navigationTitle(Text(LocalizedStringKey(tag.rawValue))) + .sheet(isPresented: $isComposeSheetPresented) { + ComposeMessageView(isPresented: $isComposeSheetPresented, message: $messageToReply) + } + .toolbar { + // Date picker + ToolbarItemGroup(placement: .cancellationAction) { + datePicker + + ProgressView(value: vulcan.dataState.messages[tag]?.progress) + .transition(.opacity) + .animation(.easeInOut) + .opacity((vulcan.dataState.messages[tag]?.loading ?? false) ? 1 : 0) + } + + // Menu + New message button + #if os(iOS) + ToolbarItem(placement: .primaryAction) { + folderButton + .navigationBarButton(edge: .trailing) + + /* if horizontalSizeClass == .compact { + folderButton + .navigationBarButton(edge: .trailing) + } else { + Button(action: { + messageToReply = nil + isComposeSheetPresented = true + }) { + Image(systemName: "square.and.pencil") + } + .navigationBarButton(edge: .trailing) + } */ + } + #endif + } + .userActivity("\(Bundle.main.bundleIdentifier ?? "vulcan").messagesActivity") { activity in + activity.title = "Messages".localized + activity.isEligibleForPrediction = true + activity.isEligibleForSearch = true + activity.keywords = ["Messages".localized, "vulcan"] + + let attributes = CSSearchableItemAttributeSet(itemContentType: kUTTypeItem as String) + attributes.contentDescription = "See your received messages".localized + activity.contentAttributeSet = attributes + } + } +} + +struct MessagesView_Previews: PreviewProvider { + static var previews: some View { + MessagesView(tag: .constant(.received)) + } +} diff --git a/Shared/Views/Navigation/AppSidebarNavigation.swift b/Shared/Views/Navigation/AppSidebarNavigation.swift new file mode 100644 index 0000000..2e591cb --- /dev/null +++ b/Shared/Views/Navigation/AppSidebarNavigation.swift @@ -0,0 +1,108 @@ +// +// AppSidebarNavigation.swift +// vulcan +// +// Created by royal on 25/06/2020. +// + +import SwiftUI +import Vulcan + +struct AppSidebarNavigation: View { + @EnvironmentObject var vulcan: Vulcan + @EnvironmentObject var settings: SettingsModel + // @Binding var currentTab: Set + + private var sidebar: some View { + List { + // Home + NavigationLink(destination: HomeView()) { + Label("Home", systemImage: "house") + } + .accessibility(label: Text("Home")) + .tag(Tab.home) + + // Grades + NavigationLink(destination: GradesView()) { + Label("Grades", systemImage: "rosette") + } + .accessibility(label: Text("Grades")) + .tag(Tab.grades) + + // Schedule + NavigationLink(destination: ScheduleView()) { + Label("Schedule", systemImage: "calendar") + } + .accessibility(label: Text("Schedule")) + .tag(Tab.schedule) + + // Tasks + NavigationLink(destination: TasksView()) { + Label("Tasks", systemImage: "doc.on.clipboard") + } + .accessibility(label: Text("Tasks")) + .tag(Tab.tasks) + + // Messages + Section(header: Text("Messages").textCase(.none)) { + // Received + NavigationLink(destination: MessagesView(tag: .constant(.received))) { + Label("Received", systemImage: "envelope") + } + .accessibility(label: Text("Received messages")) + .tag(Tab.messages) + + // Sent + NavigationLink(destination: MessagesView(tag: .constant(.sent))) { + Label("Sent", systemImage: "paperplane") + } + .accessibility(label: Text("Sent messages")) + .tag(Tab.messages) + + // Deleted + NavigationLink(destination: MessagesView(tag: .constant(.deleted))) { + Label("Deleted", systemImage: "trash") + } + .accessibility(label: Text("Deleted messages")) + .tag(Tab.messages) + } + + Divider() + + // Settings + NavigationLink(destination: SettingsView()) { + Label("Settings", systemImage: "gear") + } + .accessibility(label: Text("Settings")) + .tag(Tab.settings) + } + .listStyle(SidebarListStyle()) + .navigationTitle(Text("vulcan")) + } + + var body: some View { + NavigationView { + sidebar + + HomeView() + .tag(Tab.home) + + #if os(macOS) + Text("Nothing selected") + .opacity(0.5) + .frame(maxWidth: .infinity, maxHeight: .infinity) + .toolbar { Spacer() } + #else + Text("Nothing selected") + .opacity(0.5) + .frame(maxWidth: .infinity, maxHeight: .infinity) + #endif + } + } +} + +struct AppSidebarNavigation_Previews: PreviewProvider { + static var previews: some View { + AppSidebarNavigation() + } +} diff --git a/Shared/Views/Navigation/AppTabNavigation.swift b/Shared/Views/Navigation/AppTabNavigation.swift new file mode 100644 index 0000000..f0105dd --- /dev/null +++ b/Shared/Views/Navigation/AppTabNavigation.swift @@ -0,0 +1,93 @@ +// +// AppTabNavigation.swift +// vulcan +// +// Created by royal on 25/06/2020. +// + +import SwiftUI +import Vulcan + +struct AppTabNavigation: View { + @Binding var currentTab: Tab + @State private var messagesFolder: Vulcan.MessageTag = .received + + var body: some View { + TabView(selection: $currentTab) { + // Home + NavigationView { + #if os(OSX) + HomeView() + #else + HomeView() + .navigationBarItems(trailing: NavigationLink(destination: SettingsView()) { + Image(systemName: "gear") + .navigationBarButton(edge: .trailing) + }) + #endif + } + .tabItem { + Label("Home", systemImage: "house.fill") + .accessibility(label: Text("Home")) + } + .tag(Tab.home) + .navigationViewStyle(StackNavigationViewStyle()) + + // Grades + NavigationView { + GradesView() + + Text("Nothing selected") + .opacity(0.3) + } + .tabItem { + Label("Grades", systemImage: "rosette") + .accessibility(label: Text("Grades")) + } + .tag(Tab.grades) + .navigationViewStyle(DoubleColumnNavigationViewStyle()) + + // Schedule + NavigationView { + ScheduleView() + } + .tabItem { + Label("Schedule", systemImage: "calendar") + .accessibility(label: Text("Schedule")) + } + .tag(Tab.schedule) + .navigationViewStyle(StackNavigationViewStyle()) + + // Tasks + NavigationView { + TasksView() + } + .tabItem { + Label("Tasks", systemImage: "doc.on.clipboard.fill") + .accessibility(label: Text("Tasks")) + } + .tag(Tab.tasks) + .navigationViewStyle(StackNavigationViewStyle()) + + // Messages + NavigationView { + MessagesView(tag: $messagesFolder) + + Text("Nothing selected") + .opacity(0.3) + } + .tabItem { + Label("Messages", systemImage: "envelope.fill") + .accessibility(label: Text("Messages")) + } + .tag(Tab.messages) + .navigationViewStyle(DoubleColumnNavigationViewStyle()) + } + } +} + +struct AppTabNavigation_Previews: PreviewProvider { + static var previews: some View { + AppTabNavigation(currentTab: .constant(.home)) + } +} diff --git a/Shared/Views/OnboardingView.swift b/Shared/Views/OnboardingView.swift new file mode 100644 index 0000000..be7c0b8 --- /dev/null +++ b/Shared/Views/OnboardingView.swift @@ -0,0 +1,113 @@ +// +// OnboardingView.swift +// vulcan +// +// Created by royal on 04/05/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import SwiftUI +import Vulcan + +fileprivate struct TitleView: View { + var body: some View { + VStack { + Image("vulcan") + .resizable() + .aspectRatio(contentMode: .fit) + .frame(width: 130, alignment: .center) + .accessibility(hidden: true) + .padding(5) + + Text("Welcome to") + .font(.largeTitle) + .bold() + + Text("vulcan") + .font(.largeTitle) + .bold() + .foregroundColor(.accentColor) + } + } +} + +fileprivate struct InformationDetailView: View { + var title: LocalizedStringKey = "" + var subtitle: LocalizedStringKey = "" + var imageName: String = "" + + var body: some View { + HStack(alignment: .center) { + Image(systemName: imageName) + .font(.largeTitle) + .foregroundColor(.accentColor) + .padding() + .accessibility(hidden: true) + + VStack(alignment: .leading) { + Text(title) + .font(.headline) + .foregroundColor(.primary) + .accessibility(addTraits: .isHeader) + .lineLimit(2) + + Text(subtitle) + .font(.body) + .foregroundColor(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + .padding(.top) + } +} + +fileprivate struct InformationContainerView: View { + var body: some View { + VStack(alignment: .leading) { + InformationDetailView(title: "ONBOARDING_FUNCTION1_TITLE", subtitle: "ONBOARDING_FUNCTION1_DESCRIPTION", imageName: "command") + InformationDetailView(title: "ONBOARDING_FUNCTION2_TITLE", subtitle: "ONBOARDING_FUNCTION2_DESCRIPTION", imageName: "bell.fill") + InformationDetailView(title: "ONBOARDING_FUNCTION3_TITLE", subtitle: "ONBOARDING_FUNCTION3_DESCRIPTION", imageName: "heart.fill") + } + .padding(.horizontal) + } +} + +/// Onboarding, displayed on first launch, hosting SetupView +struct OnboardingView: View { + @Binding var isPresented: Bool + @State private var showSetup: Bool = false + + var body: some View { + VStack(alignment: .center) { + if (!showSetup) { + VStack { + Spacer() + TitleView() + Spacer() + InformationContainerView() + Spacer() + Button(action: { + generateHaptic(.light) + withAnimation { + showSetup = true + } + }) { + Text("Continue") + .buttonModifier(color: Color.accentColor) + } + } + .padding() + .transition(.asymmetric(insertion: .move(edge: .leading), removal: .move(edge: .leading))) + } else { + SetupView(isPresented: $showSetup, isParentPresented: $isPresented, hasParent: true) + .transition(.move(edge: .trailing)) + } + } + } +} + +struct OnboardingView_Previews: PreviewProvider { + static var previews: some View { + OnboardingView(isPresented: .constant(true)) + } +} diff --git a/Shared/Views/ScheduleView.swift b/Shared/Views/ScheduleView.swift new file mode 100644 index 0000000..5bbf43a --- /dev/null +++ b/Shared/Views/ScheduleView.swift @@ -0,0 +1,149 @@ +// +// ScheduleView.swift +// vulcan +// +// Created by royal on 24/06/2020. +// + +import SwiftUI +import Vulcan +import AppNotifications +import CoreSpotlight +import CoreServices + +/// View containing schedule for the current week. +struct ScheduleView: View { + @EnvironmentObject var vulcan: Vulcan + + @AppStorage(UserDefaults.AppKeys.showAllScheduleEvents.rawValue, store: .group) public var showAllScheduleEvents: Bool = false + @AppStorage(UserDefaults.AppKeys.filterSchedule.rawValue, store: .group) private var filterSchedule: Bool = false + + @State private var date: Date = Date() + + /// Loads the data for the current week. + private func fetch(timeIntervalSince1970: Double? = nil) { + if vulcan.dataState.schedule.loading { + return + } + + let previousDate: Date = self.date + guard let startDate: Date = date.startOfWeek, let endDate: Date = date.endOfWeek else { + return + } + + vulcan.getSchedule(isPersistent: startDate >= Date().startOfWeek ?? Date(), from: startDate, to: endDate) { error in + if let error = error { + generateHaptic(.error) + self.date = previousDate + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + } + + /// Date picker + private var datePicker: some View { + DatePicker("Date", selection: $date, displayedComponents: .date) + .datePickerStyle(CompactDatePickerStyle()) + .labelsHidden() + .onChange(of: date.timeIntervalSince1970, perform: fetch) + } + + /// View displayed when there are any lessons. + private var lessonsList: some View { + ForEach(vulcan.schedule) { day in + if (filterSchedule ? Calendar.autoupdatingCurrent.isDate(day.date, inSameDayAs: date) : true) { + Section(header: Text(day.date.formattedDateString(dateStyle: .full, context: .beginningOfSentence)).textCase(.none)) { + ForEach(day.events.filter({ showAllScheduleEvents ? true : $0.isUserSchedule })) { event in + ScheduleEventCell(event: event, showAllScheduleEvents: showAllScheduleEvents) + } + } + } + } + } + + var body: some View { + List { + // Schedule + if (filterSchedule ? vulcan.schedule.filter({ Calendar.autoupdatingCurrent.isDate($0.date, inSameDayAs: date) }).isEmpty : vulcan.schedule.isEmpty) { + Text(filterSchedule ? "No lessons for this day 😊" : "No lessons for this week 😊") + .opacity(0.5) + .multilineTextAlignment(.center) + .fullWidth() + } else { + lessonsList + } + } + .listStyle(InsetGroupedListStyle()) + .navigationViewStyle(StackNavigationViewStyle()) + .navigationTitle(Text("Schedule")) + .toolbar { + // Date picker + ToolbarItem(placement: .cancellationAction) { + datePicker + } + + // Refresh button + ToolbarItem(placement: .primaryAction) { + RefreshButton(loading: vulcan.dataState.schedule.loading, iconName: "arrow.clockwise", edge: .trailing) { + generateHaptic(.light) + fetch() + } + } + } + .userActivity("\(Bundle.main.bundleIdentifier ?? "vulcan").scheduleActivity") { activity in + activity.title = "Schedule".localized + activity.isEligibleForPrediction = true + activity.isEligibleForSearch = true + activity.keywords = [ + "Schedule".localized, + "Lessons".localized, + "vulcan" + ] + + let attributes = CSSearchableItemAttributeSet(itemContentType: kUTTypeItem as String) + attributes.contentDescription = "Displays your schedule".localized + activity.contentAttributeSet = attributes + } + .userActivity("\(Bundle.main.bundleIdentifier ?? "vulcan").nextScheduleEventActivity") { activity in + guard let event = vulcan.schedule.flatMap(\.events).first(where: { $0.isUserSchedule && $0.dateStarts ?? $0.date >= Date() }), + let dateStarts = event.dateStarts, + let dateEnds = event.dateEnds else { + return + } + + activity.title = event.subjectName + activity.isEligibleForPrediction = true + activity.isEligibleForSearch = true + activity.keywords = [ + "Schedule".localized, + "Next lesson".localized + ] + activity.expirationDate = dateEnds + activity.persistentIdentifier = event.id + + let attributes = CSSearchableItemAttributeSet(itemContentType: kUTTypeItem as String) + attributes.startDate = dateStarts + attributes.endDate = dateEnds + attributes.contentDescription = "\(event.employeeFullName ?? "Unknown employee".localized) • \(event.room)" + attributes.identifier = event.id + attributes.relatedUniqueIdentifier = event.id + activity.contentAttributeSet = attributes + } + .onAppear { + if AppState.networking.monitor.currentPath.isExpensive || vulcan.currentUser == nil { + return + } + + let nextFetch: Date = Calendar.autoupdatingCurrent.date(byAdding: .minute, value: 5, to: vulcan.dataState.schedule.lastFetched ?? Date(timeIntervalSince1970: 0)) ?? Date() + if nextFetch <= Date() { + fetch() + } + } + } +} + +struct ScheduleView_Previews: PreviewProvider { + static var previews: some View { + ScheduleView() + } +} diff --git a/Shared/Views/SetupView.swift b/Shared/Views/SetupView.swift new file mode 100644 index 0000000..f56cb98 --- /dev/null +++ b/Shared/Views/SetupView.swift @@ -0,0 +1,146 @@ +// +// SetupView.swift +// Harbour +// +// Created by royal on 22/03/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import SwiftUI +import Vulcan + +/// View allowing user to log in +struct SetupView: View { + @Binding var isPresented: Bool + @Binding var isParentPresented: Bool + let hasParent: Bool + + @State private var token: String = "" + @State private var symbol: String = "" + @State private var pin: String = "" + + @State private var buttonColor: Color = Color.accentColor + @State private var buttonText: String = "Log in" + + private var cellBackground: some View { + RoundedRectangle(cornerRadius: 10) + .fill(Color.secondary.opacity(0.05)) + } + + private func setButton(color: Color = Color.accentColor, text: String = "Log in") { + withAnimation { + buttonColor = color + buttonText = text + + DispatchQueue.main.asyncAfter(deadline: .now() + 3) { + buttonColor = Color.accentColor + buttonText = "Log in" + } + } + } + + var body: some View { + VStack(alignment: .center) { + Spacer() + + Text("SETUP_TITLE") + .font(.largeTitle) + .bold() + + Spacer() + + // Token + VStack(alignment: .leading) { + TextField("Token", text: $token, onCommit: { + let string = token + token = token.uppercased().trimmingCharacters(in: .whitespacesAndNewlines) + if (token != string) { + generateHaptic(.light) + } + }) + .padding(12) + .background(cellBackground) + .keyboardType(.alphabet) + // .textCase(.uppercase) + .disableAutocorrection(true) + } + .padding() + + // Symbol + VStack(alignment: .leading) { + TextField("Symbol", text: $symbol, onCommit: { + let string = symbol + symbol = symbol.lowercased().trimmingCharacters(in: .whitespacesAndNewlines) + if (symbol != string) { + generateHaptic(.light) + } + }) + .padding(12) + .background(cellBackground) + .keyboardType(.alphabet) + .disableAutocorrection(true) + } + .padding() + + // PIN + VStack(alignment: .leading) { + TextField("PIN", text: $pin) + .padding(12) + .background(cellBackground) + .keyboardType(.numberPad) + .disableAutocorrection(true) + } + .padding() + + Spacer() + + Button(action: { + if ( + token.isReallyEmpty || + symbol.isReallyEmpty || + pin.isReallyEmpty + ) { + generateHaptic(.error) + setButton(color: Color(UIColor.systemRed), text: "Fill all fields!") + } else { + generateHaptic(.light) + setButton(text: "Logging in...") + Vulcan.shared.login(token: token.trimmingCharacters(in: .whitespacesAndNewlines), symbol: symbol.trimmingCharacters(in: .whitespacesAndNewlines), pin: Int(pin) ?? 0) { success, error in + isParentPresented = !success + if (!success) { + setButton(color: Color(UIColor.systemRed), text: error?.localizedDescription ?? "Error logging in") + generateHaptic(.error) + } + } + } + }) { + Text(LocalizedStringKey(buttonText)) + .multilineTextAlignment(.center) + .buttonModifier(color: Color.accentColor) + } + .keyboardShortcut(.defaultAction) + .id("Button:" + buttonText) + .padding(.horizontal) + + Button(action: { + withAnimation { + isPresented = false + } + }) { + Text((hasParent ? "Go back" : "Nevermind")) + .font(.body) + .bold() + .padding() + } + .padding(.horizontal) + } + .padding(.vertical) + .contentShape(Rectangle()) + } +} + +struct SetupView_Previews: PreviewProvider { + static var previews: some View { + SetupView(isPresented: .constant(true), isParentPresented: .constant(true), hasParent: true) + } +} diff --git a/Shared/Views/TasksView.swift b/Shared/Views/TasksView.swift new file mode 100644 index 0000000..e91fe17 --- /dev/null +++ b/Shared/Views/TasksView.swift @@ -0,0 +1,134 @@ +// +// TasksView.swift +// vulcan +// +// Created by royal on 24/06/2020. +// + +import SwiftUI +import Vulcan +import AppNotifications +import CoreSpotlight +import CoreServices + +/// View containing current user tasks. +struct TasksView: View { + @EnvironmentObject var vulcan: Vulcan + @EnvironmentObject var settings: SettingsModel + #if os(iOS) + @Environment(\.horizontalSizeClass) private var horizontalSizeClass + #endif + + @State private var date: Date = Date() + + /// Loads the data for the current month. + private func fetch(timeIntervalSince1970: Double? = nil) { + if (vulcan.dataState.tasks.loading) { + return + } + + let previousDate: Date = self.date + let startDate: Date = date.startOfMonth + let endDate: Date = date.endOfMonth + + vulcan.getTasks(isPersistent: self.date.startOfMonth <= Date() && self.date.endOfMonth >= Date(), from: startDate, to: endDate) { error in + if let error = error { + generateHaptic(.error) + self.date = previousDate + AppNotifications.shared.notification = .init(error: error.localizedDescription) + } + } + } + + private var exams: [Vulcan.Exam] { + vulcan.tasks.exams + .filter { $0.date >= Date().startOfMonth && $0.date <= Date().endOfMonth } + } + + private var homework: [Vulcan.Homework] { + vulcan.tasks.homework + .filter { $0.date >= Date().startOfMonth && $0.date <= Date().endOfMonth } + } + + /// Date picker + private var datePicker: some View { + DatePicker("Date", selection: $date, displayedComponents: .date) + .datePickerStyle(CompactDatePickerStyle()) + .labelsHidden() + .onChange(of: date.timeIntervalSince1970, perform: fetch) + } + + var body: some View { + List { + // Exams + Section(header: Text("Exams").textCase(.none)) { + if (exams.count > 0) { + ForEach(exams) { task in + TaskCell(task: task, isBigType: task.isBigType) + } + } else { + Text("No exams for this month 😊") + .opacity(0.5) + .multilineTextAlignment(.center) + .fullWidth() + } + } + + // Homework + Section(header: Text("Homework").textCase(.none)) { + if (homework.count > 0) { + ForEach(homework) { task in + TaskCell(task: task, isBigType: nil) + } + } else { + Text("No homework for this month 😊") + .opacity(0.5) + .multilineTextAlignment(.center) + .fullWidth() + } + } + } + .listStyle(InsetGroupedListStyle()) + .navigationTitle(Text("Tasks")) + .toolbar { + // Date picker + ToolbarItem(placement: .cancellationAction) { + datePicker + } + + // Refresh button + ToolbarItem(placement: .primaryAction) { + RefreshButton(loading: vulcan.dataState.tasks.loading, iconName: "arrow.clockwise", edge: .trailing) { + generateHaptic(.light) + fetch() + } + } + } + .userActivity("\(Bundle.main.bundleIdentifier ?? "vulcan").tasksActivity") { activity in + activity.title = "Tasks".localized + activity.isEligibleForPrediction = true + activity.isEligibleForSearch = true + activity.keywords = ["Tasks".localized, "vulcan"] + + let attributes = CSSearchableItemAttributeSet(itemContentType: kUTTypeItem as String) + attributes.contentDescription = "Displays your upcoming exams and homework".localized + activity.contentAttributeSet = attributes + } + .onAppear { + if AppState.networking.monitor.currentPath.isExpensive || vulcan.currentUser == nil { + return + } + + let nextFetch: Date = Calendar.autoupdatingCurrent.date(byAdding: .minute, value: 5, to: vulcan.dataState.tasks.lastFetched ?? Date(timeIntervalSince1970: 0)) ?? Date() + if nextFetch <= Date() { + fetch() + } + } + } +} + +struct TasksView_Previews: PreviewProvider { + static var previews: some View { + TasksView() + } +} diff --git a/Shared/Views/UIViewRepresentable/LinkPreview.swift b/Shared/Views/UIViewRepresentable/LinkPreview.swift new file mode 100644 index 0000000..c83a43b --- /dev/null +++ b/Shared/Views/UIViewRepresentable/LinkPreview.swift @@ -0,0 +1,32 @@ +// +// LinkPreview.swift +// vulcan +// +// Created by royal on 24/06/2020. +// + +import SwiftUI +import LinkPresentation + +/// LPLinkView wrapper +struct LinkPreview: UIViewRepresentable { + var url: URL + + func makeUIView(context: Context) -> LPLinkView { + let view = LPLinkView(url: url) + let provider = LPMetadataProvider() + + provider.startFetchingMetadata(for: url) { (metadata, error) in + if let metadata = metadata { + DispatchQueue.main.async { + view.metadata = metadata + view.sizeToFit() + } + } + } + + return view + } + + func updateUIView(_ uiView: LPLinkView, context: UIViewRepresentableContext) { } +} diff --git a/Shared/vulcanApp.swift b/Shared/vulcanApp.swift new file mode 100644 index 0000000..d4c7de2 --- /dev/null +++ b/Shared/vulcanApp.swift @@ -0,0 +1,78 @@ +// +// vulcanApp.swift +// Shared +// +// Created by royal on 24/06/2020. +// + +import SwiftUI +import Vulcan +import AppNotifications + +@main +struct vulcanApp: App { + @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate + @Environment(\.scenePhase) private var scenePhase + @StateObject private var vulcan: Vulcan = Vulcan.shared + @StateObject private var settings: SettingsModel = SettingsModel.shared + @StateObject private var appNotifications: AppNotifications = AppNotifications.shared + // @StateObject private var appState: AppState = AppState.shared + + @State private var currentTab: Tab = .home + + @SceneBuilder var body: some Scene { + WindowGroup { + ContentView(currentTab: $currentTab) + .environment(\.managedObjectContext, CoreDataModel.shared.persistentContainer.viewContext) + .environmentObject(vulcan) + .environmentObject(settings) + .environmentObject(appNotifications) + // .environmentObject(appState) + .defaultAppStorage(.group) + .notificationOverlay(appNotifications) + .onChange(of: scenePhase) { (newPhase) in + switch newPhase { + case .active: + break + case .inactive: + break + case .background: + if vulcan.currentUser != nil { + appDelegate.scheduleBackgroundRefresh() + } + @unknown default: + break + } + } + .onOpenURL { url in + switch (url.host) { + case "schedule": currentTab = .schedule + default: break + } + } + .onContinueUserActivity("\(Bundle.main.bundleIdentifier ?? "vulcan").todayActivity") { activity in + currentTab = .home + } + .onContinueUserActivity("\(Bundle.main.bundleIdentifier ?? "vulcan").gradesActivity") { activity in + currentTab = .grades + } + .onContinueUserActivity("\(Bundle.main.bundleIdentifier ?? "vulcan").scheduleActivity") { activity in + currentTab = .schedule + } + .onContinueUserActivity("\(Bundle.main.bundleIdentifier ?? "vulcan").tasksActivity") { activity in + currentTab = .tasks + } + .onContinueUserActivity("\(Bundle.main.bundleIdentifier ?? "vulcan").messagesActivity") { activity in + currentTab = .messages + } + } + + #if os(macOS) + Settings { + MacSettingsView() + .environment(\.managedObjectContext, CoreDataModel.shared.persistentContainer.viewContext) + .defaultAppStorage(.group) + } + #endif + } +} diff --git a/WatchKit Extension/Assets.xcassets/AccentColor.colorset/Contents.json b/WatchKit Extension/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000..68dc4ff --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,20 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "srgb", + "components" : { + "alpha" : "1.000", + "blue" : "0.204", + "green" : "0.235", + "red" : "1.000" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Assets.xcassets/Complication.complicationset/Circular.imageset/Contents.json b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Circular.imageset/Contents.json new file mode 100644 index 0000000..ed7de25 --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Circular.imageset/Contents.json @@ -0,0 +1,28 @@ +{ + "images" : [ + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : "<=145" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">161" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">145" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">183" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Assets.xcassets/Complication.complicationset/Contents.json b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Contents.json new file mode 100644 index 0000000..e8b3252 --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Contents.json @@ -0,0 +1,53 @@ +{ + "assets" : [ + { + "filename" : "Circular.imageset", + "idiom" : "watch", + "role" : "circular" + }, + { + "filename" : "Extra Large.imageset", + "idiom" : "watch", + "role" : "extra-large" + }, + { + "filename" : "Graphic Bezel.imageset", + "idiom" : "watch", + "role" : "graphic-bezel" + }, + { + "filename" : "Graphic Circular.imageset", + "idiom" : "watch", + "role" : "graphic-circular" + }, + { + "filename" : "Graphic Corner.imageset", + "idiom" : "watch", + "role" : "graphic-corner" + }, + { + "filename" : "Graphic Extra Large.imageset", + "idiom" : "watch", + "role" : "graphic-extra-large" + }, + { + "filename" : "Graphic Large Rectangular.imageset", + "idiom" : "watch", + "role" : "graphic-large-rectangular" + }, + { + "filename" : "Modular.imageset", + "idiom" : "watch", + "role" : "modular" + }, + { + "filename" : "Utilitarian.imageset", + "idiom" : "watch", + "role" : "utilitarian" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Assets.xcassets/Complication.complicationset/Extra Large.imageset/Contents.json b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Extra Large.imageset/Contents.json new file mode 100644 index 0000000..ed7de25 --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Extra Large.imageset/Contents.json @@ -0,0 +1,28 @@ +{ + "images" : [ + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : "<=145" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">161" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">145" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">183" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Bezel.imageset/Contents.json b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Bezel.imageset/Contents.json new file mode 100644 index 0000000..9685a7f --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Bezel.imageset/Contents.json @@ -0,0 +1,18 @@ +{ + "images" : [ + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">161" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">183" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Circular.imageset/Contents.json b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Circular.imageset/Contents.json new file mode 100644 index 0000000..9685a7f --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Circular.imageset/Contents.json @@ -0,0 +1,18 @@ +{ + "images" : [ + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">161" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">183" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Corner.imageset/Contents.json b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Corner.imageset/Contents.json new file mode 100644 index 0000000..9685a7f --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Corner.imageset/Contents.json @@ -0,0 +1,18 @@ +{ + "images" : [ + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">161" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">183" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Extra Large.imageset/Contents.json b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Extra Large.imageset/Contents.json new file mode 100644 index 0000000..ed7de25 --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Extra Large.imageset/Contents.json @@ -0,0 +1,28 @@ +{ + "images" : [ + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : "<=145" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">161" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">145" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">183" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Large Rectangular.imageset/Contents.json b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Large Rectangular.imageset/Contents.json new file mode 100644 index 0000000..9685a7f --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Graphic Large Rectangular.imageset/Contents.json @@ -0,0 +1,18 @@ +{ + "images" : [ + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">161" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">183" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Assets.xcassets/Complication.complicationset/Modular.imageset/Contents.json b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Modular.imageset/Contents.json new file mode 100644 index 0000000..ed7de25 --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Modular.imageset/Contents.json @@ -0,0 +1,28 @@ +{ + "images" : [ + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : "<=145" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">161" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">145" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">183" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Assets.xcassets/Complication.complicationset/Utilitarian.imageset/Contents.json b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Utilitarian.imageset/Contents.json new file mode 100644 index 0000000..ed7de25 --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/Complication.complicationset/Utilitarian.imageset/Contents.json @@ -0,0 +1,28 @@ +{ + "images" : [ + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : "<=145" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">161" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">145" + }, + { + "idiom" : "watch", + "scale" : "2x", + "screen-width" : ">183" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Assets.xcassets/Contents.json b/WatchKit Extension/Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/WatchKit Extension/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/Data/ComplicationController.swift b/WatchKit Extension/Data/ComplicationController.swift new file mode 100644 index 0000000..5865148 --- /dev/null +++ b/WatchKit Extension/Data/ComplicationController.swift @@ -0,0 +1,274 @@ +// +// ComplicationController.swift +// WatchKit Extension +// +// Created by royal on 03/09/2020. +// + +import ClockKit +import Vulcan + +class ComplicationController: NSObject, CLKComplicationDataSource { + var schedule: [Vulcan.ScheduleEvent] { + VulcanStore.shared.schedule + .flatMap(\.events) + .filter { $0.isUserSchedule } + } + + // MARK: - Complication Configuration + + func getComplicationDescriptors(handler: @escaping ([CLKComplicationDescriptor]) -> Void) { + let descriptors = [ + CLKComplicationDescriptor(identifier: "ScheduleComplication", displayName: "vulcan", supportedFamilies: CLKComplicationFamily.allCases) + // Multiple complication support can be added here with more descriptors + ] + + // Call the handler with the currently supported complication descriptors + handler(descriptors) + } + + func handleSharedComplicationDescriptors(_ complicationDescriptors: [CLKComplicationDescriptor]) { + // Do any necessary work to support these newly shared complication descriptors + } + + // MARK: - Timeline Configuration + + func getTimelineStartDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) { + handler(self.schedule.filter({ $0.dateStarts ?? $0.date >= Date() }).first?.date.startOfDay) + } + + func getTimelineEndDate(for complication: CLKComplication, withHandler handler: @escaping (Date?) -> Void) { + // Call the handler with the last entry date you can currently provide or nil if you can't support future timelines + handler(self.schedule.filter({ $0.dateStarts ?? $0.date >= Date() }).last?.dateEnds) + } + + func getPrivacyBehavior(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationPrivacyBehavior) -> Void) { + // Call the handler with your desired behavior when the device is locked + handler(.hideOnLockScreen) + } + + // MARK: - Timeline Population + + func getCurrentTimelineEntry(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTimelineEntry?) -> Void) { + // Call the handler with the current timeline entry + + let schedule = self.schedule + .filter { $0.dateStarts ?? $0.date >= Date() } + + let now: Date = Date() + + // If no event, return empty template + guard let nextEventIndex = schedule.firstIndex(where: { $0.dateStarts ?? $0.date > now || $0.isCurrent ?? false }) else { + handler(CLKComplicationTimelineEntry(date: now, complicationTemplate: emptyTemplate(for: complication))) + return + } + + // First index or out of range + let nextEvent = schedule[nextEventIndex] + if nextEventIndex - 1 < 0 { + handler(CLKComplicationTimelineEntry(date: nextEvent.dateStarts ?? nextEvent.date, complicationTemplate: templateForEvent(for: complication, event: nextEvent))) + return + } + + // Other events + let previousEvent = schedule[nextEventIndex - 1] + guard let nextEventDateStarts = nextEvent.dateStarts, + let nextEventDateEnds = nextEvent.dateEnds, + let previousEventDateStarts = previousEvent.dateStarts, + let previousEventDateEnds = previousEvent.dateEnds else { + handler(CLKComplicationTimelineEntry(date: now, complicationTemplate: templateForEvent(for: complication, event: nextEvent))) + return + } + + let previousEventTriggerTime: TimeInterval = (previousEventDateStarts.timeIntervalSinceReferenceDate + previousEventDateEnds.timeIntervalSinceReferenceDate) / 2 + let nextEventTriggerTime: TimeInterval = (nextEventDateStarts.timeIntervalSinceReferenceDate + nextEventDateEnds.timeIntervalSinceReferenceDate) / 2 + let currentTime: TimeInterval = now.timeIntervalSinceReferenceDate + + if currentTime < nextEventTriggerTime { + // previousEvent + handler(CLKComplicationTimelineEntry(date: Date(timeIntervalSinceReferenceDate: previousEventTriggerTime), complicationTemplate: templateForEvent(for: complication, event: previousEvent))) + return + } else { + // nextEvent + handler(CLKComplicationTimelineEntry(date: Date(timeIntervalSinceReferenceDate: nextEventTriggerTime), complicationTemplate: templateForEvent(for: complication, event: nextEvent))) + return + } + } + + func getTimelineEntries(for complication: CLKComplication, after date: Date, limit: Int, withHandler handler: @escaping ([CLKComplicationTimelineEntry]?) -> Void) { + // Call the handler with the timeline entries after the given date + var entries: [CLKComplicationTimelineEntry] = self.schedule + .filter { $0.dateEnds ?? $0.date >= date.startOfDay } + .timeline() + .map { date, event in + CLKComplicationTimelineEntry(date: date, complicationTemplate: templateForEvent(for: complication, event: event)) + } + .sorted { $0.date < $1.date } + + entries.append(CLKComplicationTimelineEntry(date: self.schedule.last?.dateEnds ?? Date(), complicationTemplate: emptyTemplate(for: complication))) + + handler(entries) + } + + // MARK: - Sample Templates + + func getLocalizableSampleTemplate(for complication: CLKComplication, withHandler handler: @escaping (CLKComplicationTemplate?) -> Void) { + // This method will be called once per supported complication, and the results will be cached + handler(templateForEvent(for: complication, event: self.schedule.first(where: { $0.dateEnds ?? $0.date >= Date() }))) + } + + // MARK: - Helper Functions + + /// Returns empty complication template for specified complication + /// - Parameter complication: Current complication + /// - Returns: Complication template + private func emptyTemplate(for complication: CLKComplication) -> CLKComplicationTemplate { + let template: CLKComplicationTemplate + + let scheduleText = CLKSimpleTextProvider(text: "Schedule".localized) + let nothingLeftEmojiText = CLKSimpleTextProvider(text: "Nothing left for now ☺️".localized) + let nothingLeftText = CLKSimpleTextProvider(text: "Nothing left for now".localized) + let emojiText = CLKSimpleTextProvider(text: "☺️") + + // Modular Small + let modularSmall = CLKComplicationTemplateModularSmallSimpleText(textProvider: emojiText) + + // Modular Large + let modularLarge = CLKComplicationTemplateModularLargeStandardBody(headerTextProvider: scheduleText, body1TextProvider: nothingLeftEmojiText) + + // Utilitarian Small + let utilitarianSmall = CLKComplicationTemplateUtilitarianSmallRingText(textProvider: emojiText, fillFraction: 0, ringStyle: .open) + + // Utilitarian Small Flat + let utilitarianSmallFlat = CLKComplicationTemplateUtilitarianSmallFlat(textProvider: nothingLeftEmojiText) + + // Utilitarian Large + let utilitarianLarge = CLKComplicationTemplateUtilitarianLargeFlat(textProvider: nothingLeftEmojiText) + + // Circular Small + let circularSmall = CLKComplicationTemplateCircularSmallSimpleText(textProvider: emojiText) + + // Extra Large + let extraLarge = CLKComplicationTemplateExtraLargeStackText(line1TextProvider: scheduleText, line2TextProvider: nothingLeftEmojiText) + + // Graphic Corner + let graphicCorner = CLKComplicationTemplateGraphicCornerStackText(innerTextProvider: nothingLeftText, outerTextProvider: emojiText) + + // Graphic Bezel + let circularTemplate = CLKComplicationTemplateGraphicCircularStackText(line1TextProvider: CLKSimpleTextProvider(text: "📆"), line2TextProvider: emojiText) + circularTemplate.tintColor = UIColor(named: "AccentColor") + let graphicBezel = CLKComplicationTemplateGraphicBezelCircularText(circularTemplate: circularTemplate, textProvider: nothingLeftText) + + // Graphic Circular + let graphicCircular = circularTemplate + + // Graphic Rectangular + let graphicRectangular = CLKComplicationTemplateGraphicRectangularStandardBody(headerTextProvider: scheduleText, body1TextProvider: nothingLeftEmojiText) + + // Graphic Extra Large + let graphicExtraLarge = CLKComplicationTemplateGraphicExtraLargeCircularStackText(line1TextProvider: scheduleText, line2TextProvider: nothingLeftEmojiText) + + switch (complication.family) { + case .circularSmall: template = circularSmall + case .modularSmall: template = modularSmall + case .modularLarge: template = modularLarge + case .utilitarianSmall: template = utilitarianSmall + case .utilitarianSmallFlat: template = utilitarianSmallFlat + case .utilitarianLarge: template = utilitarianLarge + case .extraLarge: template = extraLarge + case .graphicCorner: template = graphicCorner + case .graphicBezel: template = graphicBezel + case .graphicCircular: template = graphicCircular + case .graphicRectangular: template = graphicRectangular + case .graphicExtraLarge: template = graphicExtraLarge + @unknown default: fatalError("Unknown complication type: \(complication.family.rawValue)") + } + + template.tintColor = UIColor(named: "AccentColor") + return template + } + + /// Returns complication template for specified complication + /// - Parameters: + /// - complication: Current complication + /// - event: Selected event + /// - Returns: Complication template + private func templateForEvent(for complication: CLKComplication, event: Vulcan.ScheduleEvent?) -> CLKComplicationTemplate { + guard let event: Vulcan.ScheduleEvent = event, + let dateStarts = event.dateStarts, + let dateEnds = event.dateEnds else { + return emptyTemplate(for: complication) + } + + let template: CLKComplicationTemplate + + let subjectTextProvider: CLKTextProvider = CLKSimpleTextProvider(text: event.subjectName) + let roomAndSubjectTextProvider: CLKTextProvider = CLKSimpleTextProvider(text: "(\(event.room)) \(event.subjectName)") + var roomAndTeacherTextProvider: CLKTextProvider { + if let employeeFullName = event.employeeFullName { + return CLKSimpleTextProvider(text: "(\(event.room)) \(employeeFullName)") + } else { + return CLKSimpleTextProvider(text: "Room \(event.room)") + } + } + let roomTextProvider: CLKTextProvider = CLKSimpleTextProvider(text: event.room) + let dateProvider: CLKTextProvider = CLKTimeIntervalTextProvider(start: dateStarts, end: dateEnds) + + // Modular Small + let modularSmall: CLKComplicationTemplate = CLKComplicationTemplateModularSmallSimpleText(textProvider: roomTextProvider) + + // Modular Large + let modularLarge: CLKComplicationTemplate = CLKComplicationTemplateModularLargeStandardBody(headerTextProvider: subjectTextProvider, body1TextProvider: roomAndTeacherTextProvider, body2TextProvider: dateProvider) + + // Utilitarian Small + let utilitarianSmall: CLKComplicationTemplate = CLKComplicationTemplateUtilitarianSmallRingText(textProvider: roomTextProvider, fillFraction: 0, ringStyle: .open) + + // Utilitarian Small Flat + let utilitarianSmallFlat: CLKComplicationTemplate = CLKComplicationTemplateUtilitarianSmallFlat(textProvider: roomAndSubjectTextProvider) + + // Utilitarian Large + let utilitarianLarge: CLKComplicationTemplate = CLKComplicationTemplateUtilitarianLargeFlat(textProvider: roomAndSubjectTextProvider) + + // Circular Small + let circularSmall: CLKComplicationTemplate = CLKComplicationTemplateCircularSmallSimpleText(textProvider: roomTextProvider) + + // Extra Large + let extraLarge: CLKComplicationTemplate = CLKComplicationTemplateExtraLargeStackText(line1TextProvider: subjectTextProvider, line2TextProvider: roomTextProvider) + + // Graphic Corner + let graphicCorner: CLKComplicationTemplate = CLKComplicationTemplateGraphicCornerStackText(innerTextProvider: dateProvider, outerTextProvider: roomTextProvider) + + // Graphic Bezel + let circularTemplate: CLKComplicationTemplateGraphicCircular = CLKComplicationTemplateGraphicCircularStackText(line1TextProvider: CLKSimpleTextProvider(text: "📆"), line2TextProvider: roomTextProvider) + circularTemplate.tintColor = UIColor(named: "AccentColor") + let graphicBezel: CLKComplicationTemplate = CLKComplicationTemplateGraphicBezelCircularText(circularTemplate: circularTemplate, textProvider: subjectTextProvider) + + // Graphic Circular + let graphicCircular: CLKComplicationTemplate = circularTemplate + + // Graphic Rectangular + let graphicRectangular: CLKComplicationTemplate = CLKComplicationTemplateGraphicRectangularStandardBody(headerTextProvider: subjectTextProvider, body1TextProvider: roomAndTeacherTextProvider, body2TextProvider: dateProvider) + + // Graphic Extra Large + let graphicExtraLarge: CLKComplicationTemplate = CLKComplicationTemplateGraphicExtraLargeCircularStackText(line1TextProvider: roomAndSubjectTextProvider, line2TextProvider: dateProvider) + + switch (complication.family) { + case .circularSmall: template = circularSmall + case .modularSmall: template = modularSmall + case .modularLarge: template = modularLarge + case .utilitarianSmall: template = utilitarianSmall + case .utilitarianSmallFlat: template = utilitarianSmallFlat + case .utilitarianLarge: template = utilitarianLarge + case .extraLarge: template = extraLarge + case .graphicCorner: template = graphicCorner + case .graphicBezel: template = graphicBezel + case .graphicCircular: template = graphicCircular + case .graphicRectangular: template = graphicRectangular + case .graphicExtraLarge: template = graphicExtraLarge + @unknown default: fatalError("Unknown complication type: \(complication.family.rawValue)") + } + + template.tintColor = UIColor(named: "AccentColor") + return template + } +} diff --git a/WatchKit Extension/Data/ExtensionDelegate.swift b/WatchKit Extension/Data/ExtensionDelegate.swift new file mode 100644 index 0000000..591209b --- /dev/null +++ b/WatchKit Extension/Data/ExtensionDelegate.swift @@ -0,0 +1,15 @@ +// +// ExtensionDelegate.swift +// WatchKit Extension +// +// Created by royal on 08/09/2020. +// + +import Foundation +import WatchKit + +class ExtensionDelegate: NSObject, WKExtensionDelegate { + func applicationDidFinishLaunching() { + WatchSessionManager.shared.startSession() + } +} diff --git a/WatchKit Extension/Data/NotificationController.swift b/WatchKit Extension/Data/NotificationController.swift new file mode 100644 index 0000000..42fb6ba --- /dev/null +++ b/WatchKit Extension/Data/NotificationController.swift @@ -0,0 +1,33 @@ +// +// NotificationController.swift +// WatchKit Extension +// +// Created by royal on 03/09/2020. +// + +import WatchKit +import SwiftUI +import UserNotifications + +class NotificationController: WKUserNotificationHostingController { + + override var body: NotificationView { + return NotificationView() + } + + override func willActivate() { + // This method is called when watch view controller is about to be visible to user + super.willActivate() + } + + override func didDeactivate() { + // This method is called when watch view controller is no longer visible + super.didDeactivate() + } + + override func didReceive(_ notification: UNNotification) { + // This method is called when a notification needs to be presented. + // Implement it if you use a dynamic notification interface. + // Populate your dynamic notification interface as quickly as possible. + } +} diff --git a/WatchKit Extension/Data/VulcanStore.swift b/WatchKit Extension/Data/VulcanStore.swift new file mode 100644 index 0000000..9dad1d5 --- /dev/null +++ b/WatchKit Extension/Data/VulcanStore.swift @@ -0,0 +1,303 @@ +// +// VulcanStore.swift +// WatchKit Extension +// +// Created by royal on 04/09/2020. +// + +import Foundation +import Vulcan +import os +import CoreData +import ClockKit + +final class VulcanStore: ObservableObject { + private let ud = UserDefaults.group + + static let shared: VulcanStore = VulcanStore() + + /// Selected user + @Published public var currentUser: Vulcan.Student? + + /// Data + @Published public var schedule: [Vulcan.Schedule] = [] + @Published public var grades: [Vulcan.SubjectGrades] = [] + @Published public var eotGrades: [Vulcan.EndOfTermGrade] = [] + @Published public var tasks: Vulcan.Tasks = Vulcan.Tasks(exams: [], homework: []) + @Published public var receivedMessages: [Vulcan.Message] = [] + + private init() { + // Load data + let context = CoreDataModel.shared.persistentContainer.viewContext + + // Student + if let storedStudents = try? context.fetch(StoredStudent.fetchRequest()) as? [StoredStudent], + let storedStudent = storedStudents.first { + self.currentUser = Vulcan.Student(from: storedStudent) + } + + // Schedule + if let storedSchedule = try? context.fetch(StoredScheduleEvent.fetchRequest()) as? [StoredScheduleEvent] { + self.schedule = storedSchedule.grouped + .map { date, storedEvents in + let events: [Vulcan.ScheduleEvent] = storedEvents + .compactMap { entity in + Vulcan.ScheduleEvent(from: entity) + } + .sorted { $0.lessonOfTheDay < $1.lessonOfTheDay } + + return Vulcan.Schedule(date: date, events: events) + } + .sorted { $0.date < $1.date } + } + + // Grades + /* if let storedGrades = try? context.fetch(StoredGrade.fetchRequest()) as? [StoredGrade] { + let dictionary = Dictionary(grouping: storedGrades, by: \.subjectID) + self.grades = dictionary + .compactMap { subjectID, grades in + guard let dictionarySubject: DictionarySubject = dictionarySubjects.first(where: { $0.id == subjectID }), + let subjectName: String = dictionarySubject.name, + let subjectCode: String = dictionarySubject.code, + let dEmployeeID = grades.first?.dEmployeeID, + let dictionaryEmployee: DictionaryEmployee = dictionaryEmployees.first(where: { $0.id == dEmployeeID }), + let employeeName: String = dictionaryEmployee.name, + let employeeSurname: String = dictionaryEmployee.surname, + let employeeCode: String = dictionaryEmployee.code + else { + return nil + } + + let subject: Vulcan.Subject = Vulcan.Subject(id: Int(dictionarySubject.id), name: subjectName, code: subjectCode, active: dictionarySubject.active, position: Int(dictionarySubject.position)) + let employee: Vulcan.Employee = Vulcan.Employee(id: Int(dictionaryEmployee.id), name: employeeName, surname: employeeSurname, code: employeeCode, active: dictionaryEmployee.active, teacher: dictionaryEmployee.teacher, loginID: Int(dictionaryEmployee.loginID)) + + let grades: [Vulcan.Grade] = storedGrades + .map { grade in + var grade = Grade(from: grade) + + if let categoryID = grade.categoryID, + let dictionaryGradeCategories: [DictionaryGradeCategory] = try? context.fetch(DictionaryGradeCategory.fetchRequest()) { + grade.category = dictionaryGradeCategories.first(where: { $0.id == categoryID }) + } + + return grade + } + .sorted { $0.dateCreatedEpoch < $1.dateCreatedEpoch } + .filter { $0.subjectID == subject.id } + + return Vulcan.SubjectGrades(subject: subject, employee: employee, grades: grades) + } + .sorted { $0.subject.name < $1.subject.name } + } */ + + // End of Term Grades + /* if let storedEndOfTermGrades = try? context.fetch(StoredEndOfTermGrade.fetchRequest()) as? [StoredEndOfTermGrade] { + self.eotGrades = storedEndOfTermGrades + .compactMap { grade in + var eotGrade = EndOfTermGrade(from: grade) + eotGrade?.subject = dictionarySubjects.first(where: { $0.id == grade.subjectID }) + + return eotGrade + } + .sorted { ($0.subject?.name ?? "") < ($1.subject?.name ?? "") } + } */ + + // Exams + if let storedExams = try? context.fetch(StoredExam.fetchRequest()) as? [StoredExam] { + self.tasks.exams = storedExams + .compactMap { exam in + Vulcan.Exam(from: exam) + } + .sorted { $0.dateEpoch < $1.dateEpoch } + } + + // Homework + if let storedHomework = try? context.fetch(StoredHomework.fetchRequest()) as? [StoredHomework] { + self.tasks.homework = storedHomework + .compactMap { task in + Vulcan.Homework(from: task) + } + .sorted { $0.dateEpoch < $1.dateEpoch } + } + + // Messages + if let storedMessages = try? context.fetch(StoredMessage.fetchRequest()) as? [StoredMessage] { + let receivedMessages: [Vulcan.Message] = storedMessages + .filter { $0.folder == "Odebrane" && $0.status == "Widoczna" } + .compactMap { entity in + let message = Vulcan.Message(from: entity) + message?.tag = .received + + return message + } + .sorted { $0.dateSentEpoch > $1.dateSentEpoch } + + self.receivedMessages = receivedMessages + } + } + + /// Sets the default user. + /// - Parameter user: Selected user + /// - Parameter force: Force dictionary update + public func setUser(_ user: Vulcan.Student, force: Bool = false) { + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).VulcanStore", category: "Users") + logger.debug("Setting default user with ID \(user.id, privacy: .sensitive) (\(user.loginID ?? -1, privacy: .sensitive) : \(user.userLoginID, privacy: .sensitive)).") + + ud.setValue(user.id, forKey: UserDefaults.AppKeys.userID.rawValue) + + DispatchQueue.main.async { + self.currentUser = user + } + + let context = CoreDataModel.shared.persistentContainer.viewContext + do { + try context.execute(NSBatchDeleteRequest(fetchRequest: StoredStudent.fetchRequest())) + _ = user.entity(context: context) + } catch { + logger.error("Couldn't execute request: \(error.localizedDescription)") + } + + CoreDataModel.shared.saveContext() + } + + /// Sets the app' schedule. + /// - Parameter schedule: Schedule received from the phone app + public func setSchedule(_ schedule: [Vulcan.Schedule]) { + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).VulcanStore", category: "Schedule") + + DispatchQueue.main.async { + self.schedule = schedule + } + + (CLKComplicationServer.sharedInstance().activeComplications ?? []) + .filter { $0.identifier == "ScheduleComplication" } + .forEach { complication in + CLKComplicationServer.sharedInstance().reloadTimeline(for: complication) + } + + let context = CoreDataModel.shared.persistentContainer.viewContext + let deleteRequest = NSBatchDeleteRequest(fetchRequest: StoredScheduleEvent.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for event in schedule.flatMap(\.events) { + _ = event.entity(context: context) + } + + CoreDataModel.shared.saveContext() + } + + /// Sets the app' grades. + /// - Parameter grades: Received grades + public func setGrades(_ grades: [Vulcan.SubjectGrades]) { + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).VulcanStore", category: "Grades") + + DispatchQueue.main.async { + self.grades = grades + } + + let context = CoreDataModel.shared.persistentContainer.viewContext + let deleteRequest = NSBatchDeleteRequest(fetchRequest: StoredGrade.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for grade in grades.flatMap(\.grades) { + _ = grade.entity(context: context) + } + + CoreDataModel.shared.saveContext() + } + + /// Sets the app' EOT grades. + /// - Parameter eotGrades: End of term grades + public func setEOTGrades(_ eotGrades: [Vulcan.EndOfTermGrade]) { + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).VulcanStore", category: "EOTGrades") + + DispatchQueue.main.async { + self.eotGrades = eotGrades + } + + let context = CoreDataModel.shared.persistentContainer.viewContext + let deleteRequest = NSBatchDeleteRequest(fetchRequest: StoredEndOfTermGrade.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for eotGrade in eotGrades { + _ = eotGrade.entity(context: context) + } + + CoreDataModel.shared.saveContext() + } + + /// Sets the app' tasks. + /// - Parameter tasks: Received tasks + public func setTasks(_ tasks: Vulcan.Tasks) { + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).VulcanStore", category: "Tasks") + + DispatchQueue.main.async { + self.tasks = tasks + } + + let context = CoreDataModel.shared.persistentContainer.viewContext + + do { + try context.execute(NSBatchDeleteRequest(fetchRequest: StoredHomework.fetchRequest())) + try context.execute(NSBatchDeleteRequest(fetchRequest: StoredExam.fetchRequest())) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for exam in tasks.exams { + _ = exam.entity(context: context) + } + + for homework in tasks.homework { + _ = homework.entity(context: context) + } + + CoreDataModel.shared.saveContext() + } + + /// Sets the app' messages. + /// - Parameters: + /// - messages: Received messages with certain tag + /// - tag: Tag of the messages + public func setMessages(_ messages: [Vulcan.Message], tag: Vulcan.MessageTag) { + let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).VulcanStore", category: "Messages") + + DispatchQueue.main.async { + switch tag { + case .deleted: break + case .received: self.receivedMessages = messages + case .sent: break + } + } + + let context = CoreDataModel.shared.persistentContainer.viewContext + let deleteRequest = NSBatchDeleteRequest(fetchRequest: StoredMessage.fetchRequest()) + + do { + try context.execute(deleteRequest) + } catch { + logger.error("Error executing request: \(error.localizedDescription)") + } + + for message in messages { + _ = message.entity(context: context) + } + + CoreDataModel.shared.saveContext() + } +} diff --git a/WatchKit Extension/Info.plist b/WatchKit Extension/Info.plist new file mode 100644 index 0000000..093bfa1 --- /dev/null +++ b/WatchKit Extension/Info.plist @@ -0,0 +1,36 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + vulcan + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + CLKComplicationPrincipalClass + $(PRODUCT_MODULE_NAME).ComplicationController + NSExtension + + NSExtensionAttributes + + WKAppBundleIdentifier + dev.niepostek.vulcan.watchkit + + NSExtensionPointIdentifier + com.apple.watchkit + + + diff --git a/WatchKit Extension/Localization/en.lproj/Localizable.strings b/WatchKit Extension/Localization/en.lproj/Localizable.strings new file mode 100644 index 0000000..b864375 --- /dev/null +++ b/WatchKit Extension/Localization/en.lproj/Localizable.strings @@ -0,0 +1,42 @@ +/* + Localizable.strings + vulcan + en_US + + Created by royal on 08/09/2020. + +*/ + +"Nothind found" = "Nothing found"; + +// MARK: ContentView.swift +"Not logged in" = "Not logged in"; +"Refresh" = "Refresh"; +"Schedule" = "Schedule"; +"Grades" = "Grades"; +"Final Grades" = "Final Grades"; +"Tasks" = "Tasks"; +"Messages" = "Messages"; + +// MARK: - ComplicationController.swift +"Nothing left for now ☺️" = "Nothing left for now ☺️"; +"Nothing left for now" = "Nothing left for now"; +"Room %@" = "Room %@"; + +// MARK: - GradesView.swift +"No grades" = "No grades"; + +// MARK: - FinalGradesView.swift +"Anticipated" = "Anticipated"; +"Final" = "Final"; + +// MARK: - TasksView.swift +"Homework" = "Homework"; +"Exams" = "Exams"; + +// MARK: - TaskCell.swift +"No entry" = "No entry"; +"TAG_EXAM" = "Exam"; +"TAG_HOMEWORK" = "Homework"; +"EXAM_BIG" = "Exam"; +"EXAM_SMALL" = "Quiz"; diff --git a/WatchKit Extension/Localization/pl.lproj/Localizable.strings b/WatchKit Extension/Localization/pl.lproj/Localizable.strings new file mode 100644 index 0000000..f471df5 --- /dev/null +++ b/WatchKit Extension/Localization/pl.lproj/Localizable.strings @@ -0,0 +1,42 @@ +/* + Localizable.strings + vulcan + pl_PL + + Created by royal on 08/09/2020. + +*/ + +"Nothing found" = "Nic nie znaleziono"; + +// MARK: ContentView.swift +"Not logged in" = "Nie zalogowano"; +"Refresh" = "Odśwież"; +"Schedule" = "Plan Lekcji"; +"Grades" = "Oceny"; +"Final Grades" = "Oceny Semestralne"; +"Tasks" = "Zadania"; +"Messages" = "Wiadomości"; + +// MARK: - ComplicationController.swift +"Nothing left for now ☺️" = "Nic w najbliższym czasie ☺️"; +"Nothing left for now" = "Nic w najbliższym czasie"; +"Room %@" = "Sala %@"; + +// MARK: - GradesView.swift +"No grades" = "Brak ocen"; + +// MARK: - FinalGradesView.swift +"Anticipated" = "Proponowane"; +"Final" = "Ostateczne"; + +// MARK: - TasksView.swift +"Homework" = "Zadania domowe"; +"Exams" = "Testy"; + +// MARK: - TaskCell.swift +"No entry" = "Brak wpisu"; +"TAG_EXAM" = "Test"; +"TAG_HOMEWORK" = "Zadanie domowe"; +"EXAM_BIG" = "Sprawdzian"; +"EXAM_SMALL" = "Kartkówka"; diff --git a/WatchKit Extension/Preview Content/Preview Assets.xcassets/Contents.json b/WatchKit Extension/Preview Content/Preview Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/WatchKit Extension/Preview Content/Preview Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit Extension/PushNotificationPayload.apns b/WatchKit Extension/PushNotificationPayload.apns new file mode 100644 index 0000000..c18b00a --- /dev/null +++ b/WatchKit Extension/PushNotificationPayload.apns @@ -0,0 +1,20 @@ +{ + "aps": { + "alert": { + "body": "Test message", + "title": "Optional title", + "subtitle": "Optional subtitle" + }, + "category": "myCategory", + "thread-id": "5280" + }, + + "WatchKit Simulator Actions": [ + { + "title": "First Button", + "identifier": "firstButtonAction" + } + ], + + "customKey": "Use this file to define a testing payload for your notifications. The aps dictionary specifies the category, alert text and title. The WatchKit Simulator Actions array can provide info for one or more action buttons in addition to the standard Dismiss button. Any other top level keys are custom payload. If you have multiple such JSON files in your project, you'll be able to select them when choosing to debug the notification interface of your Watch App." +} diff --git a/WatchKit Extension/Views/Components/HomeCardCell.swift b/WatchKit Extension/Views/Components/HomeCardCell.swift new file mode 100644 index 0000000..30c50b0 --- /dev/null +++ b/WatchKit Extension/Views/Components/HomeCardCell.swift @@ -0,0 +1,34 @@ +// +// HomeCardCell.swift +// WatchKit Extension +// +// Created by royal on 04/09/2020. +// + +import SwiftUI + +struct HomeCardCell: View { + let title: String + let emoji: String + + var body: some View { + VStack(alignment: .leading) { + Text(emoji) + .font(.title3) + .padding(.bottom) + + Spacer() + + Text(LocalizedStringKey(title)) + .font(.headline) + } + .padding(.vertical) + .frame(height: 100) + } +} + +struct HomeCardCell_Previews: PreviewProvider { + static var previews: some View { + HomeCardCell(title: "gang", emoji: "😶") + } +} diff --git a/WatchKit Extension/Views/Components/ScheduleEventCell.swift b/WatchKit Extension/Views/Components/ScheduleEventCell.swift new file mode 100644 index 0000000..7fd2746 --- /dev/null +++ b/WatchKit Extension/Views/Components/ScheduleEventCell.swift @@ -0,0 +1,37 @@ +// +// ScheduleEventCell.swift +// WatchKit Extension +// +// Created by royal on 09/09/2020. +// + +import SwiftUI +import Vulcan + +struct ScheduleEventCell: View { + let event: Vulcan.ScheduleEvent + + var body: some View { + VStack(alignment: .leading) { + Text(event.subjectName) + .font(.headline) + + if let dateStarts = event.dateStarts, + let dateEnds = event.dateEnds { + Text("\(event.room) • \(dateStarts.localizedTime) - \(dateEnds.localizedTime)") + } else { + Text(event.room) + } + } + .opacity(event.dateEnds ?? event.date < Date() ? 0.5 : 1) + .frame(height: 100) + // .listRowPlatterColor(event.isCurrent ?? false ? Color.accentColor : nil) + .listRowPlatterColor((event.dateStarts ?? Date(timeIntervalSince1970: 0) < Date() && event.dateEnds ?? Date(timeIntervalSince1970: 0) > Date()) ? Color.accentColor : nil) + } +} + +/* struct ScheduleEventCell_Previews: PreviewProvider { + static var previews: some View { + ScheduleEventCell(event: <#Vulcan.ScheduleEvent#>, group: <#Int#>) + } +} */ diff --git a/WatchKit Extension/Views/Components/TaskCell.swift b/WatchKit Extension/Views/Components/TaskCell.swift new file mode 100644 index 0000000..5ddef6b --- /dev/null +++ b/WatchKit Extension/Views/Components/TaskCell.swift @@ -0,0 +1,57 @@ +// +// TaskCell.swift +// WatchKit Extension +// +// Created by royal on 20/09/2020. +// + +import SwiftUI +import Vulcan + +struct TaskCell: View { + let task: VulcanTask + let isBigType: Bool? + + var body: some View { + VStack(alignment: .leading) { + Group { + if !task.entry.isReallyEmpty { + Text(task.entry) + } else { + Text("No entry") + .foregroundColor(.secondary) + } + } + .font(.headline) + .multilineTextAlignment(.leading) + .allowsTightening(true) + .lineLimit(5) + + Group { + if let subjectName = task.subject?.name { + Text(subjectName) + } + + if let isBigType = isBigType { + Text("\((isBigType ? "EXAM_BIG" : "EXAM_SMALL").localized) • \(task.date.relativeString)") + } else { + Text(task.date, style: .relative) + } + } + .font(.callout) + .foregroundColor(.secondary) + .multilineTextAlignment(.leading) + .allowsTightening(true) + .lineLimit(3) + } + .padding(.vertical, 10) + .opacity(task.date.endOfDay >= Date() ? 1 : 0.75) + } +} + + +/* struct TaskCell_Previews: PreviewProvider { + static var previews: some View { + TaskCell() + } +} */ diff --git a/WatchKit Extension/Views/ContentView.swift b/WatchKit Extension/Views/ContentView.swift new file mode 100644 index 0000000..a4b4774 --- /dev/null +++ b/WatchKit Extension/Views/ContentView.swift @@ -0,0 +1,66 @@ +// +// ContentView.swift +// WatchKit Extension +// +// Created by royal on 03/09/2020. +// + +import SwiftUI +import Vulcan + +struct ContentView: View { + @EnvironmentObject var vulcanStore: VulcanStore + + var messagesEmoji: String { + (vulcanStore.receivedMessages).contains(where: { !$0.hasBeenRead }) ? "📫" : "📪" + } + + var loggedInView: some View { + List { + NavigationLink(destination: ScheduleView()) { + HomeCardCell(title: "Schedule", emoji: "📆") + } + NavigationLink(destination: GradesView()) { + HomeCardCell(title: "Grades", emoji: "🏅") + } + NavigationLink(destination: FinalGradesView()) { + HomeCardCell(title: "Final Grades", emoji: "🎉") + } + NavigationLink(destination: TasksView()) { + HomeCardCell(title: "Tasks", emoji: "📚") + } + NavigationLink(destination: MessagesView()) { + HomeCardCell(title: "Messages", emoji: messagesEmoji) + } + + #if DEBUG + NavigationLink(destination: DebugView()) { + HomeCardCell(title: "Debug", emoji: "🤫") + } + #endif + } + .listStyle(CarouselListStyle()) + } + + var body: some View { + if vulcanStore.currentUser != nil { + loggedInView + } else { + VStack { + Text("Not logged in") + .padding() + + Button("Refresh") { + WKInterfaceDevice.current().play(.start) + try? WatchSessionManager.shared.sendData(["type": "Request", "requestedData": "InitData"]) + } + } + } + } +} + +struct ContentView_Previews: PreviewProvider { + static var previews: some View { + ContentView() + } +} diff --git a/WatchKit Extension/Views/DebugView.swift b/WatchKit Extension/Views/DebugView.swift new file mode 100644 index 0000000..b8c92b0 --- /dev/null +++ b/WatchKit Extension/Views/DebugView.swift @@ -0,0 +1,69 @@ +// +// DebugView.swift +// WatchKit Extension +// +// Created by royal on 04/09/2020. +// + +import SwiftUI +import ClockKit + +struct DebugView: View { + private let ud = UserDefaults.group + + var body: some View { + List { + // UserDefaults + Section(header: Text("UserDefaults").textCase(.none)) { + // ColorScheme + HStack { + Text("colorScheme") + Spacer() + Text(ud.string(forKey: "colorScheme") ?? "Default") + } + + // ColorizeGrades + HStack { + Text("colorizeGrades") + Spacer() + Text(ud.bool(forKey: "colorizeGrades") ? "true" : "false") + } + + // IsLoggedIn + HStack { + Text("isLoggedIn") + Spacer() + Text(ud.bool(forKey: "isLoggedIn") ? "true" : "false") + } + + // UserGroup + HStack { + Text("userGroup") + Spacer() + Text("\(ud.integer(forKey: "userGroup"))") + } + } + + // Complications + Section(header: Text("Complications").textCase(.none)) { + Button("Reload complications") { + for complication in CLKComplicationServer.sharedInstance().activeComplications ?? [] { + CLKComplicationServer.sharedInstance().reloadTimeline(for: complication) + } + } + + ForEach(CLKComplicationServer.sharedInstance().activeComplications ?? [], id: \.identifier) { complication in + Text("\(complication.identifier): \(complication.family.rawValue)") + } + } + } + .listStyle(PlainListStyle()) + .navigationTitle(Text("🤫")) + } +} + +struct DebugView_Previews: PreviewProvider { + static var previews: some View { + DebugView() + } +} diff --git a/WatchKit Extension/Views/Details/GradesDetailView.swift b/WatchKit Extension/Views/Details/GradesDetailView.swift new file mode 100644 index 0000000..b22b666 --- /dev/null +++ b/WatchKit Extension/Views/Details/GradesDetailView.swift @@ -0,0 +1,37 @@ +// +// GradesDetailView.swift +// WatchKit Extension +// +// Created by royal on 19/09/2020. +// + +import SwiftUI +import Vulcan + +struct GradesDetailView: View { + let subject: Vulcan.SubjectGrades + + let colorizeGrades: Bool = UserDefaults.group.bool(forKey: UserDefaults.AppKeys.colorizeGrades.rawValue) + let scheme: String = UserDefaults.group.string(forKey: UserDefaults.AppKeys.colorScheme.rawValue) ?? "Default" + + var body: some View { + List(subject.grades) { grade in + HStack { + Text(LocalizedStringKey(grade.category?.name ?? "No category")) + .font(.headline) + Spacer() + Text(grade.entry ?? "...") + } + .padding(.vertical) + .foregroundColor(colorizeGrades ? Color("ColorSchemes/\(scheme)/\(grade.grade ?? 0)", bundle: Bundle(identifier: "Colors")) : .primary) + .listRowPlatterColor(colorizeGrades ? Color("ColorSchemes/\(scheme)/\(grade.grade ?? 0)", bundle: Bundle(identifier: "Colors")).opacity(0.25) : nil) + } + .navigationTitle(subject.subject.name) + } +} + +struct GradesDetailView_Previews: PreviewProvider { + static var previews: some View { + GradesView() + } +} diff --git a/WatchKit Extension/Views/Details/MessageDetailView.swift b/WatchKit Extension/Views/Details/MessageDetailView.swift new file mode 100644 index 0000000..5b7d62d --- /dev/null +++ b/WatchKit Extension/Views/Details/MessageDetailView.swift @@ -0,0 +1,43 @@ +// +// MessageDetailView.swift +// WatchKit Extension +// +// Created by royal on 19/09/2020. +// + +import SwiftUI +import Vulcan + +struct MessageDetailView: View { + let message: Vulcan.Message + + var body: some View { + ScrollView { + VStack(alignment: .leading) { + Text(message.title) + .font(.headline) + + if let sender = message.sender { + Text(sender) + .font(.subheadline) + .foregroundColor(.secondary) + } + + Text(message.dateSent.formattedDateString(timeStyle: .short, dateStyle: .medium, context: .beginningOfSentence)) + .font(.subheadline) + .foregroundColor(.secondary) + } + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) + .padding(.bottom, 5) + + Text(message.content) + } + .navigationTitle(message.title) + } +} + +/* struct MessageDetailView_Previews: PreviewProvider { + static var previews: some View { + MessageDetailView() + } +} */ diff --git a/WatchKit Extension/Views/FinalGradesView.swift b/WatchKit Extension/Views/FinalGradesView.swift new file mode 100644 index 0000000..1c1e338 --- /dev/null +++ b/WatchKit Extension/Views/FinalGradesView.swift @@ -0,0 +1,72 @@ +// +// FinalGradesView.swift +// WatchKit Extension +// +// Created by royal on 04/09/2020. +// + +import SwiftUI +import Vulcan + +struct FinalGradesView: View { + @EnvironmentObject var vulcanStore: VulcanStore + + let colorizeGrades: Bool = UserDefaults.group.bool(forKey: UserDefaults.AppKeys.colorizeGrades.rawValue) + let scheme: String = UserDefaults.group.string(forKey: UserDefaults.AppKeys.colorScheme.rawValue) ?? "Default" + + var body: some View { + List { + // Anticipated + Section(header: Text("Anticipated")) { + if (vulcanStore.eotGrades.expected.count > 0) { + ForEach(vulcanStore.eotGrades.expected, id: \.subjectID) { grade in + HStack { + Text(grade.subject?.name ?? "Unknown subject") + .font(.headline) + Spacer() + Text(grade.entry) + } + .padding(.vertical) + .foregroundColor(colorizeGrades ? Color("ColorSchemes/\(scheme)/\(grade.entry)", bundle: Bundle(identifier: "Colors")) : .primary) + .listRowPlatterColor(colorizeGrades ? Color("ColorSchemes/\(scheme)/\(grade.entry)", bundle: Bundle(identifier: "Colors")).opacity(0.25) : nil) + } + } else { + Text("No grades") + .multilineTextAlignment(.center) + .opacity(0.3) + .fullWidth() + } + } + + // Final + Section(header: Text("Final")) { + if (vulcanStore.eotGrades.final.count > 0) { + ForEach(vulcanStore.eotGrades.final, id: \.subjectID) { grade in + HStack { + Text(grade.subject?.name ?? "Unknown subject") + .font(.headline) + Spacer() + Text(grade.entry) + } + .padding(.vertical) + .foregroundColor(colorizeGrades ? Color("ColorSchemes/\(scheme)/\(grade.entry)", bundle: Bundle(identifier: "Colors")) : .primary) + .listRowPlatterColor(colorizeGrades ? Color("ColorSchemes/\(scheme)/\(grade.entry)", bundle: Bundle(identifier: "Colors")).opacity(0.25) : nil) + } + } else { + Text("No grades") + .multilineTextAlignment(.center) + .opacity(0.3) + .fullWidth() + } + } + } + .listStyle(PlainListStyle()) + .navigationBarTitle(Text("Final Grades")) + } +} + +struct FinalGradesView_Previews: PreviewProvider { + static var previews: some View { + FinalGradesView() + } +} diff --git a/WatchKit Extension/Views/GradesView.swift b/WatchKit Extension/Views/GradesView.swift new file mode 100644 index 0000000..ccdf15a --- /dev/null +++ b/WatchKit Extension/Views/GradesView.swift @@ -0,0 +1,45 @@ +// +// GradesView.swift +// WatchKit Extension +// +// Created by royal on 04/09/2020. +// + +import SwiftUI +import Vulcan + +struct GradesView: View { + @EnvironmentObject var vulcanStore: VulcanStore + + var body: some View { + Group { + if (vulcanStore.grades.count > 0) { + List(vulcanStore.grades) { subject in + NavigationLink(destination: GradesDetailView(subject: subject)) { + VStack(alignment: .leading) { + Text(subject.subject.name) + .font(.headline) + + Text("\(subject.employee.name) \(subject.employee.surname)") + .font(.subheadline) + .foregroundColor(.secondary) + } + .padding(.vertical) + } + } + .listStyle(CarouselListStyle()) + } else { + Text("No grades") + .multilineTextAlignment(.center) + .opacity(0.3) + } + } + .navigationTitle(Text("Grades")) + } +} + +struct GradesView_Previews: PreviewProvider { + static var previews: some View { + GradesView() + } +} diff --git a/WatchKit Extension/Views/MessagesView.swift b/WatchKit Extension/Views/MessagesView.swift new file mode 100644 index 0000000..051bd7f --- /dev/null +++ b/WatchKit Extension/Views/MessagesView.swift @@ -0,0 +1,51 @@ +// +// MessagesView.swift +// WatchKit Extension +// +// Created by royal on 04/09/2020. +// + +import SwiftUI +import Vulcan + +struct MessagesView: View { + @EnvironmentObject var vulcanStore: VulcanStore + + var body: some View { + List { + if (vulcanStore.receivedMessages.count > 0) { + ForEach(vulcanStore.receivedMessages) { message in + VStack { + NavigationLink(destination: MessageDetailView(message: message)) { + VStack(alignment: .leading) { + Text(message.title) + .font(.headline) + + if let sender = message.sender { + Text(sender) + .font(.subheadline) + .foregroundColor(.secondary) + } + } + .padding(.vertical) + .opacity(message.hasBeenRead ? 0.5 : 1) + } + } + } + } else { + Text("Nothing found") + .multilineTextAlignment(.center) + .opacity(0.3) + .fullWidth() + } + } + .listStyle(CarouselListStyle()) + .navigationTitle(Text("Messages")) + } +} + +struct MessagesView_Previews: PreviewProvider { + static var previews: some View { + MessagesView() + } +} diff --git a/WatchKit Extension/Views/NotificationView.swift b/WatchKit Extension/Views/NotificationView.swift new file mode 100644 index 0000000..5bfebba --- /dev/null +++ b/WatchKit Extension/Views/NotificationView.swift @@ -0,0 +1,20 @@ +// +// NotificationView.swift +// WatchKit Extension +// +// Created by royal on 03/09/2020. +// + +import SwiftUI + +struct NotificationView: View { + var body: some View { + Text("Hello, World!") + } +} + +struct NotificationView_Previews: PreviewProvider { + static var previews: some View { + NotificationView() + } +} diff --git a/WatchKit Extension/Views/ScheduleView.swift b/WatchKit Extension/Views/ScheduleView.swift new file mode 100644 index 0000000..2ac9c74 --- /dev/null +++ b/WatchKit Extension/Views/ScheduleView.swift @@ -0,0 +1,48 @@ +// +// ScheduleView.swift +// WatchKit Extension +// +// Created by royal on 04/09/2020. +// + +import SwiftUI +import Vulcan + +struct ScheduleView: View { + @EnvironmentObject var vulcanStore: VulcanStore + + let date: Date = Date() + + var events: [Vulcan.ScheduleEvent]? { + vulcanStore.schedule + .first(where: { + $0.events.contains { $0.dateStarts ?? $0.date >= Date() } + })? + .events + .filter { $0.isUserSchedule } + } + + var body: some View { + Group { + if ((events ?? []).count > 0) { + List { + ForEach(events ?? []) { event in + ScheduleEventCell(event: event) + } + } + .listStyle(CarouselListStyle()) + } else { + Text("Nothing left for now ☺️") + .multilineTextAlignment(.center) + .opacity(0.3) + } + } + .navigationTitle(Text("Schedule")) + } +} + +struct ScheduleView_Previews: PreviewProvider { + static var previews: some View { + ScheduleView() + } +} diff --git a/WatchKit Extension/Views/TasksView.swift b/WatchKit Extension/Views/TasksView.swift new file mode 100644 index 0000000..f3bdc8d --- /dev/null +++ b/WatchKit Extension/Views/TasksView.swift @@ -0,0 +1,50 @@ +// +// TasksView.swift +// WatchKit Extension +// +// Created by royal on 04/09/2020. +// + +import SwiftUI + +struct TasksView: View { + @EnvironmentObject var vulcanStore: VulcanStore + + var body: some View { + List { + Section(header: Text("Homework")) { + if (vulcanStore.tasks.homework.filter({ $0.date >= Date() }).count > 0) { + ForEach(vulcanStore.tasks.homework.filter({ $0.date >= Date() })) { task in + TaskCell(task: task, isBigType: nil) + } + } else { + Text("Nothing found") + .multilineTextAlignment(.center) + .opacity(0.3) + .fullWidth() + } + } + + Section(header: Text("Exams")) { + if (vulcanStore.tasks.exams.filter({ $0.date >= Date() }).count > 0) { + ForEach(vulcanStore.tasks.exams.filter({ $0.date >= Date() })) { task in + TaskCell(task: task, isBigType: task.isBigType) + } + } else { + Text("Nothing found") + .multilineTextAlignment(.center) + .opacity(0.3) + .fullWidth() + } + } + } + .listStyle(PlainListStyle()) + .navigationBarTitle(Text("Tasks")) + } +} + +struct TasksView_Previews: PreviewProvider { + static var previews: some View { + TasksView() + } +} diff --git a/WatchKit Extension/WatchKit Extension.entitlements b/WatchKit Extension/WatchKit Extension.entitlements new file mode 100644 index 0000000..e3cd394 --- /dev/null +++ b/WatchKit Extension/WatchKit Extension.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.application-groups + + group.dev.niepostek.vulcanGroup + + + diff --git a/WatchKit Extension/vulcanApp.swift b/WatchKit Extension/vulcanApp.swift new file mode 100644 index 0000000..8ca0396 --- /dev/null +++ b/WatchKit Extension/vulcanApp.swift @@ -0,0 +1,27 @@ +// +// vulcanApp.swift +// WatchKit Extension +// +// Created by royal on 03/09/2020. +// + +import SwiftUI +import Vulcan + +@main +struct vulcanApp: App { + @WKExtensionDelegateAdaptor(ExtensionDelegate.self) var extensionDelegate: ExtensionDelegate + @StateObject private var vulcanStore: VulcanStore = VulcanStore.shared + + @SceneBuilder var body: some Scene { + WindowGroup { + NavigationView { + ContentView() + .navigationTitle(Text("vulcan")) + .environmentObject(vulcanStore) + } + } + + WKNotificationScene(controller: NotificationController.self, category: "myCategory") + } +} diff --git a/WatchKit/Assets.xcassets/AccentColor.colorset/Contents.json b/WatchKit/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000..68dc4ff --- /dev/null +++ b/WatchKit/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,20 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "srgb", + "components" : { + "alpha" : "1.000", + "blue" : "0.204", + "green" : "0.235", + "red" : "1.000" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Contents.json b/WatchKit/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..5385fb4 --- /dev/null +++ b/WatchKit/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,92 @@ +{ + "images" : [ + { + "filename" : "Icon_24pt@2x.png", + "idiom" : "watch", + "role" : "notificationCenter", + "scale" : "2x", + "size" : "24x24", + "subtype" : "38mm" + }, + { + "filename" : "Icon_27.5pt@2x.png", + "idiom" : "watch", + "role" : "notificationCenter", + "scale" : "2x", + "size" : "27.5x27.5", + "subtype" : "42mm" + }, + { + "filename" : "Icon_29pt@2x.png", + "idiom" : "watch", + "role" : "companionSettings", + "scale" : "2x", + "size" : "29x29" + }, + { + "filename" : "Icon_29pt@3x.png", + "idiom" : "watch", + "role" : "companionSettings", + "scale" : "3x", + "size" : "29x29" + }, + { + "filename" : "Icon_40pt@2x.png", + "idiom" : "watch", + "role" : "appLauncher", + "scale" : "2x", + "size" : "40x40", + "subtype" : "38mm" + }, + { + "filename" : "Icon_44pt@2x.png", + "idiom" : "watch", + "role" : "appLauncher", + "scale" : "2x", + "size" : "44x44", + "subtype" : "40mm" + }, + { + "filename" : "Icon_50pt@2x.png", + "idiom" : "watch", + "role" : "appLauncher", + "scale" : "2x", + "size" : "50x50", + "subtype" : "44mm" + }, + { + "filename" : "Icon_86pt@2x.png", + "idiom" : "watch", + "role" : "quickLook", + "scale" : "2x", + "size" : "86x86", + "subtype" : "38mm" + }, + { + "filename" : "Icon_98pt@2x.png", + "idiom" : "watch", + "role" : "quickLook", + "scale" : "2x", + "size" : "98x98", + "subtype" : "42mm" + }, + { + "filename" : "Icon_108pt@2x.png", + "idiom" : "watch", + "role" : "quickLook", + "scale" : "2x", + "size" : "108x108", + "subtype" : "44mm" + }, + { + "filename" : "Icon.png", + "idiom" : "watch-marketing", + "scale" : "1x", + "size" : "1024x1024" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon.png b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon.png new file mode 100644 index 0000000..2599404 Binary files /dev/null and b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon.png differ diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_108pt@2x.png b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_108pt@2x.png new file mode 100644 index 0000000..7081cc3 Binary files /dev/null and b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_108pt@2x.png differ diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_24pt@2x.png b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_24pt@2x.png new file mode 100644 index 0000000..4c43ea2 Binary files /dev/null and b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_24pt@2x.png differ diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_27.5pt@2x.png b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_27.5pt@2x.png new file mode 100644 index 0000000..a8bc7a0 Binary files /dev/null and b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_27.5pt@2x.png differ diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_29pt@2x.png b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_29pt@2x.png new file mode 100644 index 0000000..3625cea Binary files /dev/null and b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_29pt@2x.png differ diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_29pt@3x.png b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_29pt@3x.png new file mode 100644 index 0000000..44a5f21 Binary files /dev/null and b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_29pt@3x.png differ diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_40pt@2x.png b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_40pt@2x.png new file mode 100644 index 0000000..f77bcfe Binary files /dev/null and b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_40pt@2x.png differ diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_44pt@2x.png b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_44pt@2x.png new file mode 100644 index 0000000..2de52c5 Binary files /dev/null and b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_44pt@2x.png differ diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_50pt@2x.png b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_50pt@2x.png new file mode 100644 index 0000000..2064ab2 Binary files /dev/null and b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_50pt@2x.png differ diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_86pt@2x.png b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_86pt@2x.png new file mode 100644 index 0000000..967a3ec Binary files /dev/null and b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_86pt@2x.png differ diff --git a/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_98pt@2x.png b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_98pt@2x.png new file mode 100644 index 0000000..60fcac8 Binary files /dev/null and b/WatchKit/Assets.xcassets/AppIcon.appiconset/Icon_98pt@2x.png differ diff --git a/WatchKit/Assets.xcassets/Contents.json b/WatchKit/Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/WatchKit/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/WatchKit/Info.plist b/WatchKit/Info.plist new file mode 100644 index 0000000..88f127a --- /dev/null +++ b/WatchKit/Info.plist @@ -0,0 +1,33 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + vulcan + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + + WKCompanionAppBundleIdentifier + dev.niepostek.vulcan + WKWatchKitApp + + + diff --git a/Widget/Assets.xcassets/AccentColor.colorset/Contents.json b/Widget/Assets.xcassets/AccentColor.colorset/Contents.json new file mode 100644 index 0000000..c3f3a26 --- /dev/null +++ b/Widget/Assets.xcassets/AccentColor.colorset/Contents.json @@ -0,0 +1,20 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.252", + "green" : "0.307", + "red" : "0.921" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Widget/Assets.xcassets/Background/Bottom.colorset/Contents.json b/Widget/Assets.xcassets/Background/Bottom.colorset/Contents.json new file mode 100644 index 0000000..b2ed593 --- /dev/null +++ b/Widget/Assets.xcassets/Background/Bottom.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.203", + "green" : "0.254", + "red" : "0.891" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.064", + "green" : "0.059", + "red" : "0.212" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Widget/Assets.xcassets/Background/Contents.json b/Widget/Assets.xcassets/Background/Contents.json new file mode 100644 index 0000000..6e96565 --- /dev/null +++ b/Widget/Assets.xcassets/Background/Contents.json @@ -0,0 +1,9 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + }, + "properties" : { + "provides-namespace" : true + } +} diff --git a/Widget/Assets.xcassets/Background/Top.colorset/Contents.json b/Widget/Assets.xcassets/Background/Top.colorset/Contents.json new file mode 100644 index 0000000..418c17b --- /dev/null +++ b/Widget/Assets.xcassets/Background/Top.colorset/Contents.json @@ -0,0 +1,38 @@ +{ + "colors" : [ + { + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.277", + "green" : "0.310", + "red" : "0.960" + } + }, + "idiom" : "universal" + }, + { + "appearances" : [ + { + "appearance" : "luminosity", + "value" : "dark" + } + ], + "color" : { + "color-space" : "display-p3", + "components" : { + "alpha" : "1.000", + "blue" : "0.067", + "green" : "0.063", + "red" : "0.231" + } + }, + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Widget/Assets.xcassets/Contents.json b/Widget/Assets.xcassets/Contents.json new file mode 100644 index 0000000..73c0059 --- /dev/null +++ b/Widget/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json b/Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json new file mode 100644 index 0000000..eb87897 --- /dev/null +++ b/Widget/Assets.xcassets/WidgetBackground.colorset/Contents.json @@ -0,0 +1,11 @@ +{ + "colors" : [ + { + "idiom" : "universal" + } + ], + "info" : { + "author" : "xcode", + "version" : 1 + } +} diff --git a/Widget/Data/NextUpProvider.swift b/Widget/Data/NextUpProvider.swift new file mode 100644 index 0000000..1a67b36 --- /dev/null +++ b/Widget/Data/NextUpProvider.swift @@ -0,0 +1,125 @@ +// +// NextUpProvider.swift +// Widget +// +// Created by royal on 18/10/2020. +// + +import CoreData +import WidgetKit +import Vulcan + +struct NextUpProvider: TimelineProvider { + struct Entry: TimelineEntry { + let date: Date + let currentEvent: Vulcan.ScheduleEvent? + let nextEvents: [Vulcan.ScheduleEvent] + + var relevance: TimelineEntryRelevance? { + guard let event: Vulcan.ScheduleEvent = self.currentEvent else { + return TimelineEntryRelevance(score: 0.1) + } + + if let dateStarts = event.dateStarts, + let dateEnds = event.dateEnds { + return TimelineEntryRelevance(score: 1, duration: dateStarts.timeIntervalSince1970 - dateEnds.timeIntervalSince1970) + } else { + return TimelineEntryRelevance(score: 0.5) + } + } + } + + var schedule: [Vulcan.ScheduleEvent] { + let context = CoreDataModel.shared.persistentContainer.viewContext + let fetchRequest: NSFetchRequest = StoredScheduleEvent.fetchRequest() + fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(StoredScheduleEvent.dateStartsEpoch), ascending: true)] + + if let storedSchedule = try? context.fetch(fetchRequest) { + return storedSchedule + .compactMap { entity -> Vulcan.ScheduleEvent? in + guard var event = Vulcan.ScheduleEvent(from: entity) else { + return nil + } + + let employeeFetchRequest: NSFetchRequest = DictionaryEmployee.fetchRequest() + employeeFetchRequest.predicate = NSPredicate(format: "id == %d", event.employeeID) + if let employee: DictionaryEmployee = (try? context.fetch(employeeFetchRequest))?.first { + event.employee = employee + } + + let timeFetchRequest: NSFetchRequest = DictionaryLessonTime.fetchRequest() + timeFetchRequest.predicate = NSPredicate(format: "id == %d", event.lessonTimeID) + guard let time: DictionaryLessonTime = (try? context.fetch(timeFetchRequest))?.first else { + return nil + } + event.dateStartsEpoch = TimeInterval(event.dateEpoch + Int(time.start) + 3600) + event.dateEndsEpoch = TimeInterval(event.dateEpoch + Int(time.end) + 3600) + + return event + } + .filter { $0.dateStarts != nil && $0.dateEnds != nil } + .sorted { $0.dateStarts ?? $0.date < $1.dateStarts ?? $0.date } + .filter { $0.isUserSchedule } + .filter { $0.dateStarts ?? $0.date >= Date().startOfDay } + } else { + return [] + } + } + + func placeholder(in context: Context) -> Entry { + Entry(date: Date(), currentEvent: nil, nextEvents: []) + } + + func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { + var currentEvent: Vulcan.ScheduleEvent = Vulcan.ScheduleEvent(dateEpoch: Int(Date().startOfDay.timeIntervalSince1970), lessonOfTheDay: 1, lessonTimeID: 0, subjectID: 0, subjectName: "Spanish".localized, divisionShort: nil, room: "03", employeeID: 1, helpingEmployeeID: nil, oldEmployeeID: nil, oldHelpingEmployeeID: nil, scheduleID: 1, note: nil, labelStrikethrough: false, labelBold: false, isUserSchedule: false, employeeFullName: "Ben Chang") + currentEvent.dateStartsEpoch = Date().timeIntervalSince1970 + currentEvent.dateEndsEpoch = (Calendar.autoupdatingCurrent.date(byAdding: .hour, value: 1, to: Date()) ?? Date()).timeIntervalSince1970 + + var nextEvent = currentEvent + nextEvent.dateStartsEpoch = (Calendar.autoupdatingCurrent.date(byAdding: .hour, value: 1, to: nextEvent.dateStarts ?? nextEvent.date) ?? nextEvent.date).timeIntervalSince1970 + nextEvent.dateEndsEpoch = (Calendar.autoupdatingCurrent.date(byAdding: .hour, value: 1, to: nextEvent.dateEnds ?? nextEvent.date) ?? nextEvent.date).timeIntervalSince1970 + + let entry = Entry(date: Date(), currentEvent: currentEvent, nextEvents: [nextEvent]) + completion(entry) + } + + func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { + var entries: [Entry] = schedule + .map { event -> [Entry] in + let nextEvents = schedule + .filter { $0.dateStarts ?? $0.date > event.dateStarts ?? event.date } + + var entries: [Entry] = [Entry(date: event.dateStarts ?? event.date, currentEvent: event, nextEvents: nextEvents)] + + // Spaces between events + if let currentEventDateEnds = event.dateEnds, + let nextEventDateStarts = nextEvents.first?.dateStarts, + currentEventDateEnds != nextEventDateStarts { + entries.append(Entry(date: currentEventDateEnds, currentEvent: nil, nextEvents: nextEvents)) + } + + return entries + } + .flatMap { $0 } + .sorted { $0.date < $1.date } + + // Last entry + entries.append(Entry(date: entries.last?.currentEvent?.dateEnds ?? entries.last?.date.addingTimeInterval(3600) ?? Date().addingTimeInterval(3600), currentEvent: nil, nextEvents: [])) + + // If firstTimelineEventIndex == 0 (the event is first for this day), add new one + if let firstTimelineEvent = entries.first?.currentEvent, + let firstTimelineEventIndex = schedule.firstIndex(of: firstTimelineEvent), + firstTimelineEventIndex == 0 { + entries.insert(Entry(date: Date().startOfDay, currentEvent: nil, nextEvents: schedule), at: 0) + } + + let policy: TimelineReloadPolicy + if let lastEventDateEnds = entries.last?.currentEvent?.dateEnds ?? entries.last?.nextEvents.last?.dateEnds { + policy = .after(lastEventDateEnds) + } else { + policy = .atEnd + } + + completion(Timeline(entries: entries, policy: policy)) + } +} diff --git a/Widget/Data/NowProvider.swift b/Widget/Data/NowProvider.swift new file mode 100644 index 0000000..76e5430 --- /dev/null +++ b/Widget/Data/NowProvider.swift @@ -0,0 +1,106 @@ +// +// Provider.swift +// Widget +// +// Created by royal on 03/09/2020. +// + +import WidgetKit +import SwiftUI +import Intents +import Vulcan +import CoreData + +struct NowProvider: TimelineProvider { + struct Entry: TimelineEntry { + let date: Date + let event: Vulcan.ScheduleEvent? + + var relevance: TimelineEntryRelevance? { + guard let event: Vulcan.ScheduleEvent = self.event else { + return TimelineEntryRelevance(score: 0.1) + } + + if let dateStarts = event.dateStarts, + let dateEnds = event.dateEnds { + return TimelineEntryRelevance(score: 1, duration: dateStarts.timeIntervalSince1970 - dateEnds.timeIntervalSince1970) + } else { + return TimelineEntryRelevance(score: 0.5) + } + } + } + + var schedule: [Vulcan.ScheduleEvent] { + let context = CoreDataModel.shared.persistentContainer.viewContext + let fetchRequest: NSFetchRequest = StoredScheduleEvent.fetchRequest() + fetchRequest.sortDescriptors = [NSSortDescriptor(key: #keyPath(StoredScheduleEvent.dateStartsEpoch), ascending: true)] + + if let storedSchedule = try? context.fetch(fetchRequest) { + return storedSchedule + .compactMap { entity -> Vulcan.ScheduleEvent? in + guard var event = Vulcan.ScheduleEvent(from: entity) else { + return nil + } + + let employeeFetchRequest: NSFetchRequest = DictionaryEmployee.fetchRequest() + employeeFetchRequest.predicate = NSPredicate(format: "id == %d", event.employeeID) + if let employee: DictionaryEmployee = (try? context.fetch(employeeFetchRequest))?.first { + event.employee = employee + } + + let timeFetchRequest: NSFetchRequest = DictionaryLessonTime.fetchRequest() + timeFetchRequest.predicate = NSPredicate(format: "id == %d", event.lessonTimeID) + guard let time: DictionaryLessonTime = (try? context.fetch(timeFetchRequest))?.first else { + return nil + } + event.dateStartsEpoch = TimeInterval(event.dateEpoch + Int(time.start) + 3600) + event.dateEndsEpoch = TimeInterval(event.dateEpoch + Int(time.end) + 3600) + + return event + } + .filter { $0.dateStarts != nil && $0.dateEnds != nil } + .sorted { $0.dateStarts ?? $0.date < $1.dateStarts ?? $0.date } + .filter { $0.isUserSchedule } + } else { + return [] + } + } + + func placeholder(in context: Context) -> Entry { + Entry(date: Date(), event: nil) + } + + func getSnapshot(in context: Context, completion: @escaping (Entry) -> Void) { + var event: Vulcan.ScheduleEvent = Vulcan.ScheduleEvent(dateEpoch: Int(Date().startOfDay.timeIntervalSince1970), lessonOfTheDay: 1, lessonTimeID: 0, subjectID: 0, subjectName: "Spanish".localized, divisionShort: nil, room: "03", employeeID: 1, helpingEmployeeID: nil, oldEmployeeID: nil, oldHelpingEmployeeID: nil, scheduleID: 1, note: nil, labelStrikethrough: false, labelBold: false, isUserSchedule: false, employeeFullName: "Ben Chang") + event.dateStartsEpoch = Date().timeIntervalSince1970 + event.dateEndsEpoch = (Calendar.autoupdatingCurrent.date(byAdding: .hour, value: 1, to: Date()) ?? Date()).timeIntervalSince1970 + + let entry = Entry(date: Date(), event: event) + completion(entry) + } + + func getTimeline(in context: Context, completion: @escaping (Timeline) -> Void) { + var entries: [Entry] = self.schedule + .filter { $0.dateStarts != nil } + .filter { $0.dateEnds ?? $0.date >= Date().startOfDay } + .timeline() + .map { date, event in + Entry(date: date, event: event) + } + .sorted { $0.date < $1.date } + + entries.append(Entry(date: entries.last?.event?.dateEnds ?? Date(), event: nil)) + + completion(Timeline(entries: entries, policy: .atEnd)) + } + + static var noEventSubtitle: String { + let strings: [String] = [ + "Watermelon is 92% water.", + "The opening scene in \"Friends\" wasn't shot in New York.", + "You look good today." + ] + + return strings[Int.random(in: 0...(strings.count - 1))].localized + } +} diff --git a/Widget/Info.plist b/Widget/Info.plist new file mode 100644 index 0000000..260cf72 --- /dev/null +++ b/Widget/Info.plist @@ -0,0 +1,29 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Widget + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + NSExtension + + NSExtensionPointIdentifier + com.apple.widgetkit-extension + + + diff --git a/Widget/Localization/en.lproj/Localizable.strings b/Widget/Localization/en.lproj/Localizable.strings new file mode 100644 index 0000000..81b6cf0 --- /dev/null +++ b/Widget/Localization/en.lproj/Localizable.strings @@ -0,0 +1,21 @@ +/* + Localizable.strings + vulcan + en_US + + Created by royal on 03/09/2020. + +*/ + +"NOW_DESCRIPTION" = "Displays your current event. It will change halfway through the event."; +"NEXTUP_DESCRIPTION" = "Displays your next events."; + +"Spanish" = "Spanish"; + +"No events for now 😊" = "No events for now 😊"; + +"Now" = "Now"; +"Nothing for now" = "Nothing for now"; + +"Next up" = "Next up"; +"Nothing left" = "Nothing left"; diff --git a/Widget/Localization/pl.lproj/Localizable.strings b/Widget/Localization/pl.lproj/Localizable.strings new file mode 100644 index 0000000..52839a0 --- /dev/null +++ b/Widget/Localization/pl.lproj/Localizable.strings @@ -0,0 +1,21 @@ +/* + Localizable.strings + vulcan + pl_PL + + Created by royal on 03/09/2020. + +*/ + +"NOW_DESCRIPTION" = "Wyświetla twoją teraźniejszą lekcję. Widget pokaże następne wydarzenie w połowie lekcji."; +"NEXTUP_DESCRIPTION" = "Wyświetla twoje następne lekcje."; + +"Spanish" = "Hiszpański"; + +"No events for now 😊" = "Nic w najbliższym czasie 😊"; + +"Now" = "Teraz"; +"Nothing for now" = "Nic w tym momencie"; + +"Next up" = "Następnie"; +"Nothing left" = "Nic nie zostało"; diff --git a/Widget/Views/Components/SmallEventCell.swift b/Widget/Views/Components/SmallEventCell.swift new file mode 100644 index 0000000..1492d25 --- /dev/null +++ b/Widget/Views/Components/SmallEventCell.swift @@ -0,0 +1,45 @@ +// +// SmallEventCell.swift +// Widget +// +// Created by royal on 18/10/2020. +// + +import SwiftUI +import Vulcan + +struct SmallEventCell: View { + let event: Vulcan.ScheduleEvent + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + // Time + if let dateStarts = event.dateStarts, + let dateEnds = event.dateEnds { + Text("\(dateStarts.localizedTime) - \(dateEnds.localizedTime)") + .font(.footnote) + .foregroundColor(.secondary) + .lineLimit(1) + } + + // Subject, room + HStack { + Text(event.subjectName) + .font(.headline) + .lineLimit(1) + .allowsTightening(true) + .truncationMode(.middle) + + Spacer() + + Text(event.room) + } + } + } +} + +/* struct SmallEventCell_Previews: PreviewProvider { + static var previews: some View { + SmallEventCell() + } +} */ diff --git a/Widget/Views/CurrentEventView.swift b/Widget/Views/CurrentEventView.swift new file mode 100644 index 0000000..da92885 --- /dev/null +++ b/Widget/Views/CurrentEventView.swift @@ -0,0 +1,59 @@ +// +// CurrentEventView.swift +// Widget +// +// Created by royal on 18/10/2020. +// + +import SwiftUI +import Vulcan + +struct CurrentEventView: View { + let event: Vulcan.ScheduleEvent? + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + Text("Now") + .font(.subheadline) + .bold() + .foregroundColor(.white) + + Spacer() + + if let event = event { + // Time / Room + Group { + if let dateStarts = event.dateStarts { + Text("\(dateStarts.localizedTime) • \(event.room)") + } else { + Text(event.room) + } + } + .font(.subheadline) + .foregroundColor(Color.white.opacity(0.8)) + + // Subject + Text(event.subjectName) + .font(.headline) + .foregroundColor(.white) + .truncationMode(.tail) + .lineLimit(2) + } else { + Text("Nothing for now") + .font(.headline) + .foregroundColor(.white) + .truncationMode(.tail) + .lineLimit(2) + } + } + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) + .padding() + .background(LinearGradient(gradient: Gradient(colors: [Color("Background/Top"), Color("Background/Bottom")]), startPoint: .top, endPoint: .bottom)) + } +} + +struct CurrentEventView_Previews: PreviewProvider { + static var previews: some View { + CurrentEventView(event: nil) + } +} diff --git a/Widget/Views/EventView.swift b/Widget/Views/EventView.swift new file mode 100644 index 0000000..cc5e15a --- /dev/null +++ b/Widget/Views/EventView.swift @@ -0,0 +1,93 @@ +// +// EventView.swift +// Widget +// +// Created by royal on 18/10/2020. +// + +import SwiftUI +import Vulcan + +struct EventView: View { + let event: Vulcan.ScheduleEvent? + + var body: some View { + if let event = event { + VStack(alignment: .leading) { + // Top line: time and room + HStack { + if let dateStarts = event.dateStarts { + Text(dateStarts.localizedTime) + .font(.subheadline) + .bold() + .foregroundColor(.white) + } + + Spacer() + + Text(event.room) + .font(.subheadline) + .foregroundColor(.white) + } + + Spacer() + + // Middle line: subject name + Text(event.subjectName) + .font(.headline) + .foregroundColor(.white) + .truncationMode(.tail) + .minimumScaleFactor(0.75) + .lineLimit(3) + + // Bottom line: employee name + Group { + if let employeeName = event.employee?.name, + let employeeSurname = event.employee?.surname { + Text("\(employeeName) \(employeeSurname)") + } else if let employeeFullName = event.employeeFullName { + Text(employeeFullName) + } + } + .font(.subheadline) + .foregroundColor(Color.white.opacity(0.8)) + .minimumScaleFactor(0.75) + .lineLimit(2) + + } + .padding() + .background(LinearGradient(gradient: Gradient(colors: [Color("Background/Top"), Color("Background/Bottom")]), startPoint: .top, endPoint: .bottom)) + } else { + VStack(alignment: .leading) { + Text("vulcan") + .font(.subheadline) + .bold() + .foregroundColor(.white) + + Spacer() + + Text("No events for now 😊") + .font(.headline) + .foregroundColor(.white) + .truncationMode(.tail) + .minimumScaleFactor(0.75) + .lineLimit(3) + + /* Text(Provider.noEventSubtitle) + .font(.subheadline) + .foregroundColor(Color.white.opacity(0.8)) + .minimumScaleFactor(0.75) + .lineLimit(3) */ + } + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) + .padding() + .background(LinearGradient(gradient: Gradient(colors: [Color("Background/Top"), Color("Background/Bottom")]), startPoint: .top, endPoint: .bottom)) + } + } +} + +struct EventView_Previews: PreviewProvider { + static var previews: some View { + EventView(event: nil) + } +} diff --git a/Widget/Views/NextEventView.swift b/Widget/Views/NextEventView.swift new file mode 100644 index 0000000..3651288 --- /dev/null +++ b/Widget/Views/NextEventView.swift @@ -0,0 +1,65 @@ +// +// NextEventView.swift +// Widget +// +// Created by royal on 18/10/2020. +// + +import SwiftUI +import Vulcan + +struct NextEventView: View { + let event: Vulcan.ScheduleEvent? + + @Environment(\.colorScheme) var colorScheme: ColorScheme + + var foregroundColor: Color { + colorScheme == .light ? .accentColor : .white + } + + var body: some View { + VStack(alignment: .leading, spacing: 2) { + Text("Next up") + .font(.subheadline) + .bold() + .foregroundColor(foregroundColor) + + Spacer() + + if let event = event { + // Time / Room + Group { + if let dateStarts = event.dateStarts { + Text("\(dateStarts.localizedTime) • \(event.room)") + } else { + Text(event.room) + } + } + .lineLimit(1) + .font(.subheadline) + .foregroundColor(foregroundColor.opacity(0.5)) + + // Subject + Text(event.subjectName) + .font(.headline) + .foregroundColor(foregroundColor) + .truncationMode(.tail) + .lineLimit(2) + } else { + Text("Nothing left") + .font(.headline) + .foregroundColor(foregroundColor) + .truncationMode(.tail) + .lineLimit(2) + } + } + .frame(minWidth: 0, maxWidth: .infinity, alignment: .leading) + .padding() + } +} + +struct NextEventView_Previews: PreviewProvider { + static var previews: some View { + NextEventView(event: nil) + } +} diff --git a/Widget/Views/NextUp/NextUpEntryView.swift b/Widget/Views/NextUp/NextUpEntryView.swift new file mode 100644 index 0000000..8bb4cf5 --- /dev/null +++ b/Widget/Views/NextUp/NextUpEntryView.swift @@ -0,0 +1,72 @@ +// +// NextUpEntryView.swift +// Widget +// +// Created by royal on 03/09/2020. +// + +import SwiftUI +import WidgetKit + +struct NextUpEntryView: View { + let entry: NextUpProvider.Entry + + @Environment(\.widgetFamily) private var widgetFamily: WidgetFamily + @Environment(\.colorScheme) var colorScheme: ColorScheme + + var backgroundColor: Color { + colorScheme == .light ? .white : Color(UIColor.systemGroupedBackground) + } + + var systemSmallView: some View { + CurrentEventView(event: entry.currentEvent) + } + + var systemMediumView: some View { + HStack(spacing: 0) { + CurrentEventView(event: entry.currentEvent) + .mask(ContainerRelativeShape()) + .shadow(color: Color.black.opacity(0.2), radius: 10) + + NextEventView(event: entry.nextEvents.first) + } + .background(backgroundColor) + } + + var systemLargeView: some View { + GeometryReader { geometry in + VStack(spacing: 0) { + CurrentEventView(event: entry.currentEvent) + .frame(height: geometry.size.height / 2) + .mask(ContainerRelativeShape()) + .shadow(color: Color.black.opacity(0.2), radius: 10) + + VStack(alignment: .center) { + ForEach(entry.nextEvents.prefix(3)) { event in + SmallEventCell(event: event) + .padding(.vertical, 2) + } + } + .padding(.horizontal) + .padding(.vertical) + .frame(height: geometry.size.height / 2) + } + .background(backgroundColor) + } + } + + var body: some View { + switch widgetFamily { + case .systemSmall: systemSmallView + case .systemMedium: systemMediumView + case .systemLarge: systemLargeView + @unknown default: systemSmallView + } + } +} + +struct NextUpEntryView_Previews: PreviewProvider { + static var previews: some View { + NextUpEntryView(entry: .init(date: Date(), currentEvent: nil, nextEvents: [])) + } +} diff --git a/Widget/Views/Now/NowEntryView.swift b/Widget/Views/Now/NowEntryView.swift new file mode 100644 index 0000000..3c9194a --- /dev/null +++ b/Widget/Views/Now/NowEntryView.swift @@ -0,0 +1,23 @@ +// +// NowEntryView.swift +// Widget +// +// Created by royal on 18/10/2020. +// + +import SwiftUI +import WidgetKit + +struct NowEntryView: View { + let entry: NowProvider.Entry + + var body: some View { + EventView(event: entry.event) + } +} + +struct NowEntryView_Previews: PreviewProvider { + static var previews: some View { + NowEntryView(entry: .init(date: Date(), event: nil)) + } +} diff --git a/Widget/VulcanWidget.swift b/Widget/VulcanWidget.swift new file mode 100644 index 0000000..e79d2a5 --- /dev/null +++ b/Widget/VulcanWidget.swift @@ -0,0 +1,45 @@ +// +// VulcanWidget.swift +// Widget +// +// Created by royal on 03/09/2020. +// + +import WidgetKit +import SwiftUI + +struct NowWidget: Widget { + var body: some WidgetConfiguration { + StaticConfiguration(kind: "NowWidget", provider: NowProvider()) { entry in + NowEntryView(entry: entry) + .widgetURL(URL(string: "vulcan://schedule")) + .accentColor(Color("AccentColor")) + } + .configurationDisplayName("Now") + .description("NOW_DESCRIPTION") + .supportedFamilies([.systemSmall, .systemMedium]) + } +} + +struct NextUpWidget: Widget { + var body: some WidgetConfiguration { + StaticConfiguration(kind: "NextUpWidget", provider: NextUpProvider()) { entry in + NextUpEntryView(entry: entry) + .widgetURL(URL(string: "vulcan://schedule")) + .accentColor(Color("AccentColor")) + } + .configurationDisplayName("Next up") + .description("NEXTUP_DESCRIPTION") + .supportedFamilies([.systemSmall, .systemMedium]) + } +} + +@main +struct VulcanWidget: WidgetBundle { + var body: some Widget { + NowWidget() + NextUpWidget() + } +} + + diff --git a/Widget/Widget.entitlements b/Widget/Widget.entitlements new file mode 100644 index 0000000..48fd787 --- /dev/null +++ b/Widget/Widget.entitlements @@ -0,0 +1,14 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.application-groups + + group.dev.niepostek.vulcanGroup + + com.apple.security.network.client + + + diff --git a/iOS/Info.plist b/iOS/Info.plist new file mode 100644 index 0000000..d525132 --- /dev/null +++ b/iOS/Info.plist @@ -0,0 +1,100 @@ + + + + + BGTaskSchedulerPermittedIdentifiers + + dev.niepostek.vulcan.refreshData + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + vulcan + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleURLTypes + + + CFBundleTypeRole + Editor + CFBundleURLName + dev.niepostek.vulcan + CFBundleURLSchemes + + vulcan + + + + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + ITSAppUsesNonExemptEncryption + + LSApplicationCategoryType + public.app-category.education + LSRequiresIPhoneOS + + NSAppTransportSecurity + + NSExceptionDomains + + komponenty.vulcan.net.pl + + NSExceptionAllowsInsecureHTTPLoads + + NSIncludesSubdomains + + + + + NSCalendarsUsageDescription + App will use Your calendar to add new task events. + NSRemindersUsageDescription + App will use Your reminders to add new task reminders. + NSUserActivityTypes + + GroupIntent + + UIApplicationSceneManifest + + UIApplicationSupportsMultipleScenes + + + UIApplicationSupportsIndirectInputEvents + + UIBackgroundModes + + fetch + processing + remote-notification + + UILaunchScreen + + UILaunchStoryboardName + LaunchScreen + UIRequiredDeviceCapabilities + + armv7 + + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + + diff --git a/iOS/Localization/en.lproj/InfoPlist.strings b/iOS/Localization/en.lproj/InfoPlist.strings new file mode 100644 index 0000000..af1658e --- /dev/null +++ b/iOS/Localization/en.lproj/InfoPlist.strings @@ -0,0 +1,11 @@ +/* + InfoPlist.strings + vulcan + en_US + + Created by royal on 19/09/2020. + +*/ + +NSCalendarsUsageDescription = "App will use Your calendar to add new task events."; +NSRemindersUsageDescription = "App will use Your reminders to add new task reminders."; diff --git a/iOS/Localization/pl.lproj/InfoPlist.strings b/iOS/Localization/pl.lproj/InfoPlist.strings new file mode 100644 index 0000000..a00d5e4 --- /dev/null +++ b/iOS/Localization/pl.lproj/InfoPlist.strings @@ -0,0 +1,11 @@ +/* + InfoPlist.strings + vulcan + pl_PL + + Created by royal on 19/09/2020. + +*/ + +NSCalendarsUsageDescription = "Aplikacja będzie używać kalendarza aby dodawać wydarzenia z nowymi zadaniami."; +NSRemindersUsageDescription = "Aplikacja będzie używać przypomnień aby dodawać przypomnienia z nowymi zadaniami."; diff --git a/iOS/Views/AppIconView.swift b/iOS/Views/AppIconView.swift new file mode 100644 index 0000000..bdea5a1 --- /dev/null +++ b/iOS/Views/AppIconView.swift @@ -0,0 +1,43 @@ +// +// AppIconView.swift +// iOS +// +// Created by royal on 21/09/2020. +// + +import SwiftUI + +/// View showing list of available app icons. +struct AppIconView: View { + var body: some View { + List(Bundle.main.appIcons, id: \.self) { (icon) in + HStack { + Image(icon) + .cornerRadius(16) + + Spacer() + + if (Bundle.main.currentAppIcon == icon) { + Image(systemName: "checkmark") + .font(.headline) + } + } + .id(icon) + .padding(.vertical, 10) + .contentShape(Rectangle()) + .onTapGesture { + if (Bundle.main.currentAppIcon != icon) { + generateHaptic(.light) + } + } + } + .listStyle(InsetGroupedListStyle()) + .navigationTitle(Text("App Icon")) + } +} + +struct AppIconView_Previews: PreviewProvider { + static var previews: some View { + AppIconView() + } +} diff --git a/iOS/Views/ColorSchemeSettingsView.swift b/iOS/Views/ColorSchemeSettingsView.swift new file mode 100644 index 0000000..a30cb89 --- /dev/null +++ b/iOS/Views/ColorSchemeSettingsView.swift @@ -0,0 +1,58 @@ +// +// ColorSchemeSettingsView.swift +// iOS +// +// Created by royal on 21/09/2020. +// + +import SwiftUI + +/// View showing list of available color schemes. +struct ColorSchemeSettingsView: View { + @AppStorage(UserDefaults.AppKeys.colorScheme.rawValue, store: .group) var colorScheme: String = "Default" + + var body: some View { + List(Bundle.main.colorSchemes, id: \.self) { (scheme) in + HStack { + VStack(alignment: .leading) { + Text(LocalizedStringKey(scheme)) + .font(.headline) + .padding(.bottom, 2) + + HStack { + Text("6").foregroundColor(Color("ColorSchemes/\(scheme)/6", bundle: Bundle(identifier: "Colors"))) + Text("5").foregroundColor(Color("ColorSchemes/\(scheme)/5", bundle: Bundle(identifier: "Colors"))) + Text("4").foregroundColor(Color("ColorSchemes/\(scheme)/4", bundle: Bundle(identifier: "Colors"))) + Text("3").foregroundColor(Color("ColorSchemes/\(scheme)/3", bundle: Bundle(identifier: "Colors"))) + Text("2").foregroundColor(Color("ColorSchemes/\(scheme)/2", bundle: Bundle(identifier: "Colors"))) + Text("1").foregroundColor(Color("ColorSchemes/\(scheme)/1", bundle: Bundle(identifier: "Colors"))) + Text("-").foregroundColor(Color("ColorSchemes/\(scheme)/0", bundle: Bundle(identifier: "Colors"))) + } + } + + Spacer() + + if colorScheme == scheme { + Image(systemName: "checkmark") + .font(.headline) + .foregroundColor(.accentColor) + } + } + .id(scheme) + .padding(.vertical, 10) + .contentShape(Rectangle()) + .onTapGesture { + colorScheme = scheme + generateHaptic(.light) + } + } + .listStyle(InsetGroupedListStyle()) + .navigationTitle(Text("Color Scheme")) + } +} + +struct ColorSchemeSettingsView_Previews: PreviewProvider { + static var previews: some View { + ColorSchemeSettingsView() + } +} diff --git a/iOS/Views/DebugView.swift b/iOS/Views/DebugView.swift new file mode 100644 index 0000000..6c3c001 --- /dev/null +++ b/iOS/Views/DebugView.swift @@ -0,0 +1,152 @@ +// +// DebugView.swift +// vulcan +// +// Created by royal on 02/06/2020. +// Copyright © 2020 shameful. All rights reserved. +// + +import SwiftUI +import WidgetKit +import BackgroundTasks +import os +import Vulcan +import CoreSpotlight + +/// Debug view +struct DebugView: View { + @EnvironmentObject var vulcan: Vulcan + + @State private var pendingTaskRequests: [BGTaskRequest] = [] + private let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).Debug", category: "Debug") + + private var logsView: some View { + List([""], id: \.self) { entry in + Text(entry.isEmpty ? "" : entry) + .foregroundColor(entry.isEmpty ? .secondary : .primary) + .multilineTextAlignment(.leading) + .lineLimit(nil) + .font(.system(.body, design: .monospaced)) + } + .navigationTitle(Text("Logs")) + } + + var body: some View { + Form { + // VulcanAPI + Section(header: Text("VulcanAPI").textCase(.none)) { + // Reset dictionary + Button(action: { + logger.debug("Resetting dictionary!") + vulcan.getDictionary(force: true) + generateHaptic(.light) + }) { + Text("Reset dictionary") + .foregroundColor(.red) + } + + NavigationLink(destination: logsView) { + Text("Logs") + .font(.body) + .bold() + } + } + .padding(.vertical, 10) + + // Core Data + Section(header: Text("Core Data").textCase(.none)) { + VStack(alignment: .leading) { + Text("Database URL") + .font(.headline) + Text(CoreDataModel.shared.persistentContainer.persistentStoreDescriptions.first?.url?.absoluteString ?? "none") + .font(.body) + .lineLimit(nil) + } + + Button(action: { + logger.debug("Resetting CoreData DB!") + CoreDataModel.shared.clearDatabase() + generateHaptic(.light) + }) { + Text("Reset CoreData DB") + .foregroundColor(.red) + } + } + .padding(.vertical, 10) + + // Background tasks + Section(header: Text("Background tasks").textCase(.none)) { + // Schedule new + Button(action: { + logger.debug("Scheduling new BGRefresh task.") + (UIApplication.shared.delegate as? AppDelegate)?.scheduleBackgroundRefresh() + BGTaskScheduler.shared.getPendingTaskRequests(completionHandler: { (items) in + pendingTaskRequests = items + }) + generateHaptic(.light) + }) { + Text("Register refresh background task") + } + + // Cancel all + Button(action: { + logger.debug("Cancelling all BGRefresh tasks.") + BGTaskScheduler.shared.cancelAllTaskRequests() + BGTaskScheduler.shared.getPendingTaskRequests(completionHandler: { (items) in + pendingTaskRequests = items + }) + generateHaptic(.light) + }) { + Text("Cancel all tasks") + } + + // Scheduled events + ForEach(pendingTaskRequests, id: \.identifier) { (item) in + Text(String(describing: item)) + } + } + .padding(.vertical, 10) + + // WidgetKit + Section(header: Text("WidgetKit").textCase(.none)) { + // Refresh + Button(action: { + logger.debug("Reloading widget timelines.") + WidgetCenter.shared.reloadAllTimelines() + generateHaptic(.light) + }) { + Text("Reload all timelines") + } + } + .padding(.vertical, 10) + + // CoreSpotlight + Section(header: Text("CoreSpotlight").textCase(.none)) { + // Remove all + Button("Remove all") { + generateHaptic(.light) + logger.debug("Removing all searchable items") + CSSearchableIndex.default().deleteAllSearchableItems { error in + if let error = error { + logger.error("\(error.localizedDescription)") + } + } + } + } + .padding(.vertical, 10) + } + .listStyle(InsetGroupedListStyle()) + .navigationTitle(Text("Debug")) + .onAppear { + BGTaskScheduler.shared.getPendingTaskRequests { items in + pendingTaskRequests = items + } + } + } +} + +struct DebugView_Previews: PreviewProvider { + static var previews: some View { + DebugView() + } +} diff --git a/iOS/Views/LicenseView.swift b/iOS/Views/LicenseView.swift new file mode 100644 index 0000000..e969ef1 --- /dev/null +++ b/iOS/Views/LicenseView.swift @@ -0,0 +1,37 @@ +// +// LicenseView.swift +// iOS +// +// Created by royal on 21/09/2020. +// + +import SwiftUI + +struct LicenseView: View { + let KeychainAccessLicense: String = "The MIT License (MIT)\nCopyright (c) 2014 kishikawa katsumi\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE." + let KeychainAccessURL: URL? = URL(string: "https://github.com/kishikawakatsumi/KeychainAccess")! + + var body: some View { + List { + // KeychainAccess + DisclosureGroup("KeychainAccess") { + Text(KeychainAccessLicense) + .font(.system(.body, design: .monospaced)) + .onTapGesture { + guard let url = KeychainAccessURL else { return } + generateHaptic(.light) + UIApplication.shared.open(url) + } + } + .padding(.vertical) + } + .listStyle(InsetGroupedListStyle()) + .navigationTitle(Text("Libraries")) + } +} + +struct LicenseView_Previews: PreviewProvider { + static var previews: some View { + LicenseView() + } +} diff --git a/iOS/Views/SettingsView.swift b/iOS/Views/SettingsView.swift new file mode 100644 index 0000000..2550785 --- /dev/null +++ b/iOS/Views/SettingsView.swift @@ -0,0 +1,322 @@ +// +// SettingsView.swift +// iOS +// +// Created by royal on 24/06/2020. +// + +import SwiftUI +import Vulcan +import UserNotifications +import os + +/// Component used as a setting option cell. +fileprivate struct SettingsOption: View { + @Binding var setting: Bool + let title: String + let subtitle: String + + var body: some View { + VStack(alignment: .leading) { + Toggle(isOn: $setting.animation(), label: { + Text(LocalizedStringKey(title)) + .font(.body) + .bold() + Spacer() + }) + .toggleStyle(SwitchToggleStyle(tint: .accentColor)) + + Text(LocalizedStringKey(subtitle)) + .font(.footnote) + .foregroundColor(.secondary) + .lineLimit(nil) + } + } +} + +/// List view, containing list with options and NavigationBar NavigationLink to user list. +struct SettingsView: View { + @EnvironmentObject var vulcan: Vulcan + @EnvironmentObject var settings: SettingsModel + + @State private var showingSetupView: Bool = false + @State private var showingResetSheet: Bool = false + @State private var showingResetAlert: Bool = false + + @AppStorage(UserDefaults.AppKeys.enableScheduleNotifications.rawValue, store: .group) public var enableScheduleNotifications: Bool = false + @AppStorage(UserDefaults.AppKeys.enableTaskNotifications.rawValue, store: .group) public var enableTaskNotifications: Bool = false + + private let logger: Logger = Logger(subsystem: "\(Bundle.main.bundleIdentifier!).VulcanApp", category: "Settings") + + private func manageScheduleNotifications(enabled: Bool) { + if !enabled { + logger.debug("Removing all notifications with identifier \"ScheduleNotification\".") + UNUserNotificationCenter.current().getPendingNotificationRequests() { notifications in + let identifiers = notifications.filter({ $0.content.categoryIdentifier.contains("ScheduleNotification") }).map(\.identifier) + UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers) + } + + return + } + + UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .alert, .badge]) { granted, error in + if let error = error { + logger.error("Error granting notification permission: \(error.localizedDescription)") + } + + logger.debug("Granted notification permissions: \(granted)") + } + + vulcan.schedule + .flatMap(\.events) + .filter { $0.dateStarts != nil && $0.dateStarts ?? $0.date >= Date() } + .filter { $0.isUserSchedule } + .forEach { event in + vulcan.addScheduleEventNotification(event) + } + } + + private func manageTaskNotifications(enabled: Bool) { + if !enabled { + logger.debug("Removing all notifications with identifier \"TaskNotification\".") + UNUserNotificationCenter.current().getPendingNotificationRequests() { notifications in + let identifiers = notifications.filter({ $0.content.categoryIdentifier.contains("TaskNotification") }).map(\.identifier) + UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers) + } + + return + } + + UNUserNotificationCenter.current().requestAuthorization(options: [.sound, .alert, .badge]) { granted, error in + if let error = error { + logger.error("Error granting notification permission: \(error.localizedDescription)") + } + + logger.debug("Granted notification permissions: \(granted)") + } + + vulcan.tasks.combined + .filter { $0.date >= Date() } + .forEach { task in + vulcan.addTaskNotification(task) + } + } + + private var generalSection: some View { + Section(header: Text("General").sectionTitle()) { + // Mark message as read on open + SettingsOption(setting: $settings.readMessageOnOpen, title: "SETTINGS_READMESSAGEONOPEN", subtitle: "SETTINGS_READMESSAGEONOPEN_TOOLTIP") + } + .padding(.vertical, 10) + } + + private var uonetSection: some View { + Section(header: Text("UONET+").sectionTitle()) { + // Log in/out + HStack { + if (vulcan.currentUser != nil) { + Text("SETTINGS_LOGGEDIN : \(vulcan.currentUser?.userLogin ?? "")") + .font(.body) + .bold() + .id("settings:loggedin:" + String(describing: vulcan.currentUser != nil)) + Spacer() + Button(action: { + generateHaptic(.light) + vulcan.logOut() + }) { + Text("Log out") + .foregroundColor(.red) + .id("settings:logout") + } + .id("settings:loggedin") + } else { + Text("Not logged in") + .font(.body) + .bold() + .id("settings:notloggedin:") + Spacer() + Button(action: { + generateHaptic(.light) + withAnimation { + showingSetupView = true + } + }) { + Text("Log in") + .foregroundColor(.accentColor) + .id("settings:login") + } + .id("settings:notloggedin") + } + } + + if vulcan.currentUser != nil || vulcan.users.count > 0 { + NavigationLink(destination: UsersView()) { + Text("Users") + .font(.body) + .bold() + } + } + } + .padding(.vertical, 10) + } + + private var notificationsSection: some View { + Section(header: Text("Notifications").sectionTitle()) { + // Schedule + SettingsOption(setting: $settings.enableScheduleNotifications, title: "SETTINGS_SCHEDULENOTIFICATIONS", subtitle: "SETTINGS_SCHEDULENOTIFICATIONS_TOOLTIP") + .onChange(of: enableScheduleNotifications, perform: manageScheduleNotifications) + + // Tasks + SettingsOption(setting: $settings.enableTaskNotifications, title: "SETTINGS_TASKNOTIFICATIONS", subtitle: "SETTINGS_TASKNOTIFICATIONS_TOOLTIP") + .onChange(of: enableTaskNotifications, perform: manageTaskNotifications) + } + .padding(.vertical, 10) + } + + private var interfaceSection: some View { + Section(header: Text("Interface").sectionTitle()) { + // Show all schedule events + SettingsOption(setting: $settings.showAllScheduleEvents, title: "SETTINGS_SCHEDULEALLEVENTS", subtitle: "SETTINGS_SCHEDULEALLEVENTS_TOOLTIP") + + // Filter schedule + SettingsOption(setting: $settings.filterSchedule, title: "SETTINGS_FILTERSCHEDULE", subtitle: "SETTINGS_FILTERSCHEDULE_TOOLTIP") + + // Colorize grades + SettingsOption(setting: $settings.colorizeGrades, title: "SETTINGS_COLORIZEGRADES", subtitle: "SETTINGS_COLORIZEGRADES_TOOLTIP") + + // Haptic feedback + if (DeviceInfo.supportsHapticsOrVibration) { + SettingsOption(setting: $settings.hapticFeedback, title: "SETTINGS_HAPTICFEEDBACK", subtitle: "SETTINGS_HAPTICFEEDBACK_TOOLTIP") + } + + // Color scheme + if (settings.colorizeGrades) { + NavigationLink(destination: ColorSchemeSettingsView()) { + Text("Color Scheme") + .font(.body) + .bold() + } + } + + // App icon + if (Bundle.main.appIcons.count > 1) { + NavigationLink(destination: AppIconView()) { + Text("App Icon") + .font(.body) + .bold() + } + } + } + .padding(.vertical, 10) + } + + private var otherSection: some View { + Section(header: Text("Other").sectionTitle(), footer: appCredits) { + // Legal + NavigationLink(destination: LicenseView()) { + Text("Libraries") + .font(.body) + .bold() + } + + #if DEBUG + NavigationLink(destination: DebugView()) { + Text("🤫") + .font(.body) + .bold() + } + #endif + + if (settings.updatesAvailable) { + HStack { + Spacer() + Button(action: { + guard let url = URL(string: "https://github.com/rrroyal/vulcan/releases/latest") else { return } + generateHaptic(.light) + UIApplication.shared.open(url) + }) { + Text("New update available!") + .bold() + } + Spacer() + } + } + + // Reset button + Button(action: { + generateHaptic(.warning) + showingResetSheet = true + }) { + HStack { + Spacer() + Text("Reset user settings") + .foregroundColor(.red) + Spacer() + } + } + .actionSheet(isPresented: $showingResetSheet) { + ActionSheet(title: Text("SETTINGS_RESET"), message: Text("SETTINGS_RESET_TOOLTIP"), buttons: [ + .destructive(Text("Reset")) { + generateHaptic(.medium) + settings.resetSettings() + showingResetAlert = true + }, + .cancel(Text("Nevermind")) + ]) + } + .alert(isPresented: $showingResetAlert) { () -> Alert in + Alert(title: Text("Done!"), message: Text("SETTINGS_RESETTED"), primaryButton: .destructive(Text("Yes"), action: { exit(0) }), secondaryButton: .default(Text("No"))) + } + } + .padding(.vertical, 10) + } + + /// App credits, displayed as the footer of the last settings section. + private var appCredits: some View { + VStack { + Group { + Text("Made with ❤️ (and ☕️) by @rrroyal") + .bold() + Text("Version \(Bundle.main.buildVersion) (Build \(Bundle.main.buildNumber))") + .bold() + #if DEBUG + Text("🚧 DEBUG 🚧") + .bold() + #endif + } + .font(.callout) + .opacity(0.2) + .multilineTextAlignment(.center) + .foregroundColor(.primary) + } + .fullWidth() + .padding() + .edgesIgnoringSafeArea(.bottom) + .onTapGesture { + guard let url = URL(string: "https://vulcan.shameful.xyz") else { return } + generateHaptic(.light) + UIApplication.shared.open(url) + } + } + + var body: some View { + Form { + generalSection + uonetSection + notificationsSection + interfaceSection + otherSection + } + .listStyle(InsetGroupedListStyle()) + .navigationTitle(Text("Settings")) + .sheet(isPresented: $showingSetupView) { + SetupView(isPresented: $showingSetupView, isParentPresented: $showingSetupView, hasParent: false) + } + } +} + +/* struct SettingsView_Previews: PreviewProvider { +static var previews: some View { +SettingsView() +} +} */ diff --git a/iOS/Views/UsersView.swift b/iOS/Views/UsersView.swift new file mode 100644 index 0000000..12d52c0 --- /dev/null +++ b/iOS/Views/UsersView.swift @@ -0,0 +1,68 @@ +// +// UsersView.swift +// iOS +// +// Created by royal on 27/06/2020. +// + +import SwiftUI +import Vulcan + +struct UsersView: View { + @EnvironmentObject var vulcan: Vulcan + + private func fetch() { + vulcan.getUsers() { error in + if error != nil { + generateHaptic(.error) + } + } + } + + var body: some View { + List(vulcan.users) { (user) in + Button(action: { + generateHaptic(.light) + vulcan.setUser(user, force: true) + }) { + HStack { + Image(systemName: "person.fill") + .padding(.trailing, 5) + + Text("\(user.username) (\(user.unitCode))") + .foregroundColor(.primary) + + Spacer() + + if user == vulcan.currentUser { + Image(systemName: "checkmark") + .foregroundColor(.accentColor) + } + } + } + .padding(.vertical, 10) + } + .listStyle(InsetGroupedListStyle()) + .navigationTitle(Text("Users")) + /* .navigationBarItems(trailing: RefreshButton(loading: vulcan.dataState.users.loading, iconName: "arrow.clockwise", edge: .trailing) { + generateHaptic(.light) + refresh() + }) */ + .toolbar { + // Refresh button + ToolbarItem(placement: .navigationBarTrailing) { + RefreshButton(loading: vulcan.dataState.users.loading, iconName: "arrow.clockwise", edge: .trailing) { + generateHaptic(.light) + fetch() + } + } + } + .onAppear(perform: fetch) + } +} + +struct UsersView_Previews: PreviewProvider { + static var previews: some View { + UsersView() + } +} diff --git a/iOS/vulcan.entitlements b/iOS/vulcan.entitlements new file mode 100644 index 0000000..246c2be --- /dev/null +++ b/iOS/vulcan.entitlements @@ -0,0 +1,22 @@ + + + + + aps-environment + development + com.apple.developer.default-data-protection + NSFileProtectionComplete + com.apple.developer.siri + + com.apple.security.app-sandbox + + com.apple.security.application-groups + + group.dev.niepostek.vulcanGroup + + com.apple.security.network.client + + com.apple.security.personal-information.calendars + + + diff --git a/macOS/Info.plist b/macOS/Info.plist new file mode 100644 index 0000000..a648045 --- /dev/null +++ b/macOS/Info.plist @@ -0,0 +1,56 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + $(PRODUCT_BUNDLE_PACKAGE_TYPE) + CFBundleShortVersionString + $(MARKETING_VERSION) + CFBundleURLTypes + + + CFBundleTypeRole + Editor + CFBundleURLName + dev.niepostek.vulcan + CFBundleURLSchemes + + vulcan + + + + CFBundleVersion + $(CURRENT_PROJECT_VERSION) + ITSAppUsesNonExemptEncryption + + LSApplicationCategoryType + public.app-category.education + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSAppTransportSecurity + + NSExceptionDomains + + komponenty.vulcan.net.pl + + NSExceptionAllowsInsecureHTTPLoads + + NSIncludesSubdomains + + + + + + diff --git a/macOS/Views/MacSettingsView.swift b/macOS/Views/MacSettingsView.swift new file mode 100644 index 0000000..1bae16a --- /dev/null +++ b/macOS/Views/MacSettingsView.swift @@ -0,0 +1,20 @@ +// +// MacSettingsView.swift +// macOS +// +// Created by royal on 24/06/2020. +// + +import SwiftUI + +struct MacSettingsView: View { + var body: some View { + Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) + } +} + +struct MacSettingsView_Previews: PreviewProvider { + static var previews: some View { + MacSettingsView() + } +} diff --git a/macOS/macOS.entitlements b/macOS/macOS.entitlements new file mode 100644 index 0000000..d99d3ba --- /dev/null +++ b/macOS/macOS.entitlements @@ -0,0 +1,20 @@ + + + + + com.apple.developer.aps-environment + development + com.apple.security.app-sandbox + + com.apple.security.application-groups + + group.dev.niepostek.vulcanGroup + + com.apple.security.files.user-selected.read-only + + com.apple.security.network.client + + com.apple.security.personal-information.calendars + + + diff --git a/vulcan.xcodeproj/project.pbxproj b/vulcan.xcodeproj/project.pbxproj new file mode 100644 index 0000000..aef7c88 --- /dev/null +++ b/vulcan.xcodeproj/project.pbxproj @@ -0,0 +1,1634 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 53; + objects = { + +/* Begin PBXBuildFile section */ + 000702B424A7E5750061733F /* UsersView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 000702B324A7E5750061733F /* UsersView.swift */; }; + 0012BAA124A4C16B00371F23 /* RefreshButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0012BAA024A4C16B00371F23 /* RefreshButton.swift */; }; + 0012BAA224A4C16B00371F23 /* RefreshButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0012BAA024A4C16B00371F23 /* RefreshButton.swift */; }; + 0012BAA824A4EF4000371F23 /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0012BAA724A4EF4000371F23 /* AppState.swift */; }; + 0012BAA924A4EF4000371F23 /* AppState.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0012BAA724A4EF4000371F23 /* AppState.swift */; }; + 0026DB7624A7942200E232E5 /* MessageCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB7524A7942200E232E5 /* MessageCell.swift */; }; + 0026DB7724A7942200E232E5 /* MessageCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB7524A7942200E232E5 /* MessageCell.swift */; }; + 0026DB7924A7AC0C00E232E5 /* ComposeMessageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB7824A7AC0C00E232E5 /* ComposeMessageView.swift */; }; + 0026DB7A24A7AC0C00E232E5 /* ComposeMessageView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB7824A7AC0C00E232E5 /* ComposeMessageView.swift */; }; + 0026DB7F24A7B3BC00E232E5 /* MessageDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB7E24A7B3BC00E232E5 /* MessageDetailView.swift */; }; + 0026DB8024A7B3BC00E232E5 /* MessageDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB7E24A7B3BC00E232E5 /* MessageDetailView.swift */; }; + 0026DB8524A7C17D00E232E5 /* FinalGradeCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB8424A7C17D00E232E5 /* FinalGradeCell.swift */; }; + 0026DB8624A7C17D00E232E5 /* FinalGradeCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB8424A7C17D00E232E5 /* FinalGradeCell.swift */; }; + 0026DB8824A7C1CE00E232E5 /* NoteCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB8724A7C1CE00E232E5 /* NoteCell.swift */; }; + 0026DB8924A7C1CE00E232E5 /* NoteCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB8724A7C1CE00E232E5 /* NoteCell.swift */; }; + 0026DB8B24A7C6AD00E232E5 /* CloseButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB8A24A7C6AD00E232E5 /* CloseButton.swift */; }; + 0026DB8C24A7C6AD00E232E5 /* CloseButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0026DB8A24A7C6AD00E232E5 /* CloseButton.swift */; }; + 003FC5F724A4B54400001F47 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 003FC5F624A4B54400001F47 /* AppDelegate.swift */; }; + 003FC5F824A4B54400001F47 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 003FC5F624A4B54400001F47 /* AppDelegate.swift */; }; + 006AF91224A5F90F00D06D21 /* ScheduleEventCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 006AF91124A5F90F00D06D21 /* ScheduleEventCell.swift */; }; + 006AF91324A5F90F00D06D21 /* ScheduleEventCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 006AF91124A5F90F00D06D21 /* ScheduleEventCell.swift */; }; + 006AF91B24A6008500D06D21 /* TaskCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 006AF91A24A6008500D06D21 /* TaskCell.swift */; }; + 006AF91C24A6008500D06D21 /* TaskCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 006AF91A24A6008500D06D21 /* TaskCell.swift */; }; + 006AF91E24A600B500D06D21 /* Tab.swift in Sources */ = {isa = PBXBuildFile; fileRef = 006AF91D24A600B500D06D21 /* Tab.swift */; }; + 006AF91F24A600B500D06D21 /* Tab.swift in Sources */ = {isa = PBXBuildFile; fileRef = 006AF91D24A600B500D06D21 /* Tab.swift */; }; + 00708A6B24B743B1009FB4DD /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00708A6A24B743B1009FB4DD /* Notifications.swift */; }; + 00708A6C24B743B1009FB4DD /* Notifications.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00708A6A24B743B1009FB4DD /* Notifications.swift */; }; + 0088EB6B24A37BB7006F044E /* vulcanApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EB5824A37BB4006F044E /* vulcanApp.swift */; }; + 0088EB6C24A37BB7006F044E /* vulcanApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EB5824A37BB4006F044E /* vulcanApp.swift */; }; + 0088EB6D24A37BB7006F044E /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EB5924A37BB4006F044E /* ContentView.swift */; }; + 0088EB6E24A37BB7006F044E /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EB5924A37BB4006F044E /* ContentView.swift */; }; + 0088EB6F24A37BB7006F044E /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 0088EB5A24A37BB6006F044E /* Assets.xcassets */; }; + 0088EB7024A37BB7006F044E /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 0088EB5A24A37BB6006F044E /* Assets.xcassets */; }; + 0088EBA924A37C50006F044E /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBA824A37C50006F044E /* String.swift */; }; + 0088EBAA24A37C50006F044E /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBA824A37C50006F044E /* String.swift */; }; + 0088EBAF24A37C5C006F044E /* LinkPreview.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBAE24A37C5C006F044E /* LinkPreview.swift */; }; + 0088EBB024A37C5C006F044E /* LinkPreview.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBAE24A37C5C006F044E /* LinkPreview.swift */; }; + 0088EBB224A37CD2006F044E /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBB124A37CD2006F044E /* HomeView.swift */; }; + 0088EBB324A37CD2006F044E /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBB124A37CD2006F044E /* HomeView.swift */; }; + 0088EBB524A37D86006F044E /* GradesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBB424A37D86006F044E /* GradesView.swift */; }; + 0088EBB624A37D86006F044E /* GradesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBB424A37D86006F044E /* GradesView.swift */; }; + 0088EBB824A37D92006F044E /* ScheduleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBB724A37D92006F044E /* ScheduleView.swift */; }; + 0088EBB924A37D92006F044E /* ScheduleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBB724A37D92006F044E /* ScheduleView.swift */; }; + 0088EBBB24A37D9B006F044E /* TasksView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBBA24A37D9B006F044E /* TasksView.swift */; }; + 0088EBBC24A37D9B006F044E /* TasksView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBBA24A37D9B006F044E /* TasksView.swift */; }; + 0088EBBE24A37DA2006F044E /* MessagesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBBD24A37DA2006F044E /* MessagesView.swift */; }; + 0088EBBF24A37DA2006F044E /* MessagesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBBD24A37DA2006F044E /* MessagesView.swift */; }; + 00FAC9C824A3D85400ACAC83 /* SettingsModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FAC9C224A3D85400ACAC83 /* SettingsModel.swift */; }; + 00FAC9C924A3D85400ACAC83 /* SettingsModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FAC9C224A3D85400ACAC83 /* SettingsModel.swift */; }; + 00FAC9D524A3D8E800ACAC83 /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = 00FAC9D424A3D8E800ACAC83 /* KeychainAccess */; }; + 00FAC9D924A3D8F300ACAC83 /* KeychainAccess in Frameworks */ = {isa = PBXBuildFile; productRef = 00FAC9D824A3D8F300ACAC83 /* KeychainAccess */; }; + 00FAC9E124A3D93000ACAC83 /* Date.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FAC9DB24A3D93000ACAC83 /* Date.swift */; }; + 00FAC9E224A3D93000ACAC83 /* Date.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FAC9DB24A3D93000ACAC83 /* Date.swift */; }; + 00FAC9F924A3D9A600ACAC83 /* View.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FAC9EB24A3D9A600ACAC83 /* View.swift */; }; + 00FAC9FA24A3D9A600ACAC83 /* View.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FAC9EB24A3D9A600ACAC83 /* View.swift */; }; + 00FACA0124A3D9A600ACAC83 /* DeviceInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FAC9ED24A3D9A600ACAC83 /* DeviceInfo.swift */; }; + 00FACA0D24A3D9A600ACAC83 /* Bundle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FAC9F024A3D9A600ACAC83 /* Bundle.swift */; }; + 00FACA0E24A3D9A600ACAC83 /* Bundle.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FAC9F024A3D9A600ACAC83 /* Bundle.swift */; }; + 00FACA2024A3DC0600ACAC83 /* DeviceInfo.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FAC9ED24A3D9A600ACAC83 /* DeviceInfo.swift */; }; + 00FACA2724A3E2E600ACAC83 /* MacSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA2624A3E2E600ACAC83 /* MacSettingsView.swift */; }; + 00FACA3124A3E34000ACAC83 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 00FACA2B24A3E34000ACAC83 /* Localizable.strings */; }; + 00FACA3224A3E34000ACAC83 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 00FACA2B24A3E34000ACAC83 /* Localizable.strings */; }; + 00FACA3824A3EAB300ACAC83 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA3724A3EAB300ACAC83 /* SettingsView.swift */; }; + 00FACA3C24A3EDC900ACAC83 /* OnboardingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA3A24A3EDC900ACAC83 /* OnboardingView.swift */; }; + 00FACA3D24A3EDC900ACAC83 /* OnboardingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA3A24A3EDC900ACAC83 /* OnboardingView.swift */; }; + 00FACA3E24A3EDC900ACAC83 /* SetupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA3B24A3EDC900ACAC83 /* SetupView.swift */; }; + 00FACA3F24A3EDC900ACAC83 /* SetupView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA3B24A3EDC900ACAC83 /* SetupView.swift */; }; + 00FACA4124A3EE6F00ACAC83 /* Global.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA4024A3EE6F00ACAC83 /* Global.swift */; }; + 00FACA4224A3EE6F00ACAC83 /* Global.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA4024A3EE6F00ACAC83 /* Global.swift */; }; + 00FACA5224A4073A00ACAC83 /* DebugView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA5124A4073A00ACAC83 /* DebugView.swift */; }; + 00FACA5B24A40C2800ACAC83 /* Colors.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 00FACA5A24A40C2700ACAC83 /* Colors.xcassets */; }; + 00FACA5C24A40C2800ACAC83 /* Colors.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 00FACA5A24A40C2700ACAC83 /* Colors.xcassets */; }; + 00FACA6224A40EF100ACAC83 /* GradesDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA6124A40EF100ACAC83 /* GradesDetailView.swift */; }; + 00FACA6324A40EF100ACAC83 /* GradesDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA6124A40EF100ACAC83 /* GradesDetailView.swift */; }; + 00FACA6624A40F9900ACAC83 /* GradeCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA6524A40F9900ACAC83 /* GradeCell.swift */; }; + 00FACA6724A40F9900ACAC83 /* GradeCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA6524A40F9900ACAC83 /* GradeCell.swift */; }; + 00FACA6A24A41D3900ACAC83 /* AppSidebarNavigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA6924A41D3900ACAC83 /* AppSidebarNavigation.swift */; }; + 00FACA6B24A41D3900ACAC83 /* AppSidebarNavigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA6924A41D3900ACAC83 /* AppSidebarNavigation.swift */; }; + 00FACA6D24A41D5B00ACAC83 /* AppTabNavigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA6C24A41D5B00ACAC83 /* AppTabNavigation.swift */; }; + 00FACA6E24A41D5B00ACAC83 /* AppTabNavigation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FACA6C24A41D5B00ACAC83 /* AppTabNavigation.swift */; }; + E704C12D24F9A1F90036073F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = E704C12C24F9A1F90036073F /* LaunchScreen.storyboard */; }; + E704C12E24F9A1F90036073F /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = E704C12C24F9A1F90036073F /* LaunchScreen.storyboard */; }; + E71374932501825D000EA663 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = E71374952501825D000EA663 /* Localizable.strings */; }; + E71A45D225263492003176B3 /* AppNotifications in Frameworks */ = {isa = PBXBuildFile; productRef = E71A45D125263492003176B3 /* AppNotifications */; }; + E722C3F525020EDB0087C007 /* HomeCardCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = E722C3F425020EDB0087C007 /* HomeCardCell.swift */; }; + E723FAC92518F02700DD8184 /* AppIconView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E723FAC82518F02700DD8184 /* AppIconView.swift */; }; + E723FAD02518F05500DD8184 /* ColorSchemeSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E723FACF2518F05500DD8184 /* ColorSchemeSettingsView.swift */; }; + E723FAD72518F06C00DD8184 /* LicenseView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E723FAD62518F06C00DD8184 /* LicenseView.swift */; }; + E7360BCF25028B26006A4E17 /* VulcanStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7360BCE25028B26006A4E17 /* VulcanStore.swift */; }; + E74F54A5250924EF003F8066 /* ScheduleEventCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = E74F54A4250924EF003F8066 /* ScheduleEventCell.swift */; }; + E7518A2B25012C9000135D55 /* NextUpEntryView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7518A2A25012C9000135D55 /* NextUpEntryView.swift */; }; + E7518A2E25012CC800135D55 /* NowProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7518A2D25012CC800135D55 /* NowProvider.swift */; }; + E7518A3225012D5500135D55 /* Vulcan in Frameworks */ = {isa = PBXBuildFile; productRef = E7518A3125012D5500135D55 /* Vulcan */; }; + E772E6D624B36FB900A7FFB4 /* View+.swift in Sources */ = {isa = PBXBuildFile; fileRef = E772E6D524B36FB900A7FFB4 /* View+.swift */; }; + E772E6D724B36FB900A7FFB4 /* View+.swift in Sources */ = {isa = PBXBuildFile; fileRef = E772E6D524B36FB900A7FFB4 /* View+.swift */; }; + E772FEF2253C9489003F80AF /* NextUpProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = E772FEF1253C9489003F80AF /* NextUpProvider.swift */; }; + E772FF17253C9786003F80AF /* NowEntryView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E772FF16253C9786003F80AF /* NowEntryView.swift */; }; + E7790C6A24B9275600BA4187 /* Vulcan in Frameworks */ = {isa = PBXBuildFile; productRef = E7790C6924B9275600BA4187 /* Vulcan */; }; + E7790C7024B9280B00BA4187 /* AppNotifications in Frameworks */ = {isa = PBXBuildFile; productRef = E7790C6F24B9280B00BA4187 /* AppNotifications */; }; + E783D39D2502917200514060 /* ScheduleView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E783D39C2502917200514060 /* ScheduleView.swift */; }; + E783D39F2502917A00514060 /* GradesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E783D39E2502917A00514060 /* GradesView.swift */; }; + E783D3A12502918200514060 /* FinalGradesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E783D3A02502918200514060 /* FinalGradesView.swift */; }; + E783D3A32502918A00514060 /* TasksView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E783D3A22502918A00514060 /* TasksView.swift */; }; + E783D3A52502919200514060 /* MessagesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E783D3A42502919200514060 /* MessagesView.swift */; }; + E783D3A7250291E300514060 /* DebugView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E783D3A6250291E300514060 /* DebugView.swift */; }; + E78FC1C525161DB700478AC1 /* GradesDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E78FC1C425161DB700478AC1 /* GradesDetailView.swift */; }; + E78FC1F9251626AE00478AC1 /* MessageDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E78FC1F8251626AE00478AC1 /* MessageDetailView.swift */; }; + E7A1524F254D88970073DB9C /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBA824A37C50006F044E /* String.swift */; }; + E7A15255254D88980073DB9C /* String.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0088EBA824A37C50006F044E /* String.swift */; }; + E7A419AC24FA5A7400FC55D6 /* Vulcan in Frameworks */ = {isa = PBXBuildFile; productRef = E7A419AB24FA5A7400FC55D6 /* Vulcan */; }; + E7A62490253C9C6B006DEDDE /* EventView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7A6248F253C9C6B006DEDDE /* EventView.swift */; }; + E7A62497253CA093006DEDDE /* NextEventView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7A62496253CA093006DEDDE /* NextEventView.swift */; }; + E7A624A5253CA0E4006DEDDE /* CurrentEventView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7A624A4253CA0E4006DEDDE /* CurrentEventView.swift */; }; + E7A624B2253CA121006DEDDE /* SmallEventCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7A624B1253CA121006DEDDE /* SmallEventCell.swift */; }; + E7A7D38D2503A7EF00B7D4CB /* Colors.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 00FACA5A24A40C2700ACAC83 /* Colors.xcassets */; }; + E7C144D9250123F500363BD3 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E7C144D8250123F500363BD3 /* Assets.xcassets */; }; + E7C144E0250123F600363BD3 /* WatchKit Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = E7C144DF250123F600363BD3 /* WatchKit Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + E7C144E5250123F600363BD3 /* vulcanApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7C144E4250123F600363BD3 /* vulcanApp.swift */; }; + E7C144E7250123F600363BD3 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7C144E6250123F600363BD3 /* ContentView.swift */; }; + E7C144E9250123F600363BD3 /* NotificationController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7C144E8250123F600363BD3 /* NotificationController.swift */; }; + E7C144EB250123F600363BD3 /* NotificationView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7C144EA250123F600363BD3 /* NotificationView.swift */; }; + E7C144ED250123F600363BD3 /* ComplicationController.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7C144EC250123F600363BD3 /* ComplicationController.swift */; }; + E7C144EF250123F600363BD3 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E7C144EE250123F600363BD3 /* Assets.xcassets */; }; + E7C144F2250123F600363BD3 /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E7C144F1250123F600363BD3 /* Preview Assets.xcassets */; }; + E7C144F7250123F600363BD3 /* WatchKit.app in Embed Watch Content */ = {isa = PBXBuildFile; fileRef = E7C144D6250123F500363BD3 /* WatchKit.app */; platformFilter = ios; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + E7C14503250124E500363BD3 /* Vulcan in Frameworks */ = {isa = PBXBuildFile; productRef = E7C14502250124E500363BD3 /* Vulcan */; }; + E7C1452025012A2100363BD3 /* WidgetKit.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0088EBCA24A38D9E006F044E /* WidgetKit.framework */; }; + E7C1452125012A2100363BD3 /* SwiftUI.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0088EBCC24A38D9E006F044E /* SwiftUI.framework */; }; + E7C1452425012A2100363BD3 /* VulcanWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7C1452325012A2100363BD3 /* VulcanWidget.swift */; }; + E7C1452725012A2200363BD3 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = E7C1452625012A2200363BD3 /* Assets.xcassets */; }; + E7C1452D25012A2200363BD3 /* Widget.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = E7C1451F25012A2100363BD3 /* Widget.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; }; + E7EB03E725080773003043D8 /* ExtensionDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7EB03E625080773003043D8 /* ExtensionDelegate.swift */; }; + E7EB03EC25080F3A003043D8 /* WatchSessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7EB03EB25080F3A003043D8 /* WatchSessionManager.swift */; }; + E7EB03ED25081177003043D8 /* WatchSessionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7EB03EB25080F3A003043D8 /* WatchSessionManager.swift */; }; + E7EB03EE25081685003043D8 /* View.swift in Sources */ = {isa = PBXBuildFile; fileRef = 00FAC9EB24A3D9A600ACAC83 /* View.swift */; }; + E7EB03F2250818DC003043D8 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = E7EB03F4250818DC003043D8 /* Localizable.strings */; }; + E7F1B40925161BB50044F1BC /* InfoPlist.strings in Resources */ = {isa = PBXBuildFile; fileRef = E7F1B40B25161BB50044F1BC /* InfoPlist.strings */; }; + E7F47EA6251768D50075E5E4 /* TaskCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = E7F47EA5251768D50075E5E4 /* TaskCell.swift */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + E7C144E1250123F600363BD3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 0088EB5324A37BB4006F044E /* Project object */; + proxyType = 1; + remoteGlobalIDString = E7C144DE250123F600363BD3; + remoteInfo = "watchkit Extension"; + }; + E7C144F5250123F600363BD3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 0088EB5324A37BB4006F044E /* Project object */; + proxyType = 1; + remoteGlobalIDString = E7C144D5250123F500363BD3; + remoteInfo = watchkit; + }; + E7C1452B25012A2200363BD3 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 0088EB5324A37BB4006F044E /* Project object */; + proxyType = 1; + remoteGlobalIDString = E7C1451E25012A2100363BD3; + remoteInfo = widgetExtension; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + E7C144F8250123F600363BD3 /* Embed Watch Content */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = "$(CONTENTS_FOLDER_PATH)/Watch"; + dstSubfolderSpec = 16; + files = ( + E7C144F7250123F600363BD3 /* WatchKit.app in Embed Watch Content */, + ); + name = "Embed Watch Content"; + runOnlyForDeploymentPostprocessing = 0; + }; + E7C144FB250123F600363BD3 /* Embed App Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + E7C144E0250123F600363BD3 /* WatchKit Extension.appex in Embed App Extensions */, + ); + name = "Embed App Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; + E7C145182501270600363BD3 /* Embed App Extensions */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 13; + files = ( + E7C1452D25012A2200363BD3 /* Widget.appex in Embed App Extensions */, + ); + name = "Embed App Extensions"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 000702B324A7E5750061733F /* UsersView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UsersView.swift; sourceTree = ""; }; + 0012BAA024A4C16B00371F23 /* RefreshButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RefreshButton.swift; sourceTree = ""; }; + 0012BAA724A4EF4000371F23 /* AppState.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppState.swift; sourceTree = ""; }; + 0026DB7524A7942200E232E5 /* MessageCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageCell.swift; sourceTree = ""; }; + 0026DB7824A7AC0C00E232E5 /* ComposeMessageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComposeMessageView.swift; sourceTree = ""; }; + 0026DB7E24A7B3BC00E232E5 /* MessageDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageDetailView.swift; sourceTree = ""; }; + 0026DB8424A7C17D00E232E5 /* FinalGradeCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = FinalGradeCell.swift; sourceTree = ""; }; + 0026DB8724A7C1CE00E232E5 /* NoteCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = NoteCell.swift; sourceTree = ""; }; + 0026DB8A24A7C6AD00E232E5 /* CloseButton.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloseButton.swift; sourceTree = ""; }; + 003FC5F624A4B54400001F47 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 006AF91124A5F90F00D06D21 /* ScheduleEventCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ScheduleEventCell.swift; sourceTree = ""; }; + 006AF91A24A6008500D06D21 /* TaskCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TaskCell.swift; sourceTree = ""; }; + 006AF91D24A600B500D06D21 /* Tab.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Tab.swift; sourceTree = ""; }; + 00708A6A24B743B1009FB4DD /* Notifications.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Notifications.swift; sourceTree = ""; }; + 0088EB5824A37BB4006F044E /* vulcanApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = vulcanApp.swift; sourceTree = ""; }; + 0088EB5924A37BB4006F044E /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; + 0088EB5A24A37BB6006F044E /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 0088EB5F24A37BB7006F044E /* vulcan.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = vulcan.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 0088EB6224A37BB7006F044E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 0088EB6724A37BB7006F044E /* vulcan.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = vulcan.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 0088EB6924A37BB7006F044E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + 0088EB6A24A37BB7006F044E /* macOS.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = macOS.entitlements; sourceTree = ""; }; + 0088EB7924A37BE2006F044E /* vulcan.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = vulcan.entitlements; sourceTree = ""; }; + 0088EBA824A37C50006F044E /* String.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = String.swift; sourceTree = ""; }; + 0088EBAE24A37C5C006F044E /* LinkPreview.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LinkPreview.swift; sourceTree = ""; }; + 0088EBB124A37CD2006F044E /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = ""; }; + 0088EBB424A37D86006F044E /* GradesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GradesView.swift; sourceTree = ""; }; + 0088EBB724A37D92006F044E /* ScheduleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScheduleView.swift; sourceTree = ""; }; + 0088EBBA24A37D9B006F044E /* TasksView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TasksView.swift; sourceTree = ""; }; + 0088EBBD24A37DA2006F044E /* MessagesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessagesView.swift; sourceTree = ""; }; + 0088EBCA24A38D9E006F044E /* WidgetKit.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = WidgetKit.framework; path = System/Library/Frameworks/WidgetKit.framework; sourceTree = SDKROOT; }; + 0088EBCC24A38D9E006F044E /* SwiftUI.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = SwiftUI.framework; path = System/Library/Frameworks/SwiftUI.framework; sourceTree = SDKROOT; }; + 00FAC9C224A3D85400ACAC83 /* SettingsModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SettingsModel.swift; sourceTree = ""; }; + 00FAC9DB24A3D93000ACAC83 /* Date.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Date.swift; sourceTree = ""; }; + 00FAC9EB24A3D9A600ACAC83 /* View.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = View.swift; sourceTree = ""; }; + 00FAC9ED24A3D9A600ACAC83 /* DeviceInfo.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DeviceInfo.swift; sourceTree = ""; }; + 00FAC9F024A3D9A600ACAC83 /* Bundle.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Bundle.swift; sourceTree = ""; }; + 00FACA2624A3E2E600ACAC83 /* MacSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MacSettingsView.swift; sourceTree = ""; }; + 00FACA2C24A3E34000ACAC83 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Localizable.strings; sourceTree = ""; }; + 00FACA2F24A3E34000ACAC83 /* pl */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = pl; path = pl.lproj/Localizable.strings; sourceTree = ""; }; + 00FACA3724A3EAB300ACAC83 /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = ""; }; + 00FACA3A24A3EDC900ACAC83 /* OnboardingView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = OnboardingView.swift; sourceTree = ""; }; + 00FACA3B24A3EDC900ACAC83 /* SetupView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = SetupView.swift; sourceTree = ""; }; + 00FACA4024A3EE6F00ACAC83 /* Global.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Global.swift; sourceTree = ""; }; + 00FACA5124A4073A00ACAC83 /* DebugView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = DebugView.swift; sourceTree = ""; }; + 00FACA5A24A40C2700ACAC83 /* Colors.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Colors.xcassets; sourceTree = ""; }; + 00FACA6124A40EF100ACAC83 /* GradesDetailView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GradesDetailView.swift; sourceTree = ""; }; + 00FACA6524A40F9900ACAC83 /* GradeCell.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GradeCell.swift; sourceTree = ""; }; + 00FACA6924A41D3900ACAC83 /* AppSidebarNavigation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppSidebarNavigation.swift; sourceTree = ""; }; + 00FACA6C24A41D5B00ACAC83 /* AppTabNavigation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppTabNavigation.swift; sourceTree = ""; }; + E704C12C24F9A1F90036073F /* LaunchScreen.storyboard */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; path = LaunchScreen.storyboard; sourceTree = ""; }; + E71374942501825D000EA663 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Localizable.strings; sourceTree = ""; }; + E7187BDE253CBBE400C55A95 /* pl */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = pl; path = pl.lproj/Localizable.strings; sourceTree = ""; }; + E722C3F425020EDB0087C007 /* HomeCardCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeCardCell.swift; sourceTree = ""; }; + E723FAC82518F02700DD8184 /* AppIconView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppIconView.swift; sourceTree = ""; }; + E723FACF2518F05500DD8184 /* ColorSchemeSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorSchemeSettingsView.swift; sourceTree = ""; }; + E723FAD62518F06C00DD8184 /* LicenseView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LicenseView.swift; sourceTree = ""; }; + E7360BCE25028B26006A4E17 /* VulcanStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VulcanStore.swift; sourceTree = ""; }; + E74A6DAB24B907A100DBB988 /* AppNotifications */ = {isa = PBXFileReference; lastKnownFileType = folder; name = AppNotifications; path = Modules/AppNotifications; sourceTree = ""; }; + E74A6DAC24B907E100DBB988 /* Vulcan */ = {isa = PBXFileReference; lastKnownFileType = folder; name = Vulcan; path = Modules/Vulcan; sourceTree = ""; }; + E74F54A4250924EF003F8066 /* ScheduleEventCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScheduleEventCell.swift; sourceTree = ""; }; + E7518A2A25012C9000135D55 /* NextUpEntryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NextUpEntryView.swift; sourceTree = ""; }; + E7518A2D25012CC800135D55 /* NowProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NowProvider.swift; sourceTree = ""; }; + E772E6D524B36FB900A7FFB4 /* View+.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "View+.swift"; sourceTree = ""; }; + E772FEF1253C9489003F80AF /* NextUpProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NextUpProvider.swift; sourceTree = ""; }; + E772FF16253C9786003F80AF /* NowEntryView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NowEntryView.swift; sourceTree = ""; }; + E783D39C2502917200514060 /* ScheduleView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScheduleView.swift; sourceTree = ""; }; + E783D39E2502917A00514060 /* GradesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GradesView.swift; sourceTree = ""; }; + E783D3A02502918200514060 /* FinalGradesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FinalGradesView.swift; sourceTree = ""; }; + E783D3A22502918A00514060 /* TasksView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TasksView.swift; sourceTree = ""; }; + E783D3A42502919200514060 /* MessagesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessagesView.swift; sourceTree = ""; }; + E783D3A6250291E300514060 /* DebugView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DebugView.swift; sourceTree = ""; }; + E78FC1C425161DB700478AC1 /* GradesDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GradesDetailView.swift; sourceTree = ""; }; + E78FC1F8251626AE00478AC1 /* MessageDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MessageDetailView.swift; sourceTree = ""; }; + E7A6248F253C9C6B006DEDDE /* EventView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EventView.swift; sourceTree = ""; }; + E7A62496253CA093006DEDDE /* NextEventView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NextEventView.swift; sourceTree = ""; }; + E7A624A4253CA0E4006DEDDE /* CurrentEventView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CurrentEventView.swift; sourceTree = ""; }; + E7A624B1253CA121006DEDDE /* SmallEventCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SmallEventCell.swift; sourceTree = ""; }; + E7C144D6250123F500363BD3 /* WatchKit.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = WatchKit.app; sourceTree = BUILT_PRODUCTS_DIR; }; + E7C144D8250123F500363BD3 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + E7C144DA250123F500363BD3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E7C144DF250123F600363BD3 /* WatchKit Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = "WatchKit Extension.appex"; sourceTree = BUILT_PRODUCTS_DIR; }; + E7C144E4250123F600363BD3 /* vulcanApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = vulcanApp.swift; sourceTree = ""; }; + E7C144E6250123F600363BD3 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; + E7C144E8250123F600363BD3 /* NotificationController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationController.swift; sourceTree = ""; }; + E7C144EA250123F600363BD3 /* NotificationView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NotificationView.swift; sourceTree = ""; }; + E7C144EC250123F600363BD3 /* ComplicationController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ComplicationController.swift; sourceTree = ""; }; + E7C144EE250123F600363BD3 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + E7C144F1250123F600363BD3 /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; }; + E7C144F3250123F600363BD3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E7C144F4250123F600363BD3 /* PushNotificationPayload.apns */ = {isa = PBXFileReference; lastKnownFileType = text; path = PushNotificationPayload.apns; sourceTree = ""; }; + E7C145002501242D00363BD3 /* WatchKit Extension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "WatchKit Extension.entitlements"; sourceTree = ""; }; + E7C1451F25012A2100363BD3 /* Widget.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = Widget.appex; sourceTree = BUILT_PRODUCTS_DIR; }; + E7C1452325012A2100363BD3 /* VulcanWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VulcanWidget.swift; sourceTree = ""; }; + E7C1452625012A2200363BD3 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + E7C1452825012A2200363BD3 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + E7C1452E25012A2200363BD3 /* Widget.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Widget.entitlements; sourceTree = ""; }; + E7EB03E625080773003043D8 /* ExtensionDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExtensionDelegate.swift; sourceTree = ""; }; + E7EB03EB25080F3A003043D8 /* WatchSessionManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WatchSessionManager.swift; sourceTree = ""; }; + E7EB03F3250818DC003043D8 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Localizable.strings; sourceTree = ""; }; + E7EB03F5250818DD003043D8 /* pl */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = pl; path = pl.lproj/Localizable.strings; sourceTree = ""; }; + E7F1B40A25161BB50044F1BC /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/InfoPlist.strings; sourceTree = ""; }; + E7F1B41125161BB60044F1BC /* pl */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = pl; path = pl.lproj/InfoPlist.strings; sourceTree = ""; }; + E7F47EA5251768D50075E5E4 /* TaskCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TaskCell.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 0088EB5C24A37BB7006F044E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 00FAC9D524A3D8E800ACAC83 /* KeychainAccess in Frameworks */, + E7790C6A24B9275600BA4187 /* Vulcan in Frameworks */, + E7790C7024B9280B00BA4187 /* AppNotifications in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0088EB6424A37BB7006F044E /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E71A45D225263492003176B3 /* AppNotifications in Frameworks */, + 00FAC9D924A3D8F300ACAC83 /* KeychainAccess in Frameworks */, + E7A419AC24FA5A7400FC55D6 /* Vulcan in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E7C144DC250123F600363BD3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E7C14503250124E500363BD3 /* Vulcan in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E7C1451C25012A2100363BD3 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E7C1452125012A2100363BD3 /* SwiftUI.framework in Frameworks */, + E7518A3225012D5500135D55 /* Vulcan in Frameworks */, + E7C1452025012A2100363BD3 /* WidgetKit.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 0012BAAD24A4FBEB00371F23 /* Other */ = { + isa = PBXGroup; + children = ( + 00FACA4024A3EE6F00ACAC83 /* Global.swift */, + 006AF91D24A600B500D06D21 /* Tab.swift */, + ); + path = Other; + sourceTree = ""; + }; + 0026DB8D24A7C88300E232E5 /* Cells */ = { + isa = PBXGroup; + children = ( + 00FACA6524A40F9900ACAC83 /* GradeCell.swift */, + 0026DB8424A7C17D00E232E5 /* FinalGradeCell.swift */, + 006AF91124A5F90F00D06D21 /* ScheduleEventCell.swift */, + 0026DB7524A7942200E232E5 /* MessageCell.swift */, + 006AF91A24A6008500D06D21 /* TaskCell.swift */, + 0026DB8724A7C1CE00E232E5 /* NoteCell.swift */, + ); + path = Cells; + sourceTree = ""; + }; + 0088EB5224A37BB4006F044E = { + isa = PBXGroup; + children = ( + 0088EB5724A37BB4006F044E /* Shared */, + 0088EB6124A37BB7006F044E /* iOS */, + 0088EB6824A37BB7006F044E /* macOS */, + E7C144D7250123F500363BD3 /* WatchKit */, + E7C144E3250123F600363BD3 /* WatchKit Extension */, + E7C1452225012A2100363BD3 /* Widget */, + E74A6DAC24B907E100DBB988 /* Vulcan */, + E74A6DAB24B907A100DBB988 /* AppNotifications */, + 0088EBC924A38D9E006F044E /* Frameworks */, + 0088EB6024A37BB7006F044E /* Products */, + ); + sourceTree = ""; + }; + 0088EB5724A37BB4006F044E /* Shared */ = { + isa = PBXGroup; + children = ( + 0088EB5824A37BB4006F044E /* vulcanApp.swift */, + 0088EB5A24A37BB6006F044E /* Assets.xcassets */, + 00FACA5A24A40C2700ACAC83 /* Colors.xcassets */, + E704C12C24F9A1F90036073F /* LaunchScreen.storyboard */, + 00FAC9C024A3D85400ACAC83 /* Data */, + 0088EBAC24A37C5C006F044E /* Views */, + 0088EBA724A37C50006F044E /* Extensions+Modifiers */, + 00FACA2A24A3E34000ACAC83 /* Localization */, + 0012BAAD24A4FBEB00371F23 /* Other */, + ); + path = Shared; + sourceTree = ""; + }; + 0088EB6024A37BB7006F044E /* Products */ = { + isa = PBXGroup; + children = ( + 0088EB5F24A37BB7006F044E /* vulcan.app */, + 0088EB6724A37BB7006F044E /* vulcan.app */, + E7C144D6250123F500363BD3 /* WatchKit.app */, + E7C144DF250123F600363BD3 /* WatchKit Extension.appex */, + E7C1451F25012A2100363BD3 /* Widget.appex */, + ); + name = Products; + sourceTree = ""; + }; + 0088EB6124A37BB7006F044E /* iOS */ = { + isa = PBXGroup; + children = ( + 0088EB6224A37BB7006F044E /* Info.plist */, + 0088EB7924A37BE2006F044E /* vulcan.entitlements */, + 00FACA3924A3EABD00ACAC83 /* Views */, + E7F1B3F725161AFC0044F1BC /* Localization */, + ); + path = iOS; + sourceTree = ""; + }; + 0088EB6824A37BB7006F044E /* macOS */ = { + isa = PBXGroup; + children = ( + 0088EB6924A37BB7006F044E /* Info.plist */, + 0088EB6A24A37BB7006F044E /* macOS.entitlements */, + 00FACA2824A3E2E900ACAC83 /* Views */, + ); + path = macOS; + sourceTree = ""; + }; + 0088EBA724A37C50006F044E /* Extensions+Modifiers */ = { + isa = PBXGroup; + children = ( + 00FAC9EB24A3D9A600ACAC83 /* View.swift */, + E772E6D524B36FB900A7FFB4 /* View+.swift */, + 0088EBA824A37C50006F044E /* String.swift */, + 00FAC9DB24A3D93000ACAC83 /* Date.swift */, + 00FAC9F024A3D9A600ACAC83 /* Bundle.swift */, + 00FAC9ED24A3D9A600ACAC83 /* DeviceInfo.swift */, + ); + path = "Extensions+Modifiers"; + sourceTree = ""; + }; + 0088EBAC24A37C5C006F044E /* Views */ = { + isa = PBXGroup; + children = ( + 00FACA6824A41D1900ACAC83 /* Navigation */, + 00FACA6024A40ED600ACAC83 /* Details */, + 00FACA4324A3F11A00ACAC83 /* Components */, + 0088EBAD24A37C5C006F044E /* UIViewRepresentable */, + 0088EB5924A37BB4006F044E /* ContentView.swift */, + 0088EBB124A37CD2006F044E /* HomeView.swift */, + 0088EBB424A37D86006F044E /* GradesView.swift */, + 0088EBB724A37D92006F044E /* ScheduleView.swift */, + 0088EBBA24A37D9B006F044E /* TasksView.swift */, + 0088EBBD24A37DA2006F044E /* MessagesView.swift */, + 00FACA3A24A3EDC900ACAC83 /* OnboardingView.swift */, + 00FACA3B24A3EDC900ACAC83 /* SetupView.swift */, + ); + path = Views; + sourceTree = ""; + }; + 0088EBAD24A37C5C006F044E /* UIViewRepresentable */ = { + isa = PBXGroup; + children = ( + 0088EBAE24A37C5C006F044E /* LinkPreview.swift */, + ); + path = UIViewRepresentable; + sourceTree = ""; + }; + 0088EBC924A38D9E006F044E /* Frameworks */ = { + isa = PBXGroup; + children = ( + 0088EBCA24A38D9E006F044E /* WidgetKit.framework */, + 0088EBCC24A38D9E006F044E /* SwiftUI.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 00FAC9C024A3D85400ACAC83 /* Data */ = { + isa = PBXGroup; + children = ( + 003FC5F624A4B54400001F47 /* AppDelegate.swift */, + 0012BAA724A4EF4000371F23 /* AppState.swift */, + 00708A6A24B743B1009FB4DD /* Notifications.swift */, + 00FAC9C224A3D85400ACAC83 /* SettingsModel.swift */, + E7EB03EB25080F3A003043D8 /* WatchSessionManager.swift */, + ); + path = Data; + sourceTree = ""; + }; + 00FACA2824A3E2E900ACAC83 /* Views */ = { + isa = PBXGroup; + children = ( + 00FACA2624A3E2E600ACAC83 /* MacSettingsView.swift */, + ); + path = Views; + sourceTree = ""; + }; + 00FACA2A24A3E34000ACAC83 /* Localization */ = { + isa = PBXGroup; + children = ( + 00FACA2B24A3E34000ACAC83 /* Localizable.strings */, + ); + path = Localization; + sourceTree = ""; + }; + 00FACA3924A3EABD00ACAC83 /* Views */ = { + isa = PBXGroup; + children = ( + 00FACA3724A3EAB300ACAC83 /* SettingsView.swift */, + 000702B324A7E5750061733F /* UsersView.swift */, + 00FACA5124A4073A00ACAC83 /* DebugView.swift */, + E723FAC82518F02700DD8184 /* AppIconView.swift */, + E723FACF2518F05500DD8184 /* ColorSchemeSettingsView.swift */, + E723FAD62518F06C00DD8184 /* LicenseView.swift */, + ); + path = Views; + sourceTree = ""; + }; + 00FACA4324A3F11A00ACAC83 /* Components */ = { + isa = PBXGroup; + children = ( + 0026DB8A24A7C6AD00E232E5 /* CloseButton.swift */, + 0012BAA024A4C16B00371F23 /* RefreshButton.swift */, + 0026DB8D24A7C88300E232E5 /* Cells */, + ); + path = Components; + sourceTree = ""; + }; + 00FACA6024A40ED600ACAC83 /* Details */ = { + isa = PBXGroup; + children = ( + 00FACA6124A40EF100ACAC83 /* GradesDetailView.swift */, + 0026DB7824A7AC0C00E232E5 /* ComposeMessageView.swift */, + 0026DB7E24A7B3BC00E232E5 /* MessageDetailView.swift */, + ); + path = Details; + sourceTree = ""; + }; + 00FACA6824A41D1900ACAC83 /* Navigation */ = { + isa = PBXGroup; + children = ( + 00FACA6C24A41D5B00ACAC83 /* AppTabNavigation.swift */, + 00FACA6924A41D3900ACAC83 /* AppSidebarNavigation.swift */, + ); + path = Navigation; + sourceTree = ""; + }; + E71374902501821D000EA663 /* Localization */ = { + isa = PBXGroup; + children = ( + E71374952501825D000EA663 /* Localizable.strings */, + ); + path = Localization; + sourceTree = ""; + }; + E722C3F325020ECD0087C007 /* Components */ = { + isa = PBXGroup; + children = ( + E722C3F425020EDB0087C007 /* HomeCardCell.swift */, + E74F54A4250924EF003F8066 /* ScheduleEventCell.swift */, + E7F47EA5251768D50075E5E4 /* TaskCell.swift */, + ); + path = Components; + sourceTree = ""; + }; + E7360BCD25028B17006A4E17 /* Data */ = { + isa = PBXGroup; + children = ( + E7C144E8250123F600363BD3 /* NotificationController.swift */, + E7C144EC250123F600363BD3 /* ComplicationController.swift */, + E7EB03E625080773003043D8 /* ExtensionDelegate.swift */, + E7360BCE25028B26006A4E17 /* VulcanStore.swift */, + ); + path = Data; + sourceTree = ""; + }; + E7518A2925012C4B00135D55 /* Views */ = { + isa = PBXGroup; + children = ( + E7A624B0253CA116006DEDDE /* Components */, + E7A62483253C9BCA006DEDDE /* Now */, + E7A62489253C9BD1006DEDDE /* NextUp */, + E7A6248F253C9C6B006DEDDE /* EventView.swift */, + E7A624A4253CA0E4006DEDDE /* CurrentEventView.swift */, + E7A62496253CA093006DEDDE /* NextEventView.swift */, + ); + path = Views; + sourceTree = ""; + }; + E7518A2C25012CBD00135D55 /* Data */ = { + isa = PBXGroup; + children = ( + E7518A2D25012CC800135D55 /* NowProvider.swift */, + E772FEF1253C9489003F80AF /* NextUpProvider.swift */, + ); + path = Data; + sourceTree = ""; + }; + E78FC1C325161DAB00478AC1 /* Details */ = { + isa = PBXGroup; + children = ( + E78FC1C425161DB700478AC1 /* GradesDetailView.swift */, + E78FC1F8251626AE00478AC1 /* MessageDetailView.swift */, + ); + path = Details; + sourceTree = ""; + }; + E7A62483253C9BCA006DEDDE /* Now */ = { + isa = PBXGroup; + children = ( + E772FF16253C9786003F80AF /* NowEntryView.swift */, + ); + path = Now; + sourceTree = ""; + }; + E7A62489253C9BD1006DEDDE /* NextUp */ = { + isa = PBXGroup; + children = ( + E7518A2A25012C9000135D55 /* NextUpEntryView.swift */, + ); + path = NextUp; + sourceTree = ""; + }; + E7A624B0253CA116006DEDDE /* Components */ = { + isa = PBXGroup; + children = ( + E7A624B1253CA121006DEDDE /* SmallEventCell.swift */, + ); + path = Components; + sourceTree = ""; + }; + E7C144D7250123F500363BD3 /* WatchKit */ = { + isa = PBXGroup; + children = ( + E7C144D8250123F500363BD3 /* Assets.xcassets */, + E7C144DA250123F500363BD3 /* Info.plist */, + ); + path = WatchKit; + sourceTree = ""; + }; + E7C144E3250123F600363BD3 /* WatchKit Extension */ = { + isa = PBXGroup; + children = ( + E7C144E4250123F600363BD3 /* vulcanApp.swift */, + E7C144F3250123F600363BD3 /* Info.plist */, + E7C145002501242D00363BD3 /* WatchKit Extension.entitlements */, + E7C144F4250123F600363BD3 /* PushNotificationPayload.apns */, + E7C144EE250123F600363BD3 /* Assets.xcassets */, + E7360BCD25028B17006A4E17 /* Data */, + E7C145012501248800363BD3 /* Views */, + E7EB03EF25081865003043D8 /* Localization */, + E7C144F0250123F600363BD3 /* Preview Content */, + ); + path = "WatchKit Extension"; + sourceTree = ""; + }; + E7C144F0250123F600363BD3 /* Preview Content */ = { + isa = PBXGroup; + children = ( + E7C144F1250123F600363BD3 /* Preview Assets.xcassets */, + ); + path = "Preview Content"; + sourceTree = ""; + }; + E7C145012501248800363BD3 /* Views */ = { + isa = PBXGroup; + children = ( + E722C3F325020ECD0087C007 /* Components */, + E78FC1C325161DAB00478AC1 /* Details */, + E7C144E6250123F600363BD3 /* ContentView.swift */, + E7C144EA250123F600363BD3 /* NotificationView.swift */, + E783D39C2502917200514060 /* ScheduleView.swift */, + E783D39E2502917A00514060 /* GradesView.swift */, + E783D3A02502918200514060 /* FinalGradesView.swift */, + E783D3A22502918A00514060 /* TasksView.swift */, + E783D3A42502919200514060 /* MessagesView.swift */, + E783D3A6250291E300514060 /* DebugView.swift */, + ); + path = Views; + sourceTree = ""; + }; + E7C1452225012A2100363BD3 /* Widget */ = { + isa = PBXGroup; + children = ( + E7C1452325012A2100363BD3 /* VulcanWidget.swift */, + E7C1452625012A2200363BD3 /* Assets.xcassets */, + E7C1452825012A2200363BD3 /* Info.plist */, + E7C1452E25012A2200363BD3 /* Widget.entitlements */, + E71374902501821D000EA663 /* Localization */, + E7518A2C25012CBD00135D55 /* Data */, + E7518A2925012C4B00135D55 /* Views */, + ); + path = Widget; + sourceTree = ""; + }; + E7EB03EF25081865003043D8 /* Localization */ = { + isa = PBXGroup; + children = ( + E7EB03F4250818DC003043D8 /* Localizable.strings */, + ); + path = Localization; + sourceTree = ""; + }; + E7F1B3F725161AFC0044F1BC /* Localization */ = { + isa = PBXGroup; + children = ( + E7F1B40B25161BB50044F1BC /* InfoPlist.strings */, + ); + path = Localization; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 0088EB5E24A37BB7006F044E /* iOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 0088EB7324A37BB7006F044E /* Build configuration list for PBXNativeTarget "iOS" */; + buildPhases = ( + 0088EB5B24A37BB7006F044E /* Sources */, + 0088EB5C24A37BB7006F044E /* Frameworks */, + 0088EB5D24A37BB7006F044E /* Resources */, + E7C144F8250123F600363BD3 /* Embed Watch Content */, + E7C145182501270600363BD3 /* Embed App Extensions */, + ); + buildRules = ( + ); + dependencies = ( + E7C144F6250123F600363BD3 /* PBXTargetDependency */, + E7C1452C25012A2200363BD3 /* PBXTargetDependency */, + ); + name = iOS; + packageProductDependencies = ( + 00FAC9D424A3D8E800ACAC83 /* KeychainAccess */, + E7790C6924B9275600BA4187 /* Vulcan */, + E7790C6F24B9280B00BA4187 /* AppNotifications */, + ); + productName = iOS; + productReference = 0088EB5F24A37BB7006F044E /* vulcan.app */; + productType = "com.apple.product-type.application"; + }; + 0088EB6624A37BB7006F044E /* macOS */ = { + isa = PBXNativeTarget; + buildConfigurationList = 0088EB7624A37BB7006F044E /* Build configuration list for PBXNativeTarget "macOS" */; + buildPhases = ( + 0088EB6324A37BB7006F044E /* Sources */, + 0088EB6424A37BB7006F044E /* Frameworks */, + 0088EB6524A37BB7006F044E /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = macOS; + packageProductDependencies = ( + 00FAC9D824A3D8F300ACAC83 /* KeychainAccess */, + E7A419AB24FA5A7400FC55D6 /* Vulcan */, + E71A45D125263492003176B3 /* AppNotifications */, + ); + productName = macOS; + productReference = 0088EB6724A37BB7006F044E /* vulcan.app */; + productType = "com.apple.product-type.application"; + }; + E7C144D5250123F500363BD3 /* WatchKit */ = { + isa = PBXNativeTarget; + buildConfigurationList = E7C144FF250123F600363BD3 /* Build configuration list for PBXNativeTarget "WatchKit" */; + buildPhases = ( + E7C144D4250123F500363BD3 /* Resources */, + E7C144FB250123F600363BD3 /* Embed App Extensions */, + ); + buildRules = ( + ); + dependencies = ( + E7C144E2250123F600363BD3 /* PBXTargetDependency */, + ); + name = WatchKit; + productName = watchkit; + productReference = E7C144D6250123F500363BD3 /* WatchKit.app */; + productType = "com.apple.product-type.application.watchapp2"; + }; + E7C144DE250123F600363BD3 /* WatchKit Extension */ = { + isa = PBXNativeTarget; + buildConfigurationList = E7C144FE250123F600363BD3 /* Build configuration list for PBXNativeTarget "WatchKit Extension" */; + buildPhases = ( + E7C144DB250123F600363BD3 /* Sources */, + E7C144DC250123F600363BD3 /* Frameworks */, + E7C144DD250123F600363BD3 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = "WatchKit Extension"; + packageProductDependencies = ( + E7C14502250124E500363BD3 /* Vulcan */, + ); + productName = "watchkit Extension"; + productReference = E7C144DF250123F600363BD3 /* WatchKit Extension.appex */; + productType = "com.apple.product-type.watchkit2-extension"; + }; + E7C1451E25012A2100363BD3 /* Widget */ = { + isa = PBXNativeTarget; + buildConfigurationList = E7C1452F25012A2200363BD3 /* Build configuration list for PBXNativeTarget "Widget" */; + buildPhases = ( + E7C1451B25012A2100363BD3 /* Sources */, + E7C1451C25012A2100363BD3 /* Frameworks */, + E7C1451D25012A2100363BD3 /* Resources */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Widget; + packageProductDependencies = ( + E7518A3125012D5500135D55 /* Vulcan */, + ); + productName = widgetExtension; + productReference = E7C1451F25012A2100363BD3 /* Widget.appex */; + productType = "com.apple.product-type.app-extension"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 0088EB5324A37BB4006F044E /* Project object */ = { + isa = PBXProject; + attributes = { + BuildIndependentTargetsInParallel = YES; + LastSwiftUpdateCheck = 1200; + LastUpgradeCheck = 1220; + TargetAttributes = { + 0088EB5E24A37BB7006F044E = { + CreatedOnToolsVersion = 12.0; + }; + 0088EB6624A37BB7006F044E = { + CreatedOnToolsVersion = 12.0; + }; + E7C144D5250123F500363BD3 = { + CreatedOnToolsVersion = 12.0; + }; + E7C144DE250123F600363BD3 = { + CreatedOnToolsVersion = 12.0; + }; + E7C1451E25012A2100363BD3 = { + CreatedOnToolsVersion = 12.0; + }; + }; + }; + buildConfigurationList = 0088EB5624A37BB4006F044E /* Build configuration list for PBXProject "vulcan" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + pl, + ); + mainGroup = 0088EB5224A37BB4006F044E; + packageReferences = ( + 00FAC9D324A3D8E800ACAC83 /* XCRemoteSwiftPackageReference "KeychainAccess" */, + ); + productRefGroup = 0088EB6024A37BB7006F044E /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 0088EB5E24A37BB7006F044E /* iOS */, + 0088EB6624A37BB7006F044E /* macOS */, + E7C144D5250123F500363BD3 /* WatchKit */, + E7C144DE250123F600363BD3 /* WatchKit Extension */, + E7C1451E25012A2100363BD3 /* Widget */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 0088EB5D24A37BB7006F044E /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0088EB6F24A37BB7006F044E /* Assets.xcassets in Resources */, + E7F1B40925161BB50044F1BC /* InfoPlist.strings in Resources */, + 00FACA5B24A40C2800ACAC83 /* Colors.xcassets in Resources */, + E704C12D24F9A1F90036073F /* LaunchScreen.storyboard in Resources */, + 00FACA3124A3E34000ACAC83 /* Localizable.strings in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0088EB6524A37BB7006F044E /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 0088EB7024A37BB7006F044E /* Assets.xcassets in Resources */, + 00FACA5C24A40C2800ACAC83 /* Colors.xcassets in Resources */, + E704C12E24F9A1F90036073F /* LaunchScreen.storyboard in Resources */, + 00FACA3224A3E34000ACAC83 /* Localizable.strings in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E7C144D4250123F500363BD3 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E7C144D9250123F500363BD3 /* Assets.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E7C144DD250123F600363BD3 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E7A7D38D2503A7EF00B7D4CB /* Colors.xcassets in Resources */, + E7EB03F2250818DC003043D8 /* Localizable.strings in Resources */, + E7C144F2250123F600363BD3 /* Preview Assets.xcassets in Resources */, + E7C144EF250123F600363BD3 /* Assets.xcassets in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E7C1451D25012A2100363BD3 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E7C1452725012A2200363BD3 /* Assets.xcassets in Resources */, + E71374932501825D000EA663 /* Localizable.strings in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 0088EB5B24A37BB7006F044E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 00FACA0D24A3D9A600ACAC83 /* Bundle.swift in Sources */, + 00FAC9C824A3D85400ACAC83 /* SettingsModel.swift in Sources */, + 0026DB7624A7942200E232E5 /* MessageCell.swift in Sources */, + 00FAC9E124A3D93000ACAC83 /* Date.swift in Sources */, + 0026DB7924A7AC0C00E232E5 /* ComposeMessageView.swift in Sources */, + 00FACA3E24A3EDC900ACAC83 /* SetupView.swift in Sources */, + 0026DB8824A7C1CE00E232E5 /* NoteCell.swift in Sources */, + 0088EBAF24A37C5C006F044E /* LinkPreview.swift in Sources */, + 0088EBA924A37C50006F044E /* String.swift in Sources */, + 006AF91224A5F90F00D06D21 /* ScheduleEventCell.swift in Sources */, + 00FAC9F924A3D9A600ACAC83 /* View.swift in Sources */, + 00FACA0124A3D9A600ACAC83 /* DeviceInfo.swift in Sources */, + 00FACA5224A4073A00ACAC83 /* DebugView.swift in Sources */, + 003FC5F724A4B54400001F47 /* AppDelegate.swift in Sources */, + E723FAD72518F06C00DD8184 /* LicenseView.swift in Sources */, + E772E6D624B36FB900A7FFB4 /* View+.swift in Sources */, + 00FACA3C24A3EDC900ACAC83 /* OnboardingView.swift in Sources */, + 0026DB7F24A7B3BC00E232E5 /* MessageDetailView.swift in Sources */, + 00708A6B24B743B1009FB4DD /* Notifications.swift in Sources */, + 0012BAA124A4C16B00371F23 /* RefreshButton.swift in Sources */, + 0088EBBE24A37DA2006F044E /* MessagesView.swift in Sources */, + E7EB03ED25081177003043D8 /* WatchSessionManager.swift in Sources */, + E723FAD02518F05500DD8184 /* ColorSchemeSettingsView.swift in Sources */, + 00FACA6624A40F9900ACAC83 /* GradeCell.swift in Sources */, + 006AF91B24A6008500D06D21 /* TaskCell.swift in Sources */, + 0088EBB524A37D86006F044E /* GradesView.swift in Sources */, + 0026DB8524A7C17D00E232E5 /* FinalGradeCell.swift in Sources */, + 00FACA6224A40EF100ACAC83 /* GradesDetailView.swift in Sources */, + 0026DB8B24A7C6AD00E232E5 /* CloseButton.swift in Sources */, + 00FACA3824A3EAB300ACAC83 /* SettingsView.swift in Sources */, + 0088EBBB24A37D9B006F044E /* TasksView.swift in Sources */, + 00FACA4124A3EE6F00ACAC83 /* Global.swift in Sources */, + 0088EBB824A37D92006F044E /* ScheduleView.swift in Sources */, + 00FACA6D24A41D5B00ACAC83 /* AppTabNavigation.swift in Sources */, + 0088EB6D24A37BB7006F044E /* ContentView.swift in Sources */, + 006AF91E24A600B500D06D21 /* Tab.swift in Sources */, + 0088EBB224A37CD2006F044E /* HomeView.swift in Sources */, + E723FAC92518F02700DD8184 /* AppIconView.swift in Sources */, + 0012BAA824A4EF4000371F23 /* AppState.swift in Sources */, + 00FACA6A24A41D3900ACAC83 /* AppSidebarNavigation.swift in Sources */, + 000702B424A7E5750061733F /* UsersView.swift in Sources */, + 0088EB6B24A37BB7006F044E /* vulcanApp.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + 0088EB6324A37BB7006F044E /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 003FC5F824A4B54400001F47 /* AppDelegate.swift in Sources */, + 0088EBB024A37C5C006F044E /* LinkPreview.swift in Sources */, + 006AF91C24A6008500D06D21 /* TaskCell.swift in Sources */, + 0026DB8024A7B3BC00E232E5 /* MessageDetailView.swift in Sources */, + 0088EBAA24A37C50006F044E /* String.swift in Sources */, + 00FAC9C924A3D85400ACAC83 /* SettingsModel.swift in Sources */, + 0088EBBF24A37DA2006F044E /* MessagesView.swift in Sources */, + 00FACA2724A3E2E600ACAC83 /* MacSettingsView.swift in Sources */, + 0088EBB624A37D86006F044E /* GradesView.swift in Sources */, + 00FACA0E24A3D9A600ACAC83 /* Bundle.swift in Sources */, + 0026DB8624A7C17D00E232E5 /* FinalGradeCell.swift in Sources */, + 0088EBBC24A37D9B006F044E /* TasksView.swift in Sources */, + 0012BAA924A4EF4000371F23 /* AppState.swift in Sources */, + 0026DB7724A7942200E232E5 /* MessageCell.swift in Sources */, + 0026DB7A24A7AC0C00E232E5 /* ComposeMessageView.swift in Sources */, + 00FAC9E224A3D93000ACAC83 /* Date.swift in Sources */, + 00FACA6724A40F9900ACAC83 /* GradeCell.swift in Sources */, + 00FACA3F24A3EDC900ACAC83 /* SetupView.swift in Sources */, + 0026DB8C24A7C6AD00E232E5 /* CloseButton.swift in Sources */, + 0012BAA224A4C16B00371F23 /* RefreshButton.swift in Sources */, + 0088EBB924A37D92006F044E /* ScheduleView.swift in Sources */, + 00FACA6324A40EF100ACAC83 /* GradesDetailView.swift in Sources */, + 00FACA2024A3DC0600ACAC83 /* DeviceInfo.swift in Sources */, + E772E6D724B36FB900A7FFB4 /* View+.swift in Sources */, + 00FACA3D24A3EDC900ACAC83 /* OnboardingView.swift in Sources */, + 0088EB6E24A37BB7006F044E /* ContentView.swift in Sources */, + 00FACA6E24A41D5B00ACAC83 /* AppTabNavigation.swift in Sources */, + 006AF91324A5F90F00D06D21 /* ScheduleEventCell.swift in Sources */, + 00FACA6B24A41D3900ACAC83 /* AppSidebarNavigation.swift in Sources */, + 0026DB8924A7C1CE00E232E5 /* NoteCell.swift in Sources */, + 006AF91F24A600B500D06D21 /* Tab.swift in Sources */, + 00FAC9FA24A3D9A600ACAC83 /* View.swift in Sources */, + 0088EBB324A37CD2006F044E /* HomeView.swift in Sources */, + 00708A6C24B743B1009FB4DD /* Notifications.swift in Sources */, + 0088EB6C24A37BB7006F044E /* vulcanApp.swift in Sources */, + 00FACA4224A3EE6F00ACAC83 /* Global.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E7C144DB250123F600363BD3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E7EB03EE25081685003043D8 /* View.swift in Sources */, + E78FC1C525161DB700478AC1 /* GradesDetailView.swift in Sources */, + E78FC1F9251626AE00478AC1 /* MessageDetailView.swift in Sources */, + E7C144E9250123F600363BD3 /* NotificationController.swift in Sources */, + E7F47EA6251768D50075E5E4 /* TaskCell.swift in Sources */, + E783D3A12502918200514060 /* FinalGradesView.swift in Sources */, + E7C144E7250123F600363BD3 /* ContentView.swift in Sources */, + E783D3A32502918A00514060 /* TasksView.swift in Sources */, + E783D39F2502917A00514060 /* GradesView.swift in Sources */, + E722C3F525020EDB0087C007 /* HomeCardCell.swift in Sources */, + E7C144ED250123F600363BD3 /* ComplicationController.swift in Sources */, + E7C144E5250123F600363BD3 /* vulcanApp.swift in Sources */, + E7EB03E725080773003043D8 /* ExtensionDelegate.swift in Sources */, + E7EB03EC25080F3A003043D8 /* WatchSessionManager.swift in Sources */, + E783D3A52502919200514060 /* MessagesView.swift in Sources */, + E783D39D2502917200514060 /* ScheduleView.swift in Sources */, + E783D3A7250291E300514060 /* DebugView.swift in Sources */, + E74F54A5250924EF003F8066 /* ScheduleEventCell.swift in Sources */, + E7A1524F254D88970073DB9C /* String.swift in Sources */, + E7360BCF25028B26006A4E17 /* VulcanStore.swift in Sources */, + E7C144EB250123F600363BD3 /* NotificationView.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E7C1451B25012A2100363BD3 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E7A62497253CA093006DEDDE /* NextEventView.swift in Sources */, + E7518A2E25012CC800135D55 /* NowProvider.swift in Sources */, + E7A15255254D88980073DB9C /* String.swift in Sources */, + E7A624B2253CA121006DEDDE /* SmallEventCell.swift in Sources */, + E7518A2B25012C9000135D55 /* NextUpEntryView.swift in Sources */, + E7C1452425012A2100363BD3 /* VulcanWidget.swift in Sources */, + E7A62490253C9C6B006DEDDE /* EventView.swift in Sources */, + E772FEF2253C9489003F80AF /* NextUpProvider.swift in Sources */, + E772FF17253C9786003F80AF /* NowEntryView.swift in Sources */, + E7A624A5253CA0E4006DEDDE /* CurrentEventView.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + E7C144E2250123F600363BD3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = E7C144DE250123F600363BD3 /* WatchKit Extension */; + targetProxy = E7C144E1250123F600363BD3 /* PBXContainerItemProxy */; + }; + E7C144F6250123F600363BD3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + platformFilter = ios; + target = E7C144D5250123F500363BD3 /* WatchKit */; + targetProxy = E7C144F5250123F600363BD3 /* PBXContainerItemProxy */; + }; + E7C1452C25012A2200363BD3 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = E7C1451E25012A2100363BD3 /* Widget */; + targetProxy = E7C1452B25012A2200363BD3 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 00FACA2B24A3E34000ACAC83 /* Localizable.strings */ = { + isa = PBXVariantGroup; + children = ( + 00FACA2C24A3E34000ACAC83 /* en */, + 00FACA2F24A3E34000ACAC83 /* pl */, + ); + name = Localizable.strings; + sourceTree = ""; + }; + E71374952501825D000EA663 /* Localizable.strings */ = { + isa = PBXVariantGroup; + children = ( + E71374942501825D000EA663 /* en */, + E7187BDE253CBBE400C55A95 /* pl */, + ); + name = Localizable.strings; + sourceTree = ""; + }; + E7EB03F4250818DC003043D8 /* Localizable.strings */ = { + isa = PBXVariantGroup; + children = ( + E7EB03F3250818DC003043D8 /* en */, + E7EB03F5250818DD003043D8 /* pl */, + ); + name = Localizable.strings; + sourceTree = ""; + }; + E7F1B40B25161BB50044F1BC /* InfoPlist.strings */ = { + isa = PBXVariantGroup; + children = ( + E7F1B40A25161BB50044F1BC /* en */, + E7F1B41125161BB60044F1BC /* pl */, + ); + name = InfoPlist.strings; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 0088EB7124A37BB7006F044E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + MACOSX_DEPLOYMENT_TARGET = 10.16; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 0088EB7224A37BB7006F044E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + MACOSX_DEPLOYMENT_TARGET = 10.16; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 0088EB7424A37BB7006F044E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = iOS/vulcan.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 10; + DEVELOPMENT_TEAM = 3P384S9N87; + "ENABLE_HARDENED_RUNTIME[sdk=macosx*]" = YES; + ENABLE_PREVIEWS = YES; + INFOPLIST_FILE = iOS/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.niepostek.vulcan; + PRODUCT_NAME = vulcan; + SDKROOT = iphoneos; + SUPPORTS_MACCATALYST = YES; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2,6"; + }; + name = Debug; + }; + 0088EB7524A37BB7006F044E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = iOS/vulcan.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 10; + DEVELOPMENT_TEAM = 3P384S9N87; + "ENABLE_HARDENED_RUNTIME[sdk=macosx*]" = YES; + ENABLE_PREVIEWS = YES; + INFOPLIST_FILE = iOS/Info.plist; + IPHONEOS_DEPLOYMENT_TARGET = 14.0; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.niepostek.vulcan; + PRODUCT_NAME = vulcan; + SDKROOT = iphoneos; + SUPPORTS_MACCATALYST = YES; + SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2,6"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 0088EB7724A37BB7006F044E /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = macOS/macOS.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 10; + DEVELOPMENT_TEAM = 3P384S9N87; + ENABLE_HARDENED_RUNTIME = YES; + ENABLE_PREVIEWS = YES; + INFOPLIST_FILE = macOS/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 11.0; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.niepostek.vulcan; + PRODUCT_NAME = vulcan; + SDKROOT = macosx; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 0088EB7824A37BB7006F044E /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_ENTITLEMENTS = macOS/macOS.entitlements; + CODE_SIGN_IDENTITY = "Apple Development"; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + CURRENT_PROJECT_VERSION = 10; + DEVELOPMENT_TEAM = 3P384S9N87; + ENABLE_HARDENED_RUNTIME = YES; + ENABLE_PREVIEWS = YES; + INFOPLIST_FILE = macOS/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + MACOSX_DEPLOYMENT_TARGET = 11.0; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.niepostek.vulcan; + PRODUCT_NAME = vulcan; + SDKROOT = macosx; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + E7C144F9250123F600363BD3 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 10; + DEVELOPMENT_TEAM = 3P384S9N87; + IBSC_MODULE = watchkit_Extension; + INFOPLIST_FILE = watchkit/Info.plist; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.niepostek.vulcan.watchkit; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = watchos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 4; + WATCHOS_DEPLOYMENT_TARGET = 7.0; + }; + name = Debug; + }; + E7C144FA250123F600363BD3 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 10; + DEVELOPMENT_TEAM = 3P384S9N87; + IBSC_MODULE = watchkit_Extension; + INFOPLIST_FILE = watchkit/Info.plist; + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.niepostek.vulcan.watchkit; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = watchos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 4; + VALIDATE_PRODUCT = YES; + WATCHOS_DEPLOYMENT_TARGET = 7.0; + }; + name = Release; + }; + E7C144FC250123F600363BD3 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication; + CODE_SIGN_ENTITLEMENTS = "WatchKit Extension/WatchKit Extension.entitlements"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 10; + DEVELOPMENT_ASSET_PATHS = ""; + DEVELOPMENT_TEAM = 3P384S9N87; + ENABLE_PREVIEWS = YES; + INFOPLIST_FILE = "watchkit Extension/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.niepostek.vulcan.watchkit.extension; + PRODUCT_NAME = "${TARGET_NAME}"; + SDKROOT = watchos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 4; + WATCHOS_DEPLOYMENT_TARGET = 7.0; + }; + name = Debug; + }; + E7C144FD250123F600363BD3 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_COMPLICATION_NAME = Complication; + CODE_SIGN_ENTITLEMENTS = "WatchKit Extension/WatchKit Extension.entitlements"; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 10; + DEVELOPMENT_ASSET_PATHS = ""; + DEVELOPMENT_TEAM = 3P384S9N87; + ENABLE_PREVIEWS = YES; + INFOPLIST_FILE = "watchkit Extension/Info.plist"; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.niepostek.vulcan.watchkit.extension; + PRODUCT_NAME = "${TARGET_NAME}"; + SDKROOT = watchos; + SKIP_INSTALL = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = 4; + VALIDATE_PRODUCT = YES; + WATCHOS_DEPLOYMENT_TARGET = 7.0; + }; + name = Release; + }; + E7C1453025012A2200363BD3 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground; + CODE_SIGN_ENTITLEMENTS = Widget/Widget.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 10; + DEVELOPMENT_TEAM = 3P384S9N87; + INFOPLIST_FILE = Widget/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.niepostek.vulcan.widget; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SUPPORTS_MACCATALYST = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2,6"; + }; + name = Debug; + }; + E7C1453125012A2200363BD3 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; + ASSETCATALOG_COMPILER_WIDGET_BACKGROUND_COLOR_NAME = WidgetBackground; + CODE_SIGN_ENTITLEMENTS = Widget/Widget.entitlements; + CODE_SIGN_STYLE = Automatic; + CURRENT_PROJECT_VERSION = 10; + DEVELOPMENT_TEAM = 3P384S9N87; + INFOPLIST_FILE = Widget/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + "@executable_path/../../Frameworks", + ); + MARKETING_VERSION = 1.0.0; + PRODUCT_BUNDLE_IDENTIFIER = dev.niepostek.vulcan.widget; + PRODUCT_NAME = "$(TARGET_NAME)"; + SDKROOT = iphoneos; + SKIP_INSTALL = YES; + SUPPORTS_MACCATALYST = YES; + SWIFT_VERSION = 5.0; + TARGETED_DEVICE_FAMILY = "1,2,6"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 0088EB5624A37BB4006F044E /* Build configuration list for PBXProject "vulcan" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0088EB7124A37BB7006F044E /* Debug */, + 0088EB7224A37BB7006F044E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 0088EB7324A37BB7006F044E /* Build configuration list for PBXNativeTarget "iOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0088EB7424A37BB7006F044E /* Debug */, + 0088EB7524A37BB7006F044E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 0088EB7624A37BB7006F044E /* Build configuration list for PBXNativeTarget "macOS" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 0088EB7724A37BB7006F044E /* Debug */, + 0088EB7824A37BB7006F044E /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E7C144FE250123F600363BD3 /* Build configuration list for PBXNativeTarget "WatchKit Extension" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E7C144FC250123F600363BD3 /* Debug */, + E7C144FD250123F600363BD3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E7C144FF250123F600363BD3 /* Build configuration list for PBXNativeTarget "WatchKit" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E7C144F9250123F600363BD3 /* Debug */, + E7C144FA250123F600363BD3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + E7C1452F25012A2200363BD3 /* Build configuration list for PBXNativeTarget "Widget" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E7C1453025012A2200363BD3 /* Debug */, + E7C1453125012A2200363BD3 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + 00FAC9D324A3D8E800ACAC83 /* XCRemoteSwiftPackageReference "KeychainAccess" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/kishikawakatsumi/KeychainAccess.git"; + requirement = { + branch = master; + kind = branch; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + 00FAC9D424A3D8E800ACAC83 /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = 00FAC9D324A3D8E800ACAC83 /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; + 00FAC9D824A3D8F300ACAC83 /* KeychainAccess */ = { + isa = XCSwiftPackageProductDependency; + package = 00FAC9D324A3D8E800ACAC83 /* XCRemoteSwiftPackageReference "KeychainAccess" */; + productName = KeychainAccess; + }; + E71A45D125263492003176B3 /* AppNotifications */ = { + isa = XCSwiftPackageProductDependency; + productName = AppNotifications; + }; + E7518A3125012D5500135D55 /* Vulcan */ = { + isa = XCSwiftPackageProductDependency; + productName = Vulcan; + }; + E7790C6924B9275600BA4187 /* Vulcan */ = { + isa = XCSwiftPackageProductDependency; + productName = Vulcan; + }; + E7790C6F24B9280B00BA4187 /* AppNotifications */ = { + isa = XCSwiftPackageProductDependency; + productName = AppNotifications; + }; + E7A419AB24FA5A7400FC55D6 /* Vulcan */ = { + isa = XCSwiftPackageProductDependency; + productName = Vulcan; + }; + E7C14502250124E500363BD3 /* Vulcan */ = { + isa = XCSwiftPackageProductDependency; + productName = Vulcan; + }; +/* End XCSwiftPackageProductDependency section */ + }; + rootObject = 0088EB5324A37BB4006F044E /* Project object */; +} diff --git a/vulcan.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/vulcan.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..919434a --- /dev/null +++ b/vulcan.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/vulcan.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/vulcan.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/vulcan.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/vulcan.xcodeproj/xcshareddata/xcschemes/WatchKit (Complication).xcscheme b/vulcan.xcodeproj/xcshareddata/xcschemes/WatchKit (Complication).xcscheme new file mode 100644 index 0000000..8b084bd --- /dev/null +++ b/vulcan.xcodeproj/xcshareddata/xcschemes/WatchKit (Complication).xcscheme @@ -0,0 +1,107 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vulcan.xcodeproj/xcshareddata/xcschemes/WatchKit (Notification).xcscheme b/vulcan.xcodeproj/xcshareddata/xcschemes/WatchKit (Notification).xcscheme new file mode 100644 index 0000000..ec02b0d --- /dev/null +++ b/vulcan.xcodeproj/xcshareddata/xcschemes/WatchKit (Notification).xcscheme @@ -0,0 +1,109 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vulcan.xcodeproj/xcshareddata/xcschemes/WatchKit.xcscheme b/vulcan.xcodeproj/xcshareddata/xcschemes/WatchKit.xcscheme new file mode 100644 index 0000000..a816f64 --- /dev/null +++ b/vulcan.xcodeproj/xcshareddata/xcschemes/WatchKit.xcscheme @@ -0,0 +1,105 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vulcan.xcodeproj/xcshareddata/xcschemes/Widget.xcscheme b/vulcan.xcodeproj/xcshareddata/xcschemes/Widget.xcscheme new file mode 100644 index 0000000..4d51f15 --- /dev/null +++ b/vulcan.xcodeproj/xcshareddata/xcschemes/Widget.xcscheme @@ -0,0 +1,123 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vulcan.xcodeproj/xcshareddata/xcschemes/iOS.xcscheme b/vulcan.xcodeproj/xcshareddata/xcschemes/iOS.xcscheme new file mode 100644 index 0000000..e71151a --- /dev/null +++ b/vulcan.xcodeproj/xcshareddata/xcschemes/iOS.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/vulcan.xcodeproj/xcshareddata/xcschemes/macOS.xcscheme b/vulcan.xcodeproj/xcshareddata/xcschemes/macOS.xcscheme new file mode 100644 index 0000000..3e13b81 --- /dev/null +++ b/vulcan.xcodeproj/xcshareddata/xcschemes/macOS.xcscheme @@ -0,0 +1,78 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +