diff options
author | Mo Tarbin <mhed.t91@gmail.com> | 2024-06-30 21:41:41 -0400 |
---|---|---|
committer | Mo Tarbin <mhed.t91@gmail.com> | 2024-06-30 21:41:41 -0400 |
commit | c13dd9addbf89f716e4ef5cfdf1d673139ffcb68 (patch) | |
tree | bc09646ce1d6d3a402abb4694e19da51b57204f6 | |
download | donetick-c13dd9addbf89f716e4ef5cfdf1d673139ffcb68.tar.gz donetick-c13dd9addbf89f716e4ef5cfdf1d673139ffcb68.tar.bz2 donetick-c13dd9addbf89f716e4ef5cfdf1d673139ffcb68.zip |
Move to Donetick Org, first commit
Diffstat (limited to '')
42 files changed, 7463 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bab8834 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +donetick.db diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..a48d3c1 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM golang:1.22 + +WORKDIR /usr/src/app + + +COPY go.mod go.sum ./ +RUN go mod download && go mod verify + +COPY . . +RUN CGO_ENABLED=1 GOOS=linux go build -ldflags="-s -w " -buildvcs=false -o /donetick-core + +EXPOSE 8080 +CMD ["donetick-core"]
\ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..29ebfa5 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<https://www.gnu.org/licenses/>.
\ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..1fba609 --- /dev/null +++ b/README.md @@ -0,0 +1,46 @@ + +![Logo](assets/image.png) + + +## Donetick service +The Donetick service is the backend of the Donetick project. It handles all the data processing, storage, schedulers, and communication with the frontend. + +## What is Donetick? +An open-source, user-friendly app for managing tasks and chores, featuring customizable options to help you and others stay organized. + +## Why I made Donetick? +As an avid for open-source, I was eager to create a solution that could benefit the wider community. Donetick started as a personal project to address my own chore management needs, but it has evolved into bigger tool and decide to open source it for anyone seeking a customizable and privacy-focused task management tool + +## Features +- Task and Chore Management: Easily create, edit, and manage tasks and chores for yourself or your group. +- Shared To-Do Lists: Create "Circles" to collaborate on tasks with family or your group +- Assignee Assignment: Assign tasks to specific individuals or rotate them automatically using customizable strategies. +- Recurring Tasks: Schedule tasks to repeat daily, weekly, monthly, or yearly, with flexible customization options. +- Progress Tracking: Track the completion status of tasks and view historical data. + +## Installation +1. Clone the repository: +2. Navigate to the project directory: `cd donetick` +3. Download dependency `go mod download` +4. Run locally `go run .` + +## Contributing +Contributions are welcome! If you would like to contribute to Donetick, please follow these steps: +1. Fork the repository +2. Create a new branch: `git checkout -b feature/your-feature-name` +3. Make your changes and commit them: `git commit -m 'Add some feature'` +4. Push to the branch: `git push origin feature/your-feature-name` +5. Submit a pull request + +## Need Help: +As a project built while learning Golang, Donetick has evolved organically, and some areas could benefit from refactoring or optimization. I'm particularly interested in contributions that help standardize code patterns, improve performance, or enhance the overall user experience or adding new features! + +## Plans : +My goal is to expand Donetick by offering a hosted infrastructure option. This will make it even easier for users to access and utilize Donetick's features without the need for self-hosting. + +While maintaining Donetick's commitment to open source, this hosted option will provide a seamless, out-of-the-box experience for those who prefer a managed solution. + +## License +This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for more details. I might consider changing it later to something else + + diff --git a/assets/image.png b/assets/image.png Binary files differnew file mode 100644 index 0000000..e6efed1 --- /dev/null +++ b/assets/image.png diff --git a/assets/logo.svg b/assets/logo.svg new file mode 100644 index 0000000..136b82c --- /dev/null +++ b/assets/logo.svg @@ -0,0 +1,1185 @@ +<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" + width="100%" viewBox="0 0 1024 1024" enable-background="new 0 0 1024 1024" xml:space="preserve"> + +<path fill="#B5BEFB" opacity="1.000000" stroke="none" + d=" +M457.067200,42.686905 + C459.447144,26.832342 469.528015,16.203293 481.577301,7.055771 + C484.583862,4.773226 488.270081,3.385903 491.321960,1.293556 + C503.687561,1.000000 516.375122,1.000000 529.531372,1.000004 + C532.877991,2.985393 535.601196,5.258084 538.660706,6.906528 + C552.035889,14.112956 561.123352,24.814444 565.647583,39.326729 + C566.080750,40.716061 566.044800,42.251637 566.534424,44.416672 + C566.269714,53.474617 565.697205,61.835217 565.124695,70.195816 + C562.884399,82.024635 556.006897,90.798393 546.797058,98.042542 + C545.892578,98.753990 545.048767,99.542503 543.702881,100.681946 + C542.668823,101.562706 542.108643,102.056770 540.874512,103.145233 + C543.896545,103.378769 546.007507,103.627136 548.124084,103.692657 + C579.398621,104.660835 610.777283,101.454941 641.961609,106.044365 + C641.961609,106.044365 641.997559,106.000000 642.232666,106.281258 + C643.636841,106.730606 644.805908,106.898689 645.975037,107.066772 + C645.975037,107.066772 646.399109,107.196709 646.814575,107.547272 + C648.802185,108.297722 650.374390,108.697617 651.946533,109.097511 + C651.946533,109.097511 652.334167,109.251457 652.673218,109.635696 + C655.649536,111.048347 658.286804,112.076759 660.924011,113.105164 + C660.924011,113.105164 661.338745,113.293716 661.638184,113.612358 + C662.257812,113.993759 662.577942,114.056519 662.898132,114.119278 + C662.898132,114.119278 663.313416,114.351051 663.616821,114.670654 + C663.920227,114.990265 664.358093,115.225540 664.358093,115.225540 + C664.358093,115.225540 664.843811,115.120506 664.843811,115.120506 + C664.843811,115.120506 664.924805,115.072365 664.949219,115.443268 + C665.933105,116.254326 666.892517,116.694481 667.851990,117.134628 + C667.851990,117.134621 667.947266,117.053314 667.981079,117.440826 + C669.021606,118.253540 670.028381,118.678749 671.271301,119.170792 + C671.824585,119.286629 672.140808,119.341209 672.622070,119.696716 + C679.759644,127.731895 687.501282,134.920029 693.530396,143.335159 + C703.686951,157.510941 709.115906,173.618210 708.473145,191.277771 + C681.710510,191.293823 655.410950,191.385529 629.111389,191.401764 + C529.069275,191.463501 429.027130,191.500854 328.965271,191.124725 + C330.406860,167.369614 339.520386,147.529587 356.163544,131.138840 + C359.916351,127.442932 363.727966,123.806702 367.806641,120.045158 + C369.087769,118.981110 370.074799,118.014900 371.061859,117.048691 + C371.061859,117.048691 371.013489,116.999557 371.355469,117.107140 + C371.996918,116.890915 372.296387,116.567116 372.595886,116.243324 + C372.595886,116.243332 372.563263,116.098564 373.016327,116.232864 + C373.845886,115.978600 374.222382,115.590034 374.598877,115.201477 + C374.598877,115.201469 374.529510,115.009590 374.926147,115.148865 + C375.885895,114.907318 376.448944,114.526497 377.012024,114.145676 + C383.126526,111.437981 389.241028,108.730270 396.026550,106.213028 + C424.273346,100.114319 452.383545,104.830887 480.419342,102.608955 + C479.972687,101.906181 479.796143,101.424187 479.455841,101.134781 + C478.702362,100.494049 477.866638,99.950081 477.064423,99.366669 + C472.619659,94.664429 467.385376,90.467857 463.956818,85.114799 + C460.664032,79.973732 459.242096,73.634453 456.975769,66.983047 + C456.991394,58.325230 457.029297,50.506069 457.067200,42.686905 +M495.040314,43.670990 + C486.376251,56.938816 493.815094,72.260345 507.730530,74.933403 + C517.515564,76.813034 529.649231,68.062172 531.328369,59.447845 + C532.796204,51.917713 530.302063,46.677364 526.017822,41.704769 + C518.169128,32.594967 503.036163,33.744705 495.040314,43.670990 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M367.512543,120.143005 + C363.727966,123.806702 359.916351,127.442932 356.163544,131.138840 + C339.520386,147.529587 330.406860,167.369614 328.768921,191.520508 + C328.478699,198.661301 328.300964,204.983322 328.263184,211.306168 + C328.132141,233.240723 334.086792,239.255035 355.925262,239.252853 + C463.741425,239.242065 571.557556,239.221786 679.373718,239.197357 + C683.039307,239.196518 686.712097,239.247787 690.369019,239.046799 + C700.273621,238.502396 708.806946,230.141632 709.049622,220.303772 + C709.287842,210.648895 708.995605,200.980957 708.936157,191.318741 + C709.115906,173.618210 703.686951,157.510941 693.530396,143.335159 + C687.501282,134.920029 679.759644,127.731895 673.147339,119.643036 + C691.453796,119.205421 709.400879,119.116837 727.348022,119.028259 + C743.718384,119.185036 759.522888,122.356789 774.749939,128.267838 + C786.922852,132.993240 797.822937,139.913391 808.099548,148.875977 + C808.958862,149.589859 809.502563,149.758560 810.046326,149.927246 + C810.046326,149.927246 810.021057,149.975540 810.086792,150.276672 + C810.779724,151.029556 811.406799,151.481308 812.033936,151.933075 + C812.033936,151.933060 812.019409,151.965164 812.138550,152.173523 + C812.441711,152.643311 812.684631,152.826950 812.986328,152.932816 + C812.986328,152.932816 813.059509,152.936432 813.168884,153.175323 + C813.468811,153.665741 813.713806,153.841400 814.013184,153.941177 + C814.013184,153.941177 814.051208,153.950363 814.088745,154.311172 + C818.032654,158.893280 821.994446,163.064835 825.836121,167.344177 + C846.403625,190.254852 856.329895,217.527451 856.795593,247.912750 + C857.175781,272.717957 857.808350,297.541016 854.362427,322.368683 + C852.379761,336.653229 853.979675,351.360748 856.036316,365.862640 + C857.653748,377.267303 859.067017,388.958374 853.599670,400.041992 + C852.912598,401.434784 852.977539,403.305450 853.038879,404.941803 + C853.287476,411.573303 853.994141,418.202515 853.938171,424.827576 + C853.815247,439.383301 853.345520,453.936340 852.972229,468.489319 + C852.938599,469.801819 852.610535,471.112061 852.363953,472.412842 + C850.920166,480.029877 848.397461,487.615387 848.193176,495.263733 + C847.398071,525.033203 847.340332,554.822327 846.994141,584.603882 + C846.972412,586.474854 846.830505,588.344421 846.744507,590.214600 + C846.145996,590.232544 845.547485,590.250549 844.948975,590.268494 + C844.658142,587.152283 844.109802,584.033447 844.141357,580.920532 + C844.181458,576.954102 844.996338,572.987915 844.935974,569.029785 + C844.796814,559.899963 844.151367,550.777222 844.039978,541.647644 + C843.875366,528.157349 844.023315,514.663452 843.973206,501.171417 + C843.962769,498.366394 844.243896,495.191406 839.997925,494.538177 + C839.326233,478.318695 839.758423,462.430847 837.779663,446.849182 + C834.529297,421.255829 823.151123,398.918518 805.493042,380.181274 + C793.981995,367.966766 781.588867,356.570251 769.352356,345.060852 + C765.653015,341.581299 761.155518,338.950317 756.843567,335.649292 + C743.908691,326.317169 729.995605,319.814392 714.687195,316.457092 + C713.554565,316.208710 712.242615,316.778168 710.639099,316.950745 + C698.542175,312.221039 686.391602,309.916016 673.730347,309.923553 + C565.775574,309.987640 457.820831,309.968811 349.866089,310.059326 + C344.561615,310.063751 339.193878,310.469238 333.963470,311.337677 + C280.783264,320.168030 243.279373,364.230225 243.023254,418.147522 + C242.903763,443.303101 242.982635,468.459686 242.985275,493.615814 + C242.994949,586.243652 242.955917,678.871582 243.061478,771.499329 + C243.088242,794.982666 249.616028,816.593689 263.836487,835.442505 + C268.606262,841.764709 274.585938,847.174133 279.898254,853.120605 + C279.604553,853.562805 279.704010,853.814636 280.044067,853.997742 + C280.005829,853.999634 280.002563,853.923096 280.186279,854.166626 + C280.937561,854.595703 281.505157,854.781189 282.037994,854.970215 + C282.003235,854.973633 282.046844,854.919006 282.027588,855.286072 + C283.158875,857.410828 284.116425,859.338989 285.492432,860.897583 + C292.535645,868.875305 299.851685,876.616882 306.761627,884.706421 + C317.245636,896.980347 329.179504,907.451233 343.404388,915.154358 + C365.429352,927.081238 388.899506,932.710754 413.902679,931.339478 + C408.122437,933.121399 402.442688,934.550720 396.761139,935.972961 + C390.791687,937.467468 385.126617,937.440063 379.376343,934.430664 + C374.882202,932.078674 369.887848,929.649963 364.994995,929.370667 + C359.659149,929.066101 355.466064,927.296631 351.280640,924.582336 + C350.536652,924.099854 349.671295,923.804443 347.977051,923.005249 + C349.180267,925.916565 350.009216,927.922302 350.923737,930.135132 + C345.875610,932.306213 339.497589,930.720032 336.486237,936.514343 + C336.331818,936.811401 335.562317,936.919800 335.088043,936.900391 + C324.405731,936.462463 313.717834,936.111389 303.045990,935.486938 + C296.836243,935.123596 290.664795,934.695129 285.914490,939.670166 + C283.610229,942.083435 281.634979,942.063660 278.927979,940.412354 + C276.570862,938.974487 273.935120,937.459961 271.281799,937.137634 + C262.104797,936.022888 253.458191,933.694641 245.492767,928.815491 + C238.599548,924.593079 231.271408,921.058594 224.521591,916.631348 + C219.204956,913.144165 214.256332,909.001465 209.550766,904.704773 + C205.226151,900.755737 201.842072,895.720215 197.316742,892.062683 + C192.335907,888.036987 190.979248,882.060059 187.697311,877.163818 + C185.246872,873.508179 183.672867,869.253052 181.818619,865.214294 + C180.663101,862.697388 178.861938,860.101013 178.817535,857.515076 + C178.628326,846.496338 173.810349,837.184875 168.344193,827.855835 + C167.921219,832.154236 167.309845,836.566223 168.032440,840.747681 + C170.493652,854.990051 175.235184,868.571350 181.171188,881.728210 + C182.196503,884.000732 182.235214,885.558777 179.185074,885.971924 + C174.280182,873.505493 169.628265,861.253113 164.956284,848.705566 + C164.636017,848.262268 164.335815,848.114014 164.035629,847.965759 + C164.035629,847.965759 164.018539,847.998840 164.312347,847.753601 + C164.076660,845.324341 163.547180,843.140381 163.017685,840.956360 + C163.017685,840.956360 163.043472,840.974731 163.221771,840.560669 + C163.123734,837.398071 162.847382,834.649475 162.610870,831.475159 + C162.540268,823.223755 162.330643,815.398010 162.334015,807.572449 + C162.415344,619.038269 162.519424,430.504120 162.764160,241.573059 + C164.396896,224.044144 169.042175,207.829910 176.951843,192.546234 + C177.533127,191.422989 177.651611,190.060211 177.985229,188.808792 + C180.320938,185.255600 182.656647,181.702408 185.368835,177.754288 + C188.851440,173.245544 191.957565,169.131729 195.063690,165.017914 + C195.063675,165.017914 195.003845,165.003922 195.364883,165.080093 + C199.946686,161.225510 204.181549,157.309738 208.382980,153.358398 + C210.961136,150.933762 213.488052,148.454681 216.037979,146.000031 + C216.037979,146.000031 216.029800,146.033829 216.361084,146.145721 + C217.813522,145.179688 218.934677,144.101730 220.055832,143.023773 + C220.055832,143.023773 220.000656,143.001984 220.359589,143.120880 + C222.158813,142.152878 223.599106,141.065979 225.039383,139.979095 + C225.039383,139.979095 225.032379,140.038437 225.349579,140.081543 + C226.460587,139.416077 227.254410,138.707520 228.048218,137.998962 + C228.048218,137.998962 228.037643,138.048889 228.387024,138.114716 + C233.485779,135.763092 238.235138,133.345642 243.359009,130.899567 + C250.604446,128.297592 257.475372,125.724258 264.346283,123.150917 + C264.346283,123.150917 264.479218,123.093704 264.901001,123.138603 + C265.551697,123.137711 265.780579,123.091919 266.430298,123.052216 + C274.237335,121.799263 281.623535,120.540222 289.476929,119.317017 + C314.376343,119.306656 338.808563,119.244797 363.240784,119.254318 + C364.664825,119.254875 366.088623,119.833435 367.512543,120.143005 +z"/> +<path fill="#F2BB78" opacity="1.000000" stroke="none" + d=" +M840.018799,495.007324 + C844.243896,495.191406 843.962769,498.366394 843.973206,501.171417 + C844.023315,514.663452 843.875366,528.157349 844.039978,541.647644 + C844.151367,550.777222 844.796814,559.899963 844.935974,569.029785 + C844.996338,572.987915 844.181458,576.954102 844.141357,580.920532 + C844.109802,584.033447 844.658142,587.152283 844.948975,590.268494 + C845.547485,590.250549 846.145996,590.232544 846.744507,590.214600 + C846.830505,588.344421 846.972412,586.474854 846.994141,584.603882 + C847.340332,554.822327 847.398071,525.033203 848.193176,495.263733 + C848.397461,487.615387 850.920166,480.029877 852.363953,472.412842 + C852.610535,471.112061 852.938599,469.801819 852.972229,468.489319 + C853.345520,453.936340 853.815247,439.383301 853.938171,424.827576 + C853.994141,418.202515 853.287476,411.573303 853.038879,404.941803 + C852.977539,403.305450 852.912598,401.434784 853.599670,400.041992 + C859.067017,388.958374 857.653748,377.267303 856.036316,365.862640 + C853.979675,351.360748 852.379761,336.653229 854.362427,322.368683 + C857.808350,297.541016 857.175781,272.717957 856.795593,247.912750 + C856.329895,217.527451 846.403625,190.254852 825.836121,167.344177 + C821.994446,163.064835 818.032654,158.893280 814.095337,154.329620 + C820.264893,160.224182 826.899231,166.093796 832.564697,172.783936 + C841.113281,182.878738 846.997009,194.774704 851.359863,207.113754 + C854.489685,215.965591 855.696167,225.527374 857.407471,234.837357 + C858.177551,239.026825 858.343750,243.374557 858.346741,247.650787 + C858.401428,326.463135 858.385925,405.275482 858.399048,484.087860 + C858.400269,491.249817 858.513855,498.411652 858.543823,505.573700 + C858.844360,577.417786 859.186035,649.261780 859.413391,721.106079 + C859.523010,755.761902 859.915344,790.429138 859.178833,825.069885 + C858.842896,840.865723 855.393066,856.446045 849.288391,871.254150 + C839.527588,894.930969 823.921387,914.099121 803.508240,929.201782 + C795.927734,934.810120 787.249023,939.034180 778.781982,943.318115 + C768.792419,948.372375 758.154053,951.665405 746.162720,952.788208 + C744.932739,952.769287 744.469482,952.730286 744.004517,952.517944 + C744.002747,952.344543 744.002441,951.997559 744.390686,951.930542 + C770.306152,947.103455 792.922974,936.492004 812.617310,919.343201 + C829.715393,904.455261 841.866272,886.435974 849.380493,865.190491 + C851.441040,859.364441 854.719177,853.565063 851.139221,847.075500 + C850.650146,846.188904 850.874817,844.733948 851.141113,843.632019 + C854.427124,830.033813 850.615173,817.046753 847.751892,803.987915 + C847.554016,803.085510 846.639954,802.340088 845.998352,801.436340 + C843.891052,803.736511 845.286621,809.205322 839.863281,806.469971 + C839.903625,797.339233 839.957275,788.672791 839.959473,780.006409 + C839.983948,685.006714 840.000244,590.007019 840.018799,495.007324 +M856.997559,549.500000 + C856.997559,536.177307 856.997559,522.854614 856.997559,509.531891 + C856.742004,509.535126 856.486450,509.538391 856.230896,509.541626 + C856.230896,577.883972 856.230896,646.226257 856.230896,714.568542 + C856.486450,714.569092 856.742004,714.569580 856.997559,714.570068 + C856.997559,659.880066 856.997559,605.190002 856.997559,549.500000 +M855.997559,445.500366 + C855.997559,459.519104 855.997559,473.537842 855.997559,487.556549 + C856.213379,487.553558 856.429199,487.550537 856.645020,487.547516 + C856.645020,467.245667 856.645020,446.943817 856.645020,426.641968 + C856.429199,426.641449 856.213379,426.640930 855.997559,426.640411 + C855.997559,432.593872 855.997559,438.547302 855.997559,445.500366 +M855.997498,808.994690 + C856.085205,810.154968 856.172852,811.315247 856.260498,812.475464 + C856.419250,812.461060 856.578003,812.446655 856.736755,812.432251 + C856.736755,793.093262 856.736755,773.754272 856.736755,754.415222 + C856.490356,754.414307 856.243958,754.413391 855.997559,754.412415 + C855.997559,772.313599 855.997559,790.214783 855.997498,808.994690 +M844.997559,602.588379 + C844.997559,604.428589 844.997559,606.268738 844.997559,608.108948 + C845.444946,608.083740 845.892334,608.058594 846.339722,608.033386 + C846.339722,604.664795 846.339722,601.296143 846.339722,597.927551 + C846.011902,597.922180 845.684021,597.916809 845.356201,597.911438 + C845.236633,599.185974 845.117126,600.460510 844.997559,602.588379 +M856.030396,420.843170 + C856.155884,421.118500 856.281372,421.393799 856.406860,421.669098 + C856.518494,421.615692 856.726440,421.564087 856.727539,421.508575 + C856.747070,420.487610 856.741760,419.466217 856.741760,418.444885 + C856.542786,418.444489 856.343811,418.444092 856.144897,418.443726 + C856.098877,419.054138 856.052856,419.664551 856.030396,420.843170 +z"/> +<path fill="#637E63" opacity="1.000000" stroke="none" + d=" +M744.006287,952.691284 + C744.469482,952.730286 744.932739,952.769287 745.739624,952.877441 + C741.887573,953.948425 737.692993,955.819275 733.495789,955.825012 + C622.607300,955.977966 511.718536,955.925293 400.829803,955.938599 + C362.204681,955.943237 323.579346,956.101257 284.954834,955.969238 + C280.997284,955.955750 277.044922,954.428162 273.326263,953.260864 + C297.713715,953.297180 321.865051,953.675781 346.479370,954.119751 + C381.235168,954.164368 415.527924,954.122131 449.820709,954.126892 + C540.214294,954.139587 630.607910,954.192749 721.001465,954.150757 + C726.779480,954.148071 732.557312,953.471008 738.494019,953.152161 + C738.652832,953.196716 738.962341,953.082825 739.385437,953.109375 + C741.207764,952.987732 742.607056,952.839539 744.006287,952.691284 +z"/> +<path fill="#15CD9D" opacity="1.000000" stroke="none" + d=" +M162.619415,241.969971 + C162.519424,430.504120 162.415344,619.038269 162.334015,807.572449 + C162.330643,815.398010 162.540268,823.223755 162.438629,831.472839 + C162.226593,831.896301 161.889160,831.966003 161.889160,831.966003 + C161.592010,826.450500 161.246964,820.936951 161.017670,815.418579 + C160.900940,812.609009 160.992310,809.790710 160.987473,806.040527 + C160.990158,722.842468 161.000259,640.580322 160.964508,558.318115 + C160.963745,556.565186 160.435410,554.812500 160.153198,553.059692 + C160.112396,550.988770 160.071609,548.917847 160.337311,546.068665 + C160.760559,544.471375 160.978836,543.652466 160.979370,542.833374 + C160.997757,514.500916 161.006149,486.168457 160.961838,457.836121 + C160.959839,456.563782 160.453461,455.292236 160.182007,454.020325 + C160.112488,423.247040 160.009888,392.473785 159.981750,361.700470 + C159.945847,322.438934 159.951889,283.177307 160.025192,243.915878 + C160.028671,242.056046 160.859131,240.197739 161.656052,238.478958 + C162.211578,239.736115 162.415497,240.853043 162.619415,241.969971 +z"/> +<path fill="#00FFFF" opacity="1.000000" stroke="none" + d=" +M160.084442,553.520630 + C160.435410,554.812500 160.963745,556.565186 160.964508,558.318115 + C161.000259,640.580322 160.990158,722.842468 160.966766,805.575073 + C160.632248,804.539062 160.040527,803.032654 160.039810,801.526062 + C160.000397,719.011230 160.010559,636.496460 160.084442,553.520630 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M346.016357,954.054382 + C321.865051,953.675781 297.713715,953.297180 273.080811,952.937500 + C272.599182,952.956421 272.260376,952.915649 271.814270,952.691528 + C270.052246,952.081604 268.736267,951.695740 267.846802,951.220337 + C273.580353,948.060608 279.073853,950.637390 284.459656,950.717957 + C290.397705,950.806763 296.328369,951.926453 302.258606,951.895813 + C315.678070,951.826538 329.094482,951.260254 342.514587,951.093689 + C344.001587,951.075256 345.504486,952.336853 346.796021,953.139404 + C346.335419,953.486328 346.143494,953.746460 346.016357,954.054382 +z"/> +<path fill="#5C818F" opacity="1.000000" stroke="none" + d=" +M641.746216,105.740341 + C610.777283,101.454941 579.398621,104.660835 548.124084,103.692657 + C546.007507,103.627136 543.896545,103.378769 540.874512,103.145233 + C542.108643,102.056770 542.668823,101.562706 543.529297,100.978439 + C545.653198,101.292381 547.475647,102.042229 549.300537,102.048439 + C573.962708,102.132462 598.628418,101.899818 623.285339,102.270638 + C629.381653,102.362328 635.449768,104.330650 641.746216,105.740341 +z"/> +<path fill="#41C99D" opacity="1.000000" stroke="none" + d=" +M164.976349,849.000671 + C169.628265,861.253113 174.280182,873.505493 179.244354,886.247498 + C179.853500,887.211243 180.150436,887.685425 180.564713,888.501587 + C182.407700,891.398071 184.133316,893.952515 185.871307,896.666260 + C185.883682,896.825439 186.124237,897.035461 186.173950,897.272583 + C186.368225,897.833008 186.614944,898.025513 186.973724,898.053894 + C186.983658,898.020691 186.914673,898.026978 186.989227,898.323853 + C187.348221,898.908630 187.632660,899.196533 187.921509,899.647583 + C187.925919,899.810669 188.155853,900.042297 188.202271,900.269287 + C188.407745,900.791992 188.653412,900.964111 188.992844,901.006348 + C189.000000,901.000000 188.987137,901.013733 189.072021,901.271606 + C189.416840,901.776672 189.676758,902.023987 189.986023,902.537720 + C190.376892,903.208923 190.718445,903.613770 191.132080,904.248657 + C191.392334,904.765930 191.655960,904.936646 191.995972,904.996582 + C191.996902,905.002441 192.008835,905.005249 192.088135,905.246460 + C192.436050,905.677795 192.704681,905.867920 192.985931,906.030884 + C192.998520,906.003723 192.942551,906.024902 193.026917,906.286377 + C193.386230,906.783020 193.661179,907.018188 194.038177,907.552002 + C195.422150,909.231506 196.704071,910.612366 198.065399,912.238525 + C198.424850,912.666321 198.704941,912.848755 198.991333,913.014404 + C198.997620,912.997559 198.971634,913.023621 199.109039,913.318115 + C200.837189,915.060181 202.427948,916.507690 204.009216,917.979614 + C203.999710,918.003967 204.050385,917.991028 204.131653,918.220581 + C204.393250,918.747742 204.654968,918.925659 204.996948,918.994019 + C204.995773,919.004211 205.016068,919.001587 205.102859,919.234253 + C205.384537,919.757385 205.652847,919.940186 206.087311,920.246948 + C206.609146,920.700745 207.038300,920.922852 207.658997,921.424683 + C209.107803,922.913208 210.365097,924.121948 211.452667,925.513550 + C211.282928,925.696411 210.943954,926.062683 210.943939,926.062683 + C206.682892,922.596985 201.948410,919.565918 198.273193,915.562439 + C192.928619,909.740662 187.658661,903.631897 183.609131,896.893005 + C178.115723,887.751404 173.389374,878.078918 169.146606,868.282227 + C166.637726,862.489136 165.696335,856.017273 164.316650,849.426147 + C164.583221,849.001587 164.976349,849.000671 164.976349,849.000671 +z"/> +<path fill="#2CC4AC" opacity="1.000000" stroke="none" + d=" +M477.001221,99.704071 + C477.866638,99.950081 478.702362,100.494049 479.455841,101.134781 + C479.796143,101.424187 479.972687,101.906181 480.419342,102.608955 + C452.383545,104.830887 424.273346,100.114319 396.427979,106.251633 + C398.961578,105.079697 401.693359,103.568764 404.583801,103.148270 + C409.605164,102.417793 414.722748,102.103699 419.803162,102.068298 + C437.947723,101.941887 456.093781,102.035713 474.238251,101.903366 + C475.076782,101.897263 478.206116,103.684158 477.001221,99.704071 +z"/> +<path fill="#47C698" opacity="1.000000" stroke="none" + d=" +M162.764160,241.573059 + C162.415497,240.853043 162.211578,239.736115 162.000977,238.265656 + C163.086914,225.607986 164.658722,213.449402 170.869873,202.393097 + C173.269608,198.121384 175.208389,193.590683 177.671204,188.993378 + C177.651611,190.060211 177.533127,191.422989 176.951843,192.546234 + C169.042175,207.829910 164.396896,224.044144 162.764160,241.573059 +z"/> +<path fill="#00FF99" opacity="1.000000" stroke="none" + d=" +M160.113678,454.484558 + C160.453461,455.292236 160.959839,456.563782 160.961838,457.836121 + C161.006149,486.168457 160.997757,514.500916 160.979370,542.833374 + C160.978836,543.652466 160.760559,544.471375 160.412903,545.630859 + C160.136429,515.630432 160.090897,485.289642 160.113678,454.484558 +z"/> +<path fill="#2CC79F" opacity="1.000000" stroke="none" + d=" +M367.806641,120.045166 + C366.088623,119.833435 364.664825,119.254875 363.240784,119.254318 + C338.808563,119.244797 314.376343,119.306656 289.466949,119.043747 + C288.965912,118.554092 288.942047,118.373535 288.918152,118.192978 + C310.462250,118.128761 332.006836,118.127151 353.550110,117.957306 + C359.096130,117.913589 364.637970,117.340462 370.621796,117.029617 + C370.074799,118.014900 369.087769,118.981110 367.806641,120.045166 +z"/> +<path fill="#48D09A" opacity="1.000000" stroke="none" + d=" +M215.668030,145.999268 + C213.488052,148.454681 210.961136,150.933762 208.382980,153.358398 + C204.181549,157.309738 199.946686,161.225510 195.377960,165.107895 + C197.868362,161.645493 200.404190,157.906754 203.626160,154.904373 + C207.189178,151.584167 211.380432,148.938141 215.668030,145.999268 +z"/> +<path fill="#449678" opacity="1.000000" stroke="none" + d=" +M727.067993,118.662300 + C709.400879,119.116837 691.453796,119.205421 672.981384,119.347687 + C672.140808,119.341209 671.824585,119.286629 671.263428,118.966019 + C671.019348,118.694420 671.004333,118.285271 671.004333,118.285271 + C689.598877,118.288956 708.193420,118.292648 727.067993,118.662300 +z"/> +<path fill="#41C99D" opacity="1.000000" stroke="none" + d=" +M267.420319,951.309875 + C268.736267,951.695740 270.052246,952.081604 271.647125,952.657349 + C261.184357,952.121094 250.886978,949.728455 241.210999,944.257202 + C241.124313,943.833984 241.302032,943.614014 241.673523,943.691711 + C247.645523,945.586548 253.246033,947.403687 258.878174,949.201233 + C258.909851,949.181641 258.859283,949.126953 259.050751,949.351562 + C259.811005,949.668213 260.379791,949.760193 261.184509,949.979858 + C261.770721,950.109863 262.120941,950.112305 262.725647,950.340088 + C263.635315,950.658508 264.290497,950.751526 265.240295,950.977417 + C266.163361,951.176880 266.791840,951.243347 267.420319,951.309875 +z"/> +<path fill="#4CD298" opacity="1.000000" stroke="none" + d=" +M263.904022,123.090408 + C257.475372,125.724258 250.604446,128.297592 243.360748,130.718353 + C242.987946,130.565765 242.990158,130.203278 242.990158,130.203278 + C249.814026,127.812149 256.637878,125.421021 263.904022,123.090408 +z"/> +<path fill="#5CCD95" opacity="1.000000" stroke="none" + d=" +M288.503784,118.129204 + C288.942047,118.373535 288.965912,118.554092 288.999756,119.007919 + C281.623535,120.540222 274.237335,121.799263 266.433289,122.843079 + C266.015411,122.627853 266.037292,122.210213 266.037292,122.210220 + C273.388000,120.828621 280.738739,119.447021 288.503784,118.129204 +z"/> +<path fill="#48D09A" opacity="1.000000" stroke="none" + d=" +M242.617218,130.138428 + C242.990158,130.203278 242.987946,130.565765 242.986221,130.746979 + C238.235138,133.345642 233.485779,135.763092 228.361542,138.113708 + C232.739182,135.389130 237.491730,132.731339 242.617218,130.138428 +z"/> +<path fill="#31C5B1" opacity="1.000000" stroke="none" + d=" +M456.722168,42.940254 + C457.029297,50.506069 456.991394,58.325230 456.912781,66.575485 + C456.267456,65.588051 455.105225,64.150276 455.153412,62.754272 + C455.378571,56.227737 455.937469,49.712730 456.722168,42.940254 +z"/> +<path fill="#48D09A" opacity="1.000000" stroke="none" + d=" +M194.731934,165.100403 + C191.957565,169.131729 188.851440,173.245544 185.454941,177.380219 + C188.243088,173.328354 191.321625,169.255615 194.731934,165.100403 +z"/> +<path fill="#41C99D" opacity="1.000000" stroke="none" + d=" +M241.034378,943.943115 + C236.364349,941.944641 231.784271,939.837036 227.207275,937.247192 + C227.210373,936.764832 227.489731,936.456482 227.820953,936.574585 + C232.535446,938.999817 236.918732,941.306946 241.302032,943.614014 + C241.302032,943.614014 241.124313,943.833984 241.034378,943.943115 +z"/> +<path fill="#7F9DA3" opacity="1.000000" stroke="none" + d=" +M565.498962,70.090500 + C565.697205,61.835217 566.269714,53.474617 566.854797,44.657387 + C568.783508,52.882217 569.156189,61.504173 565.498962,70.090500 +z"/> +<path fill="#41C99D" opacity="1.000000" stroke="none" + d=" +M222.393082,934.758179 + C218.668427,932.067688 214.943787,929.377136 211.081543,926.374634 + C210.943954,926.062683 211.282928,925.696411 211.678467,925.610718 + C212.354584,925.720764 212.665527,925.807068 213.145172,925.999390 + C213.684586,926.524109 214.085602,926.833435 214.705933,927.427551 + C217.654785,929.761658 220.384354,931.811035 222.928955,934.081055 + C222.627045,934.453796 222.510071,934.606018 222.393082,934.758179 +z"/> +<path fill="#5C818F" opacity="1.000000" stroke="none" + d=" +M660.805725,112.763794 + C658.286804,112.076759 655.649536,111.048347 652.868408,109.709381 + C655.378784,110.406677 658.033081,111.414543 660.805725,112.763794 +z"/> +<path fill="#47C698" opacity="1.000000" stroke="none" + d=" +M161.939117,832.409668 + C161.889160,831.966003 162.226593,831.896301 162.398819,831.898621 + C162.847382,834.649475 163.123734,837.398071 163.225769,840.575989 + C162.697311,838.288025 162.343185,835.570740 161.939117,832.409668 +z"/> +<path fill="#47C698" opacity="1.000000" stroke="none" + d=" +M163.015701,841.388062 + C163.547180,843.140381 164.076660,845.324341 164.330139,847.747437 + C163.707321,845.930847 163.360519,843.875305 163.015701,841.388062 +z"/> +<path fill="#48D09A" opacity="1.000000" stroke="none" + d=" +M224.683655,140.010986 + C223.599106,141.065979 222.158813,142.152878 220.364136,143.150177 + C221.449112,142.054703 222.888519,141.048782 224.683655,140.010986 +z"/> +<path fill="#41C99D" opacity="1.000000" stroke="none" + d=" +M227.070450,936.918762 + C225.548859,936.480225 224.167191,935.887756 222.589325,935.026733 + C222.510071,934.606018 222.627045,934.453796 223.249023,934.136841 + C224.999268,934.800171 226.244507,935.628296 227.489746,936.456421 + C227.489731,936.456482 227.210373,936.764832 227.070450,936.918762 +z"/> +<path fill="#48D09A" opacity="1.000000" stroke="none" + d=" +M219.701996,143.018097 + C218.934677,144.101730 217.813522,145.179688 216.344193,146.149841 + C217.113388,145.032181 218.230759,144.022293 219.701996,143.018097 +z"/> +<path fill="#5C818F" opacity="1.000000" stroke="none" + d=" +M651.792419,108.764847 + C650.374390,108.697617 648.802185,108.297722 647.027466,107.609283 + C648.429382,107.691216 650.033813,108.061699 651.792419,108.764847 +z"/> +<path fill="#5C818F" opacity="1.000000" stroke="none" + d=" +M670.700195,118.123581 + C671.004333,118.285271 671.019348,118.694420 671.027222,118.899185 + C670.028381,118.678749 669.021606,118.253540 667.947815,117.493896 + C668.719177,117.426941 669.557617,117.694420 670.700195,118.123581 +z"/> +<path fill="#48D09A" opacity="1.000000" stroke="none" + d=" +M227.711273,138.013611 + C227.254410,138.707520 226.460587,139.416077 225.319763,140.079605 + C225.773285,139.365799 226.573792,138.697021 227.711273,138.013611 +z"/> +<path fill="#5C818F" opacity="1.000000" stroke="none" + d=" +M645.786377,106.748795 + C644.805908,106.898689 643.636841,106.730606 642.216980,106.304337 + C643.176697,106.174377 644.387207,106.302605 645.786377,106.748795 +z"/> +<path fill="#5C818F" opacity="1.000000" stroke="none" + d=" +M667.772827,116.825638 + C666.892517,116.694481 665.933105,116.254326 664.925537,115.483963 + C665.816101,115.608055 666.754883,116.062347 667.772827,116.825638 +z"/> +<path fill="#F2BB78" opacity="1.000000" stroke="none" + d=" +M811.957642,151.649704 + C811.406799,151.481308 810.779724,151.029556 810.111206,150.264404 + C810.673645,150.422791 811.277527,150.894562 811.957642,151.649704 +z"/> +<path fill="#F2BB78" opacity="1.000000" stroke="none" + d=" +M809.940186,149.637283 + C809.502563,149.758560 808.958862,149.589859 808.242065,149.189255 + C808.657410,149.087341 809.245667,149.217331 809.940186,149.637283 +z"/> +<path fill="#2CC79F" opacity="1.000000" stroke="none" + d=" +M376.637695,114.066193 + C376.448944,114.526497 375.885895,114.907318 374.968872,115.242020 + C375.164398,114.792831 375.713898,114.389771 376.637695,114.066193 +z"/> +<path fill="#4CD298" opacity="1.000000" stroke="none" + d=" +M265.734436,122.203903 + C266.037292,122.210213 266.015411,122.627853 266.012451,122.836990 + C265.780579,123.091919 265.551697,123.137711 264.973267,123.142502 + C264.893005,122.800194 265.162262,122.498901 265.734436,122.203903 +z"/> +<path fill="#47C698" opacity="1.000000" stroke="none" + d=" +M164.956284,848.705566 + C164.976349,849.000671 164.583221,849.001587 164.386658,849.000122 + C164.141586,848.829895 164.093094,848.661194 164.040100,848.229126 + C164.335815,848.114014 164.636017,848.262268 164.956284,848.705566 +z"/> +<path fill="#5C818F" opacity="1.000000" stroke="none" + d=" +M664.806885,114.837517 + C664.843811,115.120506 664.358093,115.225540 664.358093,115.225540 + C664.358093,115.225540 663.920227,114.990265 663.839233,114.754814 + C664.095459,114.531090 664.432678,114.542809 664.806885,114.837517 +z"/> +<path fill="#2CC79F" opacity="1.000000" stroke="none" + d=" +M374.187561,115.149109 + C374.222382,115.590034 373.845886,115.978600 373.052734,116.297516 + C373.016144,115.850822 373.396210,115.473778 374.187561,115.149109 +z"/> +<path fill="#5C818F" opacity="1.000000" stroke="none" + d=" +M662.845642,113.837112 + C662.577942,114.056519 662.257812,113.993759 661.853149,113.687759 + C662.110168,113.481331 662.451660,113.518135 662.845642,113.837112 +z"/> +<path fill="#2CC79F" opacity="1.000000" stroke="none" + d=" +M372.250732,116.187820 + C372.296387,116.567116 371.996918,116.890915 371.363922,117.140533 + C371.322144,116.754997 371.613892,116.443657 372.250732,116.187820 +z"/> +<path fill="#F2BB78" opacity="1.000000" stroke="none" + d=" +M813.953918,153.702118 + C813.713806,153.841400 813.468811,153.665741 813.172302,153.211761 + C813.431458,152.998047 813.707520,153.149307 813.953918,153.702118 +z"/> +<path fill="#F2BB78" opacity="1.000000" stroke="none" + d=" +M812.928528,152.694763 + C812.684631,152.826950 812.441711,152.643311 812.156128,152.173676 + C812.407043,151.995728 812.679077,152.159485 812.928528,152.694763 +z"/> +<path fill="#2E2B2B" opacity="1.000000" stroke="none" + d=" +M708.473145,191.277771 + C708.995605,200.980957 709.287842,210.648895 709.049622,220.303772 + C708.806946,230.141632 700.273621,238.502396 690.369019,239.046799 + C686.712097,239.247787 683.039307,239.196518 679.373718,239.197357 + C571.557556,239.221786 463.741425,239.242065 355.925262,239.252853 + C334.086792,239.255035 328.132141,233.240723 328.263184,211.306168 + C328.300964,204.983322 328.478699,198.661301 328.788635,191.943115 + C429.027130,191.500854 529.069275,191.463501 629.111389,191.401764 + C655.410950,191.385529 681.710510,191.293823 708.473145,191.277771 +z"/> +<path fill="#000100" opacity="1.000000" stroke="none" + d=" +M495.262878,43.353783 + C503.036163,33.744705 518.169128,32.594967 526.017822,41.704769 + C530.302063,46.677364 532.796204,51.917713 531.328369,59.447845 + C529.649231,68.062172 517.515564,76.813034 507.730530,74.933403 + C493.815094,72.260345 486.376251,56.938816 495.262878,43.353783 +z"/> +<path fill="#FFFEFD" opacity="1.000000" stroke="none" + d=" +M280.012543,853.000793 + C274.585938,847.174133 268.606262,841.764709 263.836487,835.442505 + C249.616028,816.593689 243.088242,794.982666 243.061478,771.499329 + C242.955917,678.871582 242.994949,586.243652 242.985275,493.615814 + C242.982635,468.459686 242.903763,443.303101 243.023254,418.147522 + C243.279373,364.230225 280.783264,320.168030 333.963470,311.337677 + C339.193878,310.469238 344.561615,310.063751 349.866089,310.059326 + C457.820831,309.968811 565.775574,309.987640 673.730347,309.923553 + C686.391602,309.916016 698.542175,312.221039 710.956421,317.110474 + C714.208862,318.461761 716.783264,319.606689 719.326721,320.816620 + C732.237610,326.958344 742.848145,336.165771 752.962769,346.053680 + C752.996033,346.032593 752.917358,346.035553 752.991760,346.306854 + C753.349854,346.813904 753.633545,347.049652 753.956970,347.473633 + C754.117798,347.913452 754.315796,348.063599 754.728271,348.381989 + C755.205383,348.844452 755.544861,349.037262 755.866516,349.161255 + C755.848633,349.092407 755.716675,349.145508 755.767639,349.434631 + C756.215515,350.133972 756.612427,350.544189 756.999573,350.978455 + C756.989746,351.002502 757.041687,351.004028 757.097778,351.261414 + C757.417908,351.740967 757.682007,351.963135 758.055969,352.502197 + C772.532837,372.286804 778.836487,394.112030 778.797241,418.299408 + C778.605347,536.619324 778.744690,654.939697 778.686584,773.259949 + C778.683960,778.568298 778.346191,783.955933 777.413147,789.172180 + C768.127808,841.082336 724.888916,878.058533 672.145813,878.212402 + C564.658691,878.525879 457.169952,878.385803 349.682343,878.192505 + C341.100525,878.177063 332.413483,876.854980 323.965576,875.180359 + C308.323730,872.079590 294.769073,864.267273 282.046844,854.919006 + C282.046844,854.919006 282.003235,854.973633 281.885376,854.674683 + C281.179199,854.224792 280.590881,854.073914 280.002563,853.923096 + C280.002563,853.923096 280.005829,853.999634 280.167297,853.738770 + C280.223358,853.318909 280.117950,853.159851 280.012543,853.000793 +M478.595825,743.095276 + C498.663422,722.884033 518.741638,702.683411 538.781982,682.445190 + C540.766357,680.441223 542.776978,678.379089 544.325562,676.045410 + C547.541199,671.199585 547.714111,666.002258 544.815735,660.940613 + C541.907532,655.862061 537.212158,652.817749 531.551514,654.052673 + C527.463562,654.944580 523.108032,657.281982 520.144531,660.246765 + C487.175385,693.229980 454.484741,726.491394 421.647522,759.606934 + C412.187042,769.147583 402.497681,778.461243 392.887909,787.903931 + C381.134491,779.257324 369.358521,770.583130 357.570435,761.925415 + C347.914215,754.833557 338.425537,747.493896 328.527679,740.756042 + C318.782501,734.122070 306.343109,739.964172 305.405609,751.358704 + C304.857025,758.026367 308.485413,762.622070 313.634674,766.348206 + C336.016266,782.544189 358.390045,798.751282 380.711761,815.029541 + C392.577515,823.682678 398.964447,823.247986 409.428772,812.720459 + C432.325043,789.685913 455.210907,766.641052 478.595825,743.095276 +M593.593506,547.724487 + C598.709778,558.279968 607.850586,563.773560 618.538757,566.947998 + C634.203430,571.600586 650.300415,572.348877 666.527588,571.451294 + C678.396240,570.794800 690.086609,569.317322 700.942017,564.045959 + C716.867798,556.312317 724.129761,539.352295 717.625061,524.607910 + C713.404175,515.040283 705.594299,509.210144 695.949158,505.874756 + C675.140747,498.679108 653.758911,498.761261 632.282715,501.611450 + C622.493408,502.910583 613.009094,505.576569 604.713928,511.268127 + C591.945801,520.028687 587.876953,532.894287 593.593506,547.724487 +M430.311920,521.333984 + C424.412872,511.494080 414.973907,506.780029 404.435089,504.045685 + C385.820618,499.216125 366.927155,498.851624 347.966248,501.604187 + C337.681488,503.097290 327.736176,505.745728 319.125580,511.965790 + C300.820587,525.188904 301.548828,549.719604 320.819763,561.451599 + C325.442627,564.265930 330.658661,566.447205 335.888275,567.858521 + C350.641968,571.840271 365.764771,572.477539 380.966400,571.480652 + C392.799683,570.704712 404.512909,569.291504 415.380096,564.060608 + C432.444458,555.846741 438.867523,538.172668 430.311920,521.333984 +M683.201294,745.417236 + C678.875183,745.513611 674.549194,745.691833 670.223022,745.693970 + C622.578979,745.717346 574.934998,745.689270 527.290955,745.732788 + C514.636780,745.744324 506.119385,753.155151 506.035461,763.984863 + C505.949615,775.067200 514.631836,783.022522 527.076965,783.090088 + C542.236023,783.172302 557.395813,783.141663 572.555237,783.141907 + C609.371033,783.142639 646.186951,783.094604 683.002625,783.160950 + C690.032715,783.173584 695.674194,780.708801 699.725586,774.944824 + C707.980652,763.200256 700.328857,746.028748 683.201294,745.417236 +M573.435547,517.796875 + C563.290527,513.203308 554.096924,517.702332 552.040833,528.681213 + C550.224304,538.380920 545.466309,546.021118 537.482544,551.629333 + C513.555176,568.437317 474.801666,556.611938 472.075714,527.791504 + C471.571320,522.458679 468.217896,518.713257 463.056824,516.828613 + C451.910858,512.758362 441.973785,522.234802 444.109802,535.145996 + C445.820068,545.483887 449.907104,554.909119 456.439301,563.146667 + C473.917084,585.187134 505.757721,594.419189 534.178406,585.122131 + C558.985962,577.006897 575.193726,560.573547 580.340332,534.374939 + C581.639832,527.759460 579.713318,522.207764 573.435547,517.796875 +M339.474243,431.979828 + C335.828156,437.661072 331.469757,443.023926 328.746185,449.117493 + C326.267822,454.662567 327.625061,460.599701 331.880798,465.395721 + C338.238922,472.561127 348.371613,472.942932 355.360992,466.202850 + C360.625397,461.126282 365.369873,455.432312 371.034668,450.868103 + C378.804321,444.608063 383.656525,444.462585 391.265015,450.512360 + C396.940247,455.024902 401.674011,460.736115 406.737183,465.999939 + C412.669189,472.167053 420.260956,473.669586 427.099426,469.884247 + C434.161804,465.975098 437.887146,457.635101 435.282349,449.818817 + C433.785217,445.326324 431.594604,440.831604 428.760559,437.055054 + C407.427307,408.627106 366.645386,406.159454 339.474243,431.979828 +M628.154541,452.611237 + C639.186340,444.087555 644.515686,444.122406 654.848511,453.421021 + C659.164978,457.305450 662.849915,461.882324 666.995239,465.968567 + C672.520691,471.415222 679.697083,472.468719 686.240051,469.049805 + C692.859985,465.590668 696.739807,458.505768 695.058716,451.151093 + C694.083984,446.886444 692.195496,442.593872 689.778137,438.934937 + C676.143799,418.297729 649.069153,409.031464 624.522034,416.614532 + C608.181335,421.662506 595.618164,431.562134 588.567383,447.426849 + C584.819092,455.860718 587.804260,464.808380 595.025513,469.367218 + C602.081177,473.821533 609.730530,472.273621 616.356384,465.097839 + C620.080261,461.064819 623.856323,457.079926 628.154541,452.611237 +z"/> +<path fill="#FDA836" opacity="1.000000" stroke="none" + d=" +M282.027588,855.286072 + C294.769073,864.267273 308.323730,872.079590 323.965576,875.180359 + C332.413483,876.854980 341.100525,878.177063 349.682343,878.192505 + C457.169952,878.385803 564.658691,878.525879 672.145813,878.212402 + C724.888916,878.058533 768.127808,841.082336 777.413147,789.172180 + C778.346191,783.955933 778.683960,778.568298 778.686584,773.259949 + C778.744690,654.939697 778.605347,536.619324 778.797241,418.299408 + C778.836487,394.112030 772.532837,372.286804 757.967163,352.262115 + C757.526184,351.471436 757.283936,351.237732 757.041687,351.004028 + C757.041687,351.004028 756.989746,351.002502 756.955811,350.682068 + C756.520142,349.956268 756.118408,349.550903 755.716675,349.145508 + C755.716675,349.145508 755.848633,349.092407 755.727051,348.896423 + C755.267212,348.504425 754.928955,348.308350 754.590698,348.112305 + C754.315796,348.063599 754.117798,347.913452 753.862549,347.213348 + C753.458069,346.521759 753.187683,346.278656 752.917358,346.035553 + C752.917358,346.035553 752.996033,346.032593 752.997681,345.679779 + C754.340759,342.194855 755.682190,339.062775 757.023621,335.930664 + C761.155518,338.950317 765.653015,341.581299 769.352356,345.060852 + C781.588867,356.570251 793.981995,367.966766 805.493042,380.181274 + C823.151123,398.918518 834.529297,421.255829 837.779663,446.849182 + C839.758423,462.430847 839.326233,478.318695 839.997925,494.538177 + C840.000244,590.007019 839.983948,685.006714 839.959473,780.006409 + C839.957275,788.672791 839.903625,797.339233 839.643494,806.797852 + C838.941223,811.062500 838.469360,814.534912 837.971436,818.370667 + C837.888306,819.458557 837.831360,820.183167 837.563110,821.188965 + C836.904236,823.315308 836.456665,825.160400 835.979858,827.381470 + C835.922607,828.512756 835.894592,829.267944 835.624756,830.283691 + C833.067017,836.462341 830.934265,842.460083 828.401245,848.283752 + C820.399475,866.680786 808.950439,882.542114 793.806335,895.831482 + C767.704224,918.736694 737.199402,930.656067 702.717712,930.805969 + C606.480835,931.224121 510.241028,930.971497 414.002380,930.983704 + C388.899506,932.710754 365.429352,927.081238 343.404388,915.154358 + C329.179504,907.451233 317.245636,896.980347 306.761627,884.706421 + C299.851685,876.616882 292.535645,868.875305 285.492432,860.897583 + C284.116425,859.338989 283.158875,857.410828 282.027588,855.286072 +z"/> +<path fill="#FDBD73" opacity="1.000000" stroke="none" + d=" +M413.902679,931.339478 + C510.241028,930.971497 606.480835,931.224121 702.717712,930.805969 + C737.199402,930.656067 767.704224,918.736694 793.806335,895.831482 + C808.950439,882.542114 820.399475,866.680786 828.401245,848.283752 + C830.934265,842.460083 833.067017,836.462341 835.950623,830.211914 + C836.348572,828.921509 836.178833,827.963501 836.009033,827.005432 + C836.456665,825.160400 836.904236,823.315308 837.901245,821.156677 + C838.299622,819.897827 838.148560,818.952576 837.997559,818.007324 + C838.469360,814.534912 838.941223,811.062500 839.632812,807.262207 + C845.286621,809.205322 843.891052,803.736511 845.998352,801.436340 + C846.639954,802.340088 847.554016,803.085510 847.751892,803.987915 + C850.615173,817.046753 854.427124,830.033813 851.141113,843.632019 + C850.874817,844.733948 850.650146,846.188904 851.139221,847.075500 + C854.719177,853.565063 851.441040,859.364441 849.380493,865.190491 + C841.866272,886.435974 829.715393,904.455261 812.617310,919.343201 + C792.922974,936.492004 770.306152,947.103455 744.003479,951.930786 + C741.806152,952.359619 740.384216,952.721252 738.962341,953.082825 + C738.962341,953.082825 738.652832,953.196716 737.993591,953.117432 + C607.222900,953.027039 477.111450,953.015930 347.000000,953.004822 + C345.504486,952.336853 344.001587,951.075256 342.514587,951.093689 + C329.094482,951.260254 315.678070,951.826538 302.258606,951.895813 + C296.328369,951.926453 290.397705,950.806763 284.459656,950.717957 + C279.073853,950.637390 273.580353,948.060608 267.846802,951.220337 + C266.791840,951.243347 266.163361,951.176880 264.981812,950.771851 + C263.776215,950.327087 263.123688,950.220886 262.471191,950.114746 + C262.120941,950.112305 261.770721,950.109863 260.973389,949.785278 + C259.970612,949.351013 259.414948,949.238953 258.859283,949.126953 + C258.859283,949.126953 258.909851,949.181641 258.909607,948.798828 + C257.638184,947.219116 256.554169,945.360046 255.063782,944.938782 + C248.240509,943.010132 241.385727,941.520691 235.749908,936.607056 + C232.829391,934.060791 229.235718,932.111450 225.661499,930.539734 + C222.122910,928.983582 218.226273,928.241699 214.486649,927.142700 + C214.085602,926.833435 213.684586,926.524109 213.126999,925.637329 + C212.488144,921.854431 210.445160,920.842712 207.467438,921.144897 + C207.038300,920.922852 206.609146,920.700745 205.964981,920.041443 + C205.551910,919.346619 205.307281,919.145752 205.016068,919.001587 + C205.016068,919.001587 204.995773,919.004211 204.876251,918.795471 + C204.563873,918.337646 204.328430,918.139038 204.050385,917.991028 + C204.050385,917.991028 203.999710,918.003967 203.992035,917.612488 + C202.313446,915.821899 200.642563,914.422729 198.971649,913.023560 + C198.971634,913.023621 198.997620,912.997559 198.868042,912.803101 + C198.535645,912.344788 198.284836,912.139648 197.986023,911.993164 + C196.704071,910.612366 195.422150,909.231506 193.936340,907.299805 + C193.469131,906.507568 193.205826,906.266235 192.942535,906.024902 + C192.942551,906.024902 192.998520,906.003723 192.870880,905.816528 + C192.550140,905.360535 192.305328,905.152527 192.008835,905.005249 + C192.008835,905.005249 191.996902,905.002441 191.878357,904.800293 + C191.570862,904.351379 191.337585,904.158203 191.059998,904.018555 + C190.718445,903.613770 190.376892,903.208923 189.890594,902.283875 + C189.492950,901.513672 189.240036,901.263672 188.987137,901.013733 + C188.987137,901.013733 189.000000,901.000000 188.892502,900.814087 + C188.620224,900.384644 188.410507,900.189331 188.155853,900.042297 + C188.155853,900.042297 187.925919,899.810669 187.829956,899.354736 + C187.460892,898.608215 187.187790,898.317566 186.914673,898.026978 + C186.914673,898.026978 186.983658,898.020691 186.878143,897.845154 + C186.609207,897.404358 186.393066,897.192993 186.124237,897.035461 + C186.124237,897.035461 185.883682,896.825439 185.903168,896.223083 + C186.232300,891.567139 185.097229,888.573730 180.447357,888.159607 + C180.150436,887.685425 179.853500,887.211243 179.497314,886.461426 + C182.235214,885.558777 182.196503,884.000732 181.171188,881.728210 + C175.235184,868.571350 170.493652,854.990051 168.032440,840.747681 + C167.309845,836.566223 167.921219,832.154236 168.344193,827.855835 + C173.810349,837.184875 178.628326,846.496338 178.817535,857.515076 + C178.861938,860.101013 180.663101,862.697388 181.818619,865.214294 + C183.672867,869.253052 185.246872,873.508179 187.697311,877.163818 + C190.979248,882.060059 192.335907,888.036987 197.316742,892.062683 + C201.842072,895.720215 205.226151,900.755737 209.550766,904.704773 + C214.256332,909.001465 219.204956,913.144165 224.521591,916.631348 + C231.271408,921.058594 238.599548,924.593079 245.492767,928.815491 + C253.458191,933.694641 262.104797,936.022888 271.281799,937.137634 + C273.935120,937.459961 276.570862,938.974487 278.927979,940.412354 + C281.634979,942.063660 283.610229,942.083435 285.914490,939.670166 + C290.664795,934.695129 296.836243,935.123596 303.045990,935.486938 + C313.717834,936.111389 324.405731,936.462463 335.088043,936.900391 + C335.562317,936.919800 336.331818,936.811401 336.486237,936.514343 + C339.497589,930.720032 345.875610,932.306213 350.923737,930.135132 + C350.009216,927.922302 349.180267,925.916565 347.977051,923.005249 + C349.671295,923.804443 350.536652,924.099854 351.280640,924.582336 + C355.466064,927.296631 359.659149,929.066101 364.994995,929.370667 + C369.887848,929.649963 374.882202,932.078674 379.376343,934.430664 + C385.126617,937.440063 390.791687,937.467468 396.761139,935.972961 + C402.442688,934.550720 408.122437,933.121399 413.902679,931.339478 +z"/> +<path fill="#F7A543" opacity="1.000000" stroke="none" + d=" +M756.843567,335.649292 + C755.682190,339.062775 754.340759,342.194855 752.964478,345.700867 + C742.848145,336.165771 732.237610,326.958344 719.326721,320.816620 + C716.783264,319.606689 714.208862,318.461761 711.331421,317.127136 + C712.242615,316.778168 713.554565,316.208710 714.687195,316.457092 + C729.995605,319.814392 743.908691,326.317169 756.843567,335.649292 +z"/> +<path fill="#FDA836" opacity="1.000000" stroke="none" + d=" +M280.186279,854.166626 + C280.590881,854.073914 281.179199,854.224792 281.920135,854.671204 + C281.505157,854.781189 280.937561,854.595703 280.186279,854.166626 +z"/> +<path fill="#FDA836" opacity="1.000000" stroke="none" + d=" +M279.898254,853.120605 + C280.117950,853.159851 280.223358,853.318909 280.205566,853.736877 + C279.704010,853.814636 279.604553,853.562805 279.898254,853.120605 +z"/> +<path fill="#FFBD76" opacity="1.000000" stroke="none" + d=" +M856.997559,550.000000 + C856.997559,605.190002 856.997559,659.880066 856.997559,714.570068 + C856.742004,714.569580 856.486450,714.569092 856.230896,714.568542 + C856.230896,646.226257 856.230896,577.883972 856.230896,509.541626 + C856.486450,509.538391 856.742004,509.535126 856.997559,509.531891 + C856.997559,522.854614 856.997559,536.177307 856.997559,550.000000 +z"/> +<path fill="#FFBD76" opacity="1.000000" stroke="none" + d=" +M855.997559,445.000549 + C855.997559,438.547302 855.997559,432.593872 855.997559,426.640411 + C856.213379,426.640930 856.429199,426.641449 856.645020,426.641968 + C856.645020,446.943817 856.645020,467.245667 856.645020,487.547516 + C856.429199,487.550537 856.213379,487.553558 855.997559,487.556549 + C855.997559,473.537842 855.997559,459.519104 855.997559,445.000549 +z"/> +<path fill="#FFBD76" opacity="1.000000" stroke="none" + d=" +M855.997559,808.555298 + C855.997559,790.214783 855.997559,772.313599 855.997559,754.412415 + C856.243958,754.413391 856.490356,754.414307 856.736755,754.415222 + C856.736755,773.754272 856.736755,793.093262 856.736755,812.432251 + C856.578003,812.446655 856.419250,812.461060 856.260498,812.475464 + C856.172852,811.315247 856.085205,810.154968 855.997559,808.555298 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M844.997559,602.161743 + C845.117126,600.460510 845.236633,599.185974 845.356201,597.911438 + C845.684021,597.916809 846.011902,597.922180 846.339722,597.927551 + C846.339722,601.296143 846.339722,604.664795 846.339722,608.033386 + C845.892334,608.058594 845.444946,608.083740 844.997559,608.108948 + C844.997559,606.268738 844.997559,604.428589 844.997559,602.161743 +z"/> +<path fill="#FFBD76" opacity="1.000000" stroke="none" + d=" +M856.018616,420.559082 + C856.052856,419.664551 856.098877,419.054138 856.144897,418.443726 + C856.343811,418.444092 856.542786,418.444489 856.741760,418.444885 + C856.741760,419.466217 856.747070,420.487610 856.727539,421.508575 + C856.726440,421.564087 856.518494,421.615692 856.406860,421.669098 + C856.281372,421.393799 856.155884,421.118500 856.018616,420.559082 +z"/> +<path fill="#EFC381" opacity="1.000000" stroke="none" + d=" +M739.385437,953.109375 + C740.384216,952.721252 741.806152,952.359619 743.615234,951.997803 + C744.002441,951.997559 744.002747,952.344543 744.004517,952.517944 + C742.607056,952.839539 741.207764,952.987732 739.385437,953.109375 +z"/> +<path fill="#EFC381" opacity="1.000000" stroke="none" + d=" +M346.796021,953.139404 + C477.111450,953.015930 607.222900,953.027039 737.834778,953.072876 + C732.557312,953.471008 726.779480,954.148071 721.001465,954.150757 + C630.607910,954.192749 540.214294,954.139587 449.820709,954.126892 + C415.527924,954.122131 381.235168,954.164368 346.479370,954.119751 + C346.143494,953.746460 346.335419,953.486328 346.796021,953.139404 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M180.564713,888.501587 + C185.097229,888.573730 186.232300,891.567139 185.890808,896.063843 + C184.133316,893.952515 182.407700,891.398071 180.564713,888.501587 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M207.658966,921.424744 + C210.445160,920.842712 212.488144,921.854431 212.988617,925.421936 + C212.665527,925.807068 212.354584,925.720764 211.848190,925.427856 + C210.365097,924.121948 209.107803,922.913208 207.658966,921.424744 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M199.109039,913.318115 + C200.642563,914.422729 202.313446,915.821899 204.001526,917.588135 + C202.427948,916.507690 200.837189,915.060181 199.109039,913.318115 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M205.102859,919.234253 + C205.307281,919.145752 205.551910,919.346619 205.872284,919.809692 + C205.652847,919.940186 205.384537,919.757385 205.102859,919.234253 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M204.131653,918.220581 + C204.328430,918.139038 204.563873,918.337646 204.877426,918.785278 + C204.654968,918.925659 204.393250,918.747742 204.131653,918.220581 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M198.065399,912.238525 + C198.284836,912.139648 198.535645,912.344788 198.861755,912.819946 + C198.704941,912.848755 198.424850,912.666321 198.065399,912.238525 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M193.026886,906.286377 + C193.205826,906.266235 193.469131,906.507568 193.834290,907.001099 + C193.661179,907.018188 193.386230,906.783020 193.026886,906.286377 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M186.173950,897.272583 + C186.393066,897.192993 186.609207,897.404358 186.868210,897.878357 + C186.614944,898.025513 186.368225,897.833008 186.173950,897.272583 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M186.989243,898.323853 + C187.187790,898.317566 187.460892,898.608215 187.825546,899.191650 + C187.632660,899.196533 187.348221,898.908630 186.989243,898.323853 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M188.202271,900.269287 + C188.410507,900.189331 188.620224,900.384644 188.885345,900.820435 + C188.653412,900.964111 188.407745,900.791992 188.202271,900.269287 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M189.072021,901.271606 + C189.240036,901.263672 189.492950,901.513672 189.841278,902.017456 + C189.676758,902.023987 189.416840,901.776672 189.072021,901.271606 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M191.132080,904.248657 + C191.337585,904.158203 191.570862,904.351379 191.877441,904.794434 + C191.655960,904.936646 191.392334,904.765930 191.132080,904.248657 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M192.088135,905.246460 + C192.305328,905.152527 192.550140,905.360535 192.858292,905.843689 + C192.704681,905.867920 192.436050,905.677795 192.088135,905.246460 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M214.705933,927.427490 + C218.226273,928.241699 222.122910,928.983582 225.661499,930.539734 + C229.235718,932.111450 232.829391,934.060791 235.749908,936.607056 + C241.385727,941.520691 248.240509,943.010132 255.063782,944.938782 + C256.554169,945.360046 257.638184,947.219116 258.877930,948.818420 + C253.246033,947.403687 247.645523,945.586548 241.673523,943.691772 + C236.918732,941.306946 232.535446,938.999817 227.820953,936.574585 + C226.244507,935.628296 224.999268,934.800171 223.433960,933.916199 + C220.384354,931.811035 217.654785,929.761658 214.705933,927.427490 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M259.050751,949.351562 + C259.414948,949.238953 259.970612,949.351013 260.737427,949.657593 + C260.379791,949.760193 259.811005,949.668213 259.050751,949.351562 +z"/> +<path fill="#FBBF74" opacity="1.000000" stroke="none" + d=" +M262.725647,950.340088 + C263.123688,950.220886 263.776215,950.327087 264.687195,950.638916 + C264.290497,950.751526 263.635315,950.658508 262.725647,950.340088 +z"/> +<path fill="#2E2C2A" opacity="1.000000" stroke="none" + d=" +M478.348419,743.347900 + C455.210907,766.641052 432.325043,789.685913 409.428772,812.720459 + C398.964447,823.247986 392.577515,823.682678 380.711761,815.029541 + C358.390045,798.751282 336.016266,782.544189 313.634674,766.348206 + C308.485413,762.622070 304.857025,758.026367 305.405609,751.358704 + C306.343109,739.964172 318.782501,734.122070 328.527679,740.756042 + C338.425537,747.493896 347.914215,754.833557 357.570435,761.925415 + C369.358521,770.583130 381.134491,779.257324 392.887909,787.903931 + C402.497681,778.461243 412.187042,769.147583 421.647522,759.606934 + C454.484741,726.491394 487.175385,693.229980 520.144531,660.246765 + C523.108032,657.281982 527.463562,654.944580 531.551514,654.052673 + C537.212158,652.817749 541.907532,655.862061 544.815735,660.940613 + C547.714111,666.002258 547.541199,671.199585 544.325562,676.045410 + C542.776978,678.379089 540.766357,680.441223 538.781982,682.445190 + C518.741638,702.683411 498.663422,722.884033 478.348419,743.347900 +z"/> +<path fill="#FA6874" opacity="1.000000" stroke="none" + d=" +M593.420898,547.380493 + C587.876953,532.894287 591.945801,520.028687 604.713928,511.268127 + C613.009094,505.576569 622.493408,502.910583 632.282715,501.611450 + C653.758911,498.761261 675.140747,498.679108 695.949158,505.874756 + C705.594299,509.210144 713.404175,515.040283 717.625061,524.607910 + C724.129761,539.352295 716.867798,556.312317 700.942017,564.045959 + C690.086609,569.317322 678.396240,570.794800 666.527588,571.451294 + C650.300415,572.348877 634.203430,571.600586 618.538757,566.947998 + C607.850586,563.773560 598.709778,558.279968 593.420898,547.380493 +z"/> +<path fill="#FA6874" opacity="1.000000" stroke="none" + d=" +M430.520630,521.645142 + C438.867523,538.172668 432.444458,555.846741 415.380096,564.060608 + C404.512909,569.291504 392.799683,570.704712 380.966400,571.480652 + C365.764771,572.477539 350.641968,571.840271 335.888275,567.858521 + C330.658661,566.447205 325.442627,564.265930 320.819763,561.451599 + C301.548828,549.719604 300.820587,525.188904 319.125580,511.965790 + C327.736176,505.745728 337.681488,503.097290 347.966248,501.604187 + C366.927155,498.851624 385.820618,499.216125 404.435089,504.045685 + C414.973907,506.780029 424.412872,511.494080 430.520630,521.645142 +z"/> +<path fill="#54E6DD" opacity="1.000000" stroke="none" + d=" +M683.619385,745.466919 + C700.328857,746.028748 707.980652,763.200256 699.725586,774.944824 + C695.674194,780.708801 690.032715,783.173584 683.002625,783.160950 + C646.186951,783.094604 609.371033,783.142639 572.555237,783.141907 + C557.395813,783.141663 542.236023,783.172302 527.076965,783.090088 + C514.631836,783.022522 505.949615,775.067200 506.035461,763.984863 + C506.119385,753.155151 514.636780,745.744324 527.290955,745.732788 + C574.934998,745.689270 622.578979,745.717346 670.223022,745.693970 + C674.549194,745.691833 678.875183,745.513611 683.619385,745.466919 +z"/> +<path fill="#2E2C2B" opacity="1.000000" stroke="none" + d=" +M573.774963,517.974915 + C579.713318,522.207764 581.639832,527.759460 580.340332,534.374939 + C575.193726,560.573547 558.985962,577.006897 534.178406,585.122131 + C505.757721,594.419189 473.917084,585.187134 456.439301,563.146667 + C449.907104,554.909119 445.820068,545.483887 444.109802,535.145996 + C441.973785,522.234802 451.910858,512.758362 463.056824,516.828613 + C468.217896,518.713257 471.571320,522.458679 472.075714,527.791504 + C474.801666,556.611938 513.555176,568.437317 537.482544,551.629333 + C545.466309,546.021118 550.224304,538.380920 552.040833,528.681213 + C554.096924,517.702332 563.290527,513.203308 573.774963,517.974915 +z"/> +<path fill="#2E2B2B" opacity="1.000000" stroke="none" + d=" +M339.727905,431.729614 + C366.645386,406.159454 407.427307,408.627106 428.760559,437.055054 + C431.594604,440.831604 433.785217,445.326324 435.282349,449.818817 + C437.887146,457.635101 434.161804,465.975098 427.099426,469.884247 + C420.260956,473.669586 412.669189,472.167053 406.737183,465.999939 + C401.674011,460.736115 396.940247,455.024902 391.265015,450.512360 + C383.656525,444.462585 378.804321,444.608063 371.034668,450.868103 + C365.369873,455.432312 360.625397,461.126282 355.360992,466.202850 + C348.371613,472.942932 338.238922,472.561127 331.880798,465.395721 + C327.625061,460.599701 326.267822,454.662567 328.746185,449.117493 + C331.469757,443.023926 335.828156,437.661072 339.727905,431.729614 +z"/> +<path fill="#2E2C2B" opacity="1.000000" stroke="none" + d=" +M627.881714,452.842285 + C623.856323,457.079926 620.080261,461.064819 616.356384,465.097839 + C609.730530,472.273621 602.081177,473.821533 595.025513,469.367218 + C587.804260,464.808380 584.819092,455.860718 588.567383,447.426849 + C595.618164,431.562134 608.181335,421.662506 624.522034,416.614532 + C649.069153,409.031464 676.143799,418.297729 689.778137,438.934937 + C692.195496,442.593872 694.083984,446.886444 695.058716,451.151093 + C696.739807,458.505768 692.859985,465.590668 686.240051,469.049805 + C679.697083,472.468719 672.520691,471.415222 666.995239,465.968567 + C662.849915,461.882324 659.164978,457.305450 654.848511,453.421021 + C644.515686,444.122406 639.186340,444.087555 627.881714,452.842285 +z"/> +<path fill="#F7A543" opacity="1.000000" stroke="none" + d=" +M755.767639,349.434631 + C756.118408,349.550903 756.520142,349.956268 756.965637,350.658020 + C756.612427,350.544189 756.215515,350.133972 755.767639,349.434631 +z"/> +<path fill="#F7A543" opacity="1.000000" stroke="none" + d=" +M754.728271,348.381989 + C754.928955,348.308350 755.267212,348.504425 755.744934,348.965271 + C755.544861,349.037262 755.205383,348.844452 754.728271,348.381989 +z"/> +<path fill="#F7A543" opacity="1.000000" stroke="none" + d=" +M757.097778,351.261414 + C757.283936,351.237732 757.526184,351.471436 757.857178,351.945251 + C757.682007,351.963135 757.417908,351.740967 757.097778,351.261414 +z"/> +<path fill="#F7A543" opacity="1.000000" stroke="none" + d=" +M752.991760,346.306854 + C753.187683,346.278656 753.458069,346.521759 753.822815,347.025085 + C753.633545,347.049652 753.349854,346.813904 752.991760,346.306854 +z"/> +<path fill="#F2BB78" opacity="1.000000" stroke="none" + d=" +M835.979858,827.381470 + C836.178833,827.963501 836.348572,828.921509 836.192383,829.951416 + C835.894592,829.267944 835.922607,828.512756 835.979858,827.381470 +z"/> +<path fill="#F2BB78" opacity="1.000000" stroke="none" + d=" +M837.971436,818.370667 + C838.148560,818.952576 838.299622,819.897827 838.112549,820.875366 + C837.831360,820.183167 837.888306,819.458557 837.971436,818.370667 +z"/> +</svg>
\ No newline at end of file diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..b1f73a1 --- /dev/null +++ b/config/config.go @@ -0,0 +1,126 @@ +package config + +import ( + "fmt" + "os" + "time" + + "github.com/spf13/viper" +) + +type Config struct { + Name string `mapstructure:"name" yaml:"name"` + Telegram TelegramConfig `mapstructure:"telegram" yaml:"telegram"` + Database DatabaseConfig `mapstructure:"database" yaml:"database"` + Jwt JwtConfig `mapstructure:"jwt" yaml:"jwt"` + Server ServerConfig `mapstructure:"server" yaml:"server"` + SchedulerJobs SchedulerConfig `mapstructure:"scheduler_jobs" yaml:"scheduler_jobs"` + EmailConfig EmailConfig `mapstructure:"email" yaml:"email"` + StripeConfig StripeConfig `mapstructure:"stripe" yaml:"stripe"` + IsDoneTickDotCom bool `mapstructure:"is_done_tick_dot_com" yaml:"is_done_tick_dot_com"` +} + +type TelegramConfig struct { + Token string `mapstructure:"token" yaml:"token"` +} + +type DatabaseConfig struct { + Type string `mapstructure:"type" yaml:"type"` + Host string `mapstructure:"host" yaml:"host"` + Port int `mapstructure:"port" yaml:"port"` + User string `mapstructure:"user" yaml:"user"` + Password string `mapstructure:"password" yaml:"password"` + Name string `mapstructure:"name" yaml:"name"` + Migration bool `mapstructure:"migration" yaml:"migration"` + LogLevel int `mapstructure:"logger" yaml:"logger"` +} + +type JwtConfig struct { + Secret string `mapstructure:"secret" yaml:"secret"` + SessionTime time.Duration `mapstructure:"session_time" yaml:"session_time"` + MaxRefresh time.Duration `mapstructure:"max_refresh" yaml:"max_refresh"` +} + +type ServerConfig struct { + Port int `mapstructure:"port" yaml:"port"` + RatePeriod time.Duration `mapstructure:"rate_period" yaml:"rate_period"` + RateLimit int `mapstructure:"rate_limit" yaml:"rate_limit"` + ReadTimeout time.Duration `mapstructure:"read_timeout" yaml:"read_timeout"` + WriteTimeout time.Duration `mapstructure:"write_timeout" yaml:"write_timeout"` +} + +type SchedulerConfig struct { + DueJob time.Duration `mapstructure:"due_job" yaml:"due_job"` + OverdueJob time.Duration `mapstructure:"overdue_job" yaml:"overdue_job"` + PreDueJob time.Duration `mapstructure:"pre_due_job" yaml:"pre_due_job"` +} + +type StripeConfig struct { + APIKey string `mapstructure:"api_key"` + WhitelistedIPs []string `mapstructure:"whitelisted_ips"` + Prices []StripePrices `mapstructure:"prices"` + SuccessURL string `mapstructure:"success_url"` + CancelURL string `mapstructure:"cancel_url"` +} + +type StripePrices struct { + PriceID string `mapstructure:"id"` + Name string `mapstructure:"name"` +} + +type EmailConfig struct { + Email string `mapstructure:"email"` + Key string `mapstructure:"key"` + Host string `mapstructure:"host"` + Port int `mapstructure:"port"` + AppHost string `mapstructure:"appHost"` +} + +func NewConfig() *Config { + return &Config{ + Telegram: TelegramConfig{ + Token: "", + }, + Database: DatabaseConfig{ + Type: "sqlite", + Migration: true, + }, + Jwt: JwtConfig{ + Secret: "secret", + SessionTime: 7 * 24 * time.Hour, + MaxRefresh: 7 * 24 * time.Hour, + }, + } +} + +func LoadConfig() *Config { + // read evniroment variable FORWARD_ENV and see if it's equal local then load local (config/local.yaml) using viper: + if os.Getenv("CA_ENV") == "local" { + viper.SetConfigName("local") + } else if os.Getenv("CA_ENV") == "prod" { + viper.SetConfigName("prod") + } else { + viper.SetConfigName("local") + } + // get logger and log the current environment: + fmt.Printf("--ConfigLoad config for environment: %s ", os.Getenv("CA_ENV")) + + viper.AddConfigPath("./config") + viper.SetConfigType("yaml") + err := viper.ReadInConfig() + // print a useful error: + if err != nil { + panic(err) + } + + var config Config + err = viper.Unmarshal(&config) + if err != nil { + panic(err) + } + fmt.Printf("--ConfigLoad name : %s ", config.Name) + + return &config + + // return LocalConfig() +} diff --git a/config/local.yaml b/config/local.yaml new file mode 100644 index 0000000..945a122 --- /dev/null +++ b/config/local.yaml @@ -0,0 +1,28 @@ +name: "local" +is_done_tick_dot_com: true +telegram: + token: "" +database: + type: "sqlite" + migration: true +jwt: + secret: "secret" + session_time: 168h + max_refresh: 168h +server: + port: 8000 + read_timeout: 2s + write_timeout: 1s + rate_period: 60s + rate_limit: 200 + +scheduler_jobs: + due_job: 30m + overdue_job: 3h + pre_due_job: 3h +email: + host: + port: + key: + email: + appHost: diff --git a/docker-compose.yaml b/docker-compose.yaml new file mode 100644 index 0000000..efaee3a --- /dev/null +++ b/docker-compose.yaml @@ -0,0 +1,22 @@ +version: '3.3' + +services: + app: + build: + context: . + dockerfile: Dockerfile + container_name: donetick-core + restart: unless-stopped + + volumes: + # sqlite database: + - ./data:/usr/src/app/data + + ports: + - "8085:8000" + environment: + - CA_ENV=prod + hostname: donetick-core + command: ["/donetick-core"] # Command to execute your binary inside the container +networks: + default: diff --git a/external/user/model/model.go b/external/user/model/model.go new file mode 100644 index 0000000..d132e68 --- /dev/null +++ b/external/user/model/model.go @@ -0,0 +1,14 @@ +package model + +import ( + "time" + + uModel "donetick.com/core/internal/user/model" +) + +type UserExtended struct { + uModel.User + Credit int `gorm:"column:amount;->"` + SubscriptionStatus *string `gorm:"column:status;<-:false"` // read one column + ExpiredAt *time.Time `gorm:"column:expired_at;<-:false"` // read one column +} diff --git a/external/user/repo/repository.go b/external/user/repo/repository.go new file mode 100644 index 0000000..6876984 --- /dev/null +++ b/external/user/repo/repository.go @@ -0,0 +1,49 @@ +package user + +import ( + "context" + + exUser "donetick.com/core/external/user/model" + "donetick.com/core/logging" + "gorm.io/gorm" +) + +type ExtendedUserRepository struct { + db *gorm.DB +} + +func NewExtendedUserRepository(db *gorm.DB) *ExtendedUserRepository { + return &ExtendedUserRepository{db} +} + +func (a *ExtendedUserRepository) FindFullUserByEmail(ctx context.Context, email string) (*exUser.UserExtended, error) { + logger := logging.FromContext(ctx) + logger.Debugw("repository.user.FindFullUserByEmail", "email", email) + var acc exUser.UserExtended + if err := a.db.Table("users"). + Select("users.*, s.expired_at, s.status , s.customer_id"). + Joins("LEFT JOIN stripe_customers sc ON sc.user_id = users.id"). + Joins("LEFT JOIN stripe_subscriptions s ON s.customer_id = sc.customer_id AND s.expired_at > now() OR s.expired_at is null"). + Where("email = ?", email). + First(&acc).Error; err != nil { + logger.Error("repository.user.FindFullUserByEmail failed to find", "err", err) + return nil, err + } + return &acc, nil +} + +func (a *ExtendedUserRepository) FindFullUserByUsername(ctx context.Context, username string) (*exUser.UserExtended, error) { + logger := logging.FromContext(ctx) + logger.Debugw("repository.user.FindFullUserByUsername", "username", username) + var acc exUser.UserExtended + if err := a.db.Table("users"). + Select("users.*, s.expired_at, s.status , s.customer_id"). + Joins("LEFT JOIN stripe_customers sc ON sc.user_id = users.id"). + Joins("LEFT JOIN stripe_subscriptions s ON s.customer_id = sc.customer_id AND s.expired_at > now() OR s.expired_at is null"). + Where("username = ?", username). + First(&acc).Error; err != nil { + logger.Error("repository.user.FindFullUserByUsername failed to find", "err", err) + return nil, err + } + return &acc, nil +} @@ -0,0 +1,97 @@ +module donetick.com/core + +go 1.20 + +require ( + github.com/appleboy/gin-jwt/v2 v2.9.2 + github.com/gin-contrib/cors v1.7.2 + github.com/gin-gonic/gin v1.10.0 + github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 + github.com/spf13/viper v1.19.0 + github.com/stripe/stripe-go/v76 v76.25.0 + github.com/ulule/limiter/v3 v3.11.2 + go.uber.org/fx v1.22.0 + go.uber.org/zap v1.26.0 + golang.org/x/crypto v0.23.0 + google.golang.org/api v0.183.0 + gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df + gorm.io/driver/postgres v1.5.7 + gorm.io/driver/sqlite v1.5.5 + gorm.io/gorm v1.25.10 +) + +require ( + cloud.google.com/go/auth v0.5.1 // indirect + cloud.google.com/go/auth/oauth2adapt v0.2.2 // indirect + cloud.google.com/go/compute/metadata v0.3.0 // indirect + github.com/BurntSushi/toml v0.3.1 // indirect + github.com/bytedance/sonic v1.11.8 // indirect + github.com/bytedance/sonic/loader v0.1.1 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/felixge/httpsnoop v1.0.4 // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.4 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-logr/logr v1.4.1 // indirect + github.com/go-logr/stdr v1.2.2 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.20.0 // indirect + github.com/goccy/go-json v0.10.3 // indirect + github.com/golang-jwt/jwt/v4 v4.5.0 // indirect + github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/google/s2a-go v0.1.7 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/googleapis/enterprise-certificate-proxy v0.3.2 // indirect + github.com/googleapis/gax-go/v2 v2.12.4 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect + github.com/jackc/pgx/v5 v5.4.3 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.7 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/magiconair/properties v1.8.7 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mattn/go-sqlite3 v1.14.17 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/sagikazarmark/locafero v0.4.0 // indirect + github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spf13/afero v1.11.0 // indirect + github.com/spf13/cast v1.6.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + go.opencensus.io v0.24.0 // indirect + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 // indirect + go.opentelemetry.io/otel v1.24.0 // indirect + go.opentelemetry.io/otel/metric v1.24.0 // indirect + go.opentelemetry.io/otel/trace v1.24.0 // indirect + go.uber.org/dig v1.17.1 // indirect + go.uber.org/multierr v1.10.0 // indirect + golang.org/x/arch v0.8.0 // indirect + golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect + golang.org/x/mod v0.12.0 // indirect + golang.org/x/net v0.25.0 // indirect + golang.org/x/oauth2 v0.21.0 // indirect + golang.org/x/sys v0.20.0 // indirect + golang.org/x/text v0.15.0 // indirect + golang.org/x/tools v0.13.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240528184218-531527333157 // indirect + google.golang.org/grpc v1.64.0 // indirect + google.golang.org/protobuf v1.34.1 // indirect + gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect + gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + honnef.co/go/tools v0.0.1-2020.1.4 // indirect +) @@ -0,0 +1,315 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go/auth v0.5.1 h1:0QNO7VThG54LUzKiQxv8C6x1YX7lUrzlAa1nVLF8CIw= +cloud.google.com/go/auth v0.5.1/go.mod h1:vbZT8GjzDf3AVqCcQmqeeM32U9HBFc32vVVAbwDsa6s= +cloud.google.com/go/auth/oauth2adapt v0.2.2 h1:+TTV8aXpjeChS9M+aTtN/TjdQnzJvmzKFt//oWu7HX4= +cloud.google.com/go/auth/oauth2adapt v0.2.2/go.mod h1:wcYjgpZI9+Yu7LyYBg4pqSiaRkfEK3GQcpb7C/uyF1Q= +cloud.google.com/go/compute/metadata v0.3.0 h1:Tz+eQXMEqDIKRsmY3cHTL6FVaynIjX2QxYC4trgAKZc= +cloud.google.com/go/compute/metadata v0.3.0/go.mod h1:zFmK7XCadkQkj6TtorcaGlCW1hT1fIilQDwofLpJ20k= +github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/appleboy/gin-jwt/v2 v2.9.2 h1:GeS3lm9mb9HMmj7+GNjYUtpp3V1DAQ1TkUFa5poiZ7Y= +github.com/appleboy/gin-jwt/v2 v2.9.2/go.mod h1:mxGjKt9Lrx9Xusy1SrnmsCJMZG6UJwmdHN9bN27/QDw= +github.com/appleboy/gofight/v2 v2.1.2 h1:VOy3jow4vIK8BRQJoC/I9muxyYlJ2yb9ht2hZoS3rf4= +github.com/bytedance/sonic v1.11.8 h1:Zw/j1KfiS+OYTi9lyB3bb0CFxPJVkM17k1wyDG32LRA= +github.com/bytedance/sonic v1.11.8/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4= +github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg= +github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/gabriel-vasile/mimetype v1.4.4 h1:QjV6pZ7/XZ7ryI2KuyeEDE8wnh7fHP9YnQy+R0LnH8I= +github.com/gabriel-vasile/mimetype v1.4.4/go.mod h1:JwLei5XPtWdGiMFB5Pjle1oEeoSeEuJfJE+TtfvdB/s= +github.com/gin-contrib/cors v1.7.2 h1:oLDHxdg8W/XDoN/8zamqk/Drgt4oVZDvaV0YmvVICQw= +github.com/gin-contrib/cors v1.7.2/go.mod h1:SUJVARKgQ40dmrzgXEVxj2m7Ig1v1qIboQkPDTQ9t2E= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= +github.com/go-logr/logr v1.4.1 h1:pKouT5E8xu9zeFC39JXRDukb6JFQPXM5p5I91188VAQ= +github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= +github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8= +github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= +github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= +github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= +github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= +github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE= +github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI= +github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o= +github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= +github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs= +github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0= +github.com/googleapis/gax-go/v2 v2.12.4 h1:9gWcmF85Wvq4ryPFvGFaOgPIs1AQX0d0bcbGw4Z96qg= +github.com/googleapis/gax-go/v2 v2.12.4/go.mod h1:KYEYLorsnIGDi/rPC8b5TdlB9kbKoFubselGIoBMCwI= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.4.3 h1:cxFyXhxlvAifxnkKKdlxv8XqUf59tDlYjnV5YYfsJJY= +github.com/jackc/pgx/v5 v5.4.3/go.mod h1:Ig06C2Vu0t5qXC60W8sqIthScaEnFvojjj9dSljmHRA= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM= +github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= +github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-sqlite3 v1.14.17 h1:mCRHCLDUBXgpKAqIKsaAaAsrAlbkeomtRFKXh2L6YIM= +github.com/mattn/go-sqlite3 v1.14.17/go.mod h1:2eHXhiwb8IkHr+BDWZGa96P6+rkvnG63S2DGjv9HUNg= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= +github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= +github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= +github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= +github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= +github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= +github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/stripe/stripe-go/v76 v76.25.0 h1:kmDoOTvdQSTQssQzWZQQkgbAR2Q8eXdMWbN/ylNalWA= +github.com/stripe/stripe-go/v76 v76.25.0/go.mod h1:rw1MxjlAKKcZ+3FOXgTHgwiOa2ya6CPq6ykpJ0Q6Po4= +github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/ulule/limiter/v3 v3.11.2 h1:P4yOrxoEMJbOTfRJR2OzjL90oflzYPPmWg+dvwN2tHA= +github.com/ulule/limiter/v3 v3.11.2/go.mod h1:QG5GnFOCV+k7lrL5Y8kgEeeflPH3+Cviqlqa8SVSQxI= +go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0= +go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw= +go.opentelemetry.io/otel v1.24.0 h1:0LAOdjNmQeSTzGBzduGe/rU4tZhMwL5rWgtp9Ku5Jfo= +go.opentelemetry.io/otel v1.24.0/go.mod h1:W7b9Ozg4nkF5tWI5zsXkaKKDjdVjpD4oAt9Qi/MArHo= +go.opentelemetry.io/otel/metric v1.24.0 h1:6EhoGWWK28x1fbpA4tYTOWBkPefTDQnb8WSGXlc88kI= +go.opentelemetry.io/otel/metric v1.24.0/go.mod h1:VYhLe1rFfxuTXLgj4CBiyz+9WYBA8pNGJgDcSFRKBco= +go.opentelemetry.io/otel/trace v1.24.0 h1:CsKnnL4dUAr/0llH9FKuc698G04IrpWV0MQA/Y1YELI= +go.opentelemetry.io/otel/trace v1.24.0/go.mod h1:HPc3Xr/cOApsBI154IU0OI0HJexz+aw5uPdbs3UCjNU= +go.uber.org/dig v1.17.1 h1:Tga8Lz8PcYNsWsyHMZ1Vm0OQOUaJNDyvPImgbAu9YSc= +go.uber.org/dig v1.17.1/go.mod h1:Us0rSJiThwCv2GteUN0Q7OKvU7n5J4dxZ9JKUXozFdE= +go.uber.org/fx v1.22.0 h1:pApUK7yL0OUHMd8vkunWSlLxZVFFk70jR2nKde8X2NM= +go.uber.org/fx v1.22.0/go.mod h1:HT2M7d7RHo+ebKGh9NRcrsrHHfpZ60nW3QRubMRfv48= +go.uber.org/goleak v1.2.0 h1:xqgm/S+aQvhWFTtR0XK3Jvg7z8kGV8P4X14IzwN3Eqk= +go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= +go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.26.0 h1:sI7k6L95XOKS281NhVKOFCUNIvv9e0w4BF8N3u+tCRo= +go.uber.org/zap v1.26.0/go.mod h1:dtElttAiwGvoJ/vj4IwHBS/gXsEu/pZ50mUIRWuG0so= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc= +golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI= +golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= +golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc= +golang.org/x/mod v0.12.0 h1:rmsUpXtvNzj340zd98LZ4KntptpfRHwpFOHG188oHXc= +golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210520170846-37e1c6afe023/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac= +golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.21.0 h1:tsimM75w1tF/uws5rbeHzIWxEqElMehnc+iW793zsZs= +golang.org/x/oauth2 v0.21.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.7.0 h1:YsImfSBoP9QPYL0xyKJPq0gcaJdG3rInoqxTWbfQu9M= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y= +golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk= +golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191130070609-6e064ea0cf2d/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.13.0 h1:Iey4qkscZuv0VvIt8E0neZjtPVQFSc870HQ448QgEmQ= +golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/api v0.183.0 h1:PNMeRDwo1pJdgNcFQ9GstuLe/noWKIc89pRWRLMvLwE= +google.golang.org/api v0.183.0/go.mod h1:q43adC5/pHoSZTx5h2mSmdF7NcyfW9JuDyIOJAgS9ZQ= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto v0.0.0-20240528184218-531527333157 h1:u7WMYrIrVvs0TF5yaKwKNbcJyySYf+HAIFXxWltJOXE= +google.golang.org/genproto/googleapis/api v0.0.0-20240415180920-8c6c420018be h1:Zz7rLWqp0ApfsR/l7+zSHhY3PMiH2xqgxlfYfAfNpoU= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240528184218-531527333157 h1:Zy9XzmMEflZ/MAaA7vNcoebnRAld7FsPW1EeBB7V0m8= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240528184218-531527333157/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc= +google.golang.org/grpc v1.64.0 h1:KH3VH9y/MgNQg1dE7b3XfVK0GsPSIzJwdF617gUSbvY= +google.golang.org/grpc v1.64.0/go.mod h1:oxjF8E3FBnjp+/gVFYdWacaLDx9na1aqy9oovLpxQYg= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg= +google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk= +gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE= +gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/driver/postgres v1.5.7 h1:8ptbNJTDbEmhdr62uReG5BGkdQyeasu/FZHxI0IMGnM= +gorm.io/driver/postgres v1.5.7/go.mod h1:3e019WlBaYI5o5LIdNV+LyxCMNtLOQETBXL2h4chKpA= +gorm.io/driver/sqlite v1.5.5 h1:7MDMtUZhV065SilG62E0MquljeArQZNfJnjd9i9gx3E= +gorm.io/driver/sqlite v1.5.5/go.mod h1:6NgQ7sQWAIFsPrJJl1lSNSu2TABh0ZZ/zm5fosATavE= +gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s= +gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.1-2020.1.4 h1:UoveltGrhghAA7ePc+e+QYDHXrBps2PqFZiHkGR/xK8= +honnef.co/go/tools v0.0.1-2020.1.4/go.mod h1:X/FiERA/W4tHapMX5mGpAtMSVEeEUOyHaw9vFzvIQ3k= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/internal/authorization/middleware.go b/internal/authorization/middleware.go new file mode 100644 index 0000000..18a7026 --- /dev/null +++ b/internal/authorization/middleware.go @@ -0,0 +1,137 @@ +package auth + +import ( + "net/http" + "time" + + "donetick.com/core/config" + uModel "donetick.com/core/internal/user/model" + uRepo "donetick.com/core/internal/user/repo" + "donetick.com/core/logging" + jwt "github.com/appleboy/gin-jwt/v2" + "github.com/gin-gonic/gin" + "golang.org/x/crypto/bcrypt" +) + +var identityKey = "id" + +type signIn struct { + Username string `form:"username" json:"username" binding:"required"` + Password string `form:"password" json:"password" binding:"required"` +} + +func CurrentUser(c *gin.Context) (*uModel.User, bool) { + data, ok := c.Get(identityKey) + if !ok { + return nil, false + } + acc, ok := data.(*uModel.User) + return acc, ok +} + +func MustCurrentUser(c *gin.Context) *uModel.User { + acc, ok := CurrentUser(c) + if ok { + return acc + } + panic("no account in gin.Context") +} + +func NewAuthMiddleware(cfg *config.Config, userRepo *uRepo.UserRepository) (*jwt.GinJWTMiddleware, error) { + return jwt.New(&jwt.GinJWTMiddleware{ + Realm: "test zone", + Key: []byte(cfg.Jwt.Secret), + Timeout: cfg.Jwt.SessionTime, + MaxRefresh: cfg.Jwt.MaxRefresh, // 7 days as long as their token is valid they can refresh it + IdentityKey: identityKey, + PayloadFunc: func(data interface{}) jwt.MapClaims { + if u, ok := data.(*uModel.User); ok { + return jwt.MapClaims{ + identityKey: u.Username, + } + } + return jwt.MapClaims{} + }, + IdentityHandler: func(c *gin.Context) interface{} { + claims := jwt.ExtractClaims(c) + username, ok := claims[identityKey].(string) + if !ok { + return nil + } + user, err := userRepo.GetUserByUsername(c.Request.Context(), username) + if err != nil { + return nil + } + return user + }, + Authenticator: func(c *gin.Context) (interface{}, error) { + provider := c.Value("auth_provider") + switch provider { + case nil: + var req signIn + if err := c.ShouldBindJSON(&req); err != nil { + return "", jwt.ErrMissingLoginValues + } + + // ctx := cache.WithCacheSkip(c.Request.Context(), true) + user, err := userRepo.GetUserByUsername(c.Request.Context(), req.Username) + if err != nil || user.Disabled { + return nil, jwt.ErrFailedAuthentication + } + err = Matches(user.Password, req.Password) + if err != nil { + if err != bcrypt.ErrMismatchedHashAndPassword { + logging.FromContext(c).Warnw("middleware.jwt.Authenticator found unknown error when matches password", "err", err) + } + return nil, jwt.ErrFailedAuthentication + } + return &uModel.User{ + ID: user.ID, + Username: user.Username, + Password: "", + Image: user.Image, + CreatedAt: user.CreatedAt, + UpdatedAt: user.UpdatedAt, + Disabled: user.Disabled, + CircleID: user.CircleID, + }, nil + case "3rdPartyAuth": + // we should only reach this stage if a handler mannually call authenticator with it's context: + + var authObject *uModel.User + v := c.Value("user_account") + authObject = v.(*uModel.User) + + return authObject, nil + + default: + return nil, jwt.ErrFailedAuthentication + } + }, + + Authorizator: func(data interface{}, c *gin.Context) bool { + + if _, ok := data.(*uModel.User); ok { + return true + } + return false + }, + Unauthorized: func(c *gin.Context, code int, message string) { + logging.FromContext(c).Info("middleware.jwt.Unauthorized", "code", code, "message", message) + c.JSON(code, gin.H{ + "code": code, + "message": message, + }) + }, + LoginResponse: func(c *gin.Context, code int, token string, expire time.Time) { + c.JSON(http.StatusOK, gin.H{ + "code": code, + "token": token, + "expire": expire, + }) + }, + TokenLookup: "header: Authorization", + TokenHeadName: "Bearer", + TimeFunc: time.Now, + }) +} diff --git a/internal/authorization/password.go b/internal/authorization/password.go new file mode 100644 index 0000000..00cd222 --- /dev/null +++ b/internal/authorization/password.go @@ -0,0 +1,60 @@ +package auth + +import ( + "crypto/rand" + "encoding/base64" + "math/big" + + "donetick.com/core/logging" + "github.com/gin-gonic/gin" + "golang.org/x/crypto/bcrypt" +) + +const chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;':,.<>?/~" + +func EncodePassword(password string) (string, error) { + bytes, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost) + if err != nil { + return "", err + } + return string(bytes), nil +} + +func Matches(hashedPassword, password string) error { + return bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password)) +} + +func GenerateRandomPassword(length int) string { + // Create a buffer to hold the random bytes. + buffer := make([]byte, length) + + // Compute the maximum index for the characters. + maxIndex := big.NewInt(int64(len(chars))) + + // Generate random bytes and use them to select characters from the set. + for i := 0; i < length; i++ { + randomIndex, _ := rand.Int(rand.Reader, maxIndex) + buffer[i] = chars[randomIndex.Int64()] + } + + return string(buffer) +} + +func GenerateEmailResetToken(c *gin.Context) (string, error) { + logger := logging.FromContext(c) + // Define the length of the token (in bytes). For example, 32 bytes will result in a 44-character base64-encoded token. + tokenLength := 32 + + // Generate a random byte slice. + tokenBytes := make([]byte, tokenLength) + _, err := rand.Read(tokenBytes) + if err != nil { + logger.Errorw("password.GenerateEmailResetToken failed to generate random bytes", "err", err) + return "", err + } + + // Encode the byte slice to a base64 string. + token := base64.URLEncoding.EncodeToString(tokenBytes) + + return token, nil +} diff --git a/internal/chore/handler.go b/internal/chore/handler.go new file mode 100644 index 0000000..bc90c4c --- /dev/null +++ b/internal/chore/handler.go @@ -0,0 +1,974 @@ +package chore + +import ( + "encoding/json" + "fmt" + "html" + "log" + "math" + "math/rand" + "strconv" + "strings" + "time" + + auth "donetick.com/core/internal/authorization" + chModel "donetick.com/core/internal/chore/model" + chRepo "donetick.com/core/internal/chore/repo" + cRepo "donetick.com/core/internal/circle/repo" + nRepo "donetick.com/core/internal/notifier/repo" + nps "donetick.com/core/internal/notifier/service" + telegram "donetick.com/core/internal/notifier/telegram" + tRepo "donetick.com/core/internal/thing/repo" + uModel "donetick.com/core/internal/user/model" + "donetick.com/core/logging" + jwt "github.com/appleboy/gin-jwt/v2" + "github.com/gin-gonic/gin" +) + +type ThingTrigger struct { + ID int `json:"thingID" binding:"required"` + TriggerState string `json:"triggerState" binding:"required"` + Condition string `json:"condition"` +} + +type ChoreReq struct { + Name string `json:"name" binding:"required"` + FrequencyType string `json:"frequencyType"` + ID int `json:"id"` + DueDate string `json:"dueDate"` + Assignees []chModel.ChoreAssignees `json:"assignees"` + AssignStrategy string `json:"assignStrategy" binding:"required"` + AssignedTo int `json:"assignedTo"` + IsRolling bool `json:"isRolling"` + IsActive bool `json:"isActive"` + Frequency int `json:"frequency"` + FrequencyMetadata *chModel.FrequencyMetadata `json:"frequencyMetadata"` + Notification bool `json:"notification"` + NotificationMetadata *chModel.NotificationMetadata `json:"notificationMetadata"` + Labels []string `json:"labels"` + ThingTrigger *ThingTrigger `json:"thingTrigger"` +} +type Handler struct { + choreRepo *chRepo.ChoreRepository + circleRepo *cRepo.CircleRepository + notifier *telegram.TelegramNotifier + nPlanner *nps.NotificationPlanner + nRepo *nRepo.NotificationRepository + tRepo *tRepo.ThingRepository +} + +func NewHandler(cr *chRepo.ChoreRepository, circleRepo *cRepo.CircleRepository, nt *telegram.TelegramNotifier, + np *nps.NotificationPlanner, nRepo *nRepo.NotificationRepository, tRepo *tRepo.ThingRepository) *Handler { + return &Handler{ + choreRepo: cr, + circleRepo: circleRepo, + notifier: nt, + nPlanner: np, + nRepo: nRepo, + tRepo: tRepo, + } +} + +func (h *Handler) getChores(c *gin.Context) { + u, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current circle", + }) + return + } + chores, err := h.choreRepo.GetChores(c, u.CircleID, u.ID) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting chores", + }) + return + } + + c.JSON(200, gin.H{ + "res": chores, + }) +} + +func (h *Handler) getChore(c *gin.Context) { + + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + + rawID := c.Param("id") + id, err := strconv.Atoi(rawID) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid ID", + }) + return + } + + chore, err := h.choreRepo.GetChore(c, id) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting chore", + }) + return + } + isAssignee := false + + for _, assignee := range chore.Assignees { + if assignee.UserID == currentUser.ID { + isAssignee = true + break + } + } + + if currentUser.ID != chore.CreatedBy && !isAssignee { + c.JSON(403, gin.H{ + "error": "You are not allowed to view this chore", + }) + return + } + + c.JSON(200, gin.H{ + "res": chore, + }) +} + +func (h *Handler) createChore(c *gin.Context) { + logger := logging.FromContext(c) + currentUser, ok := auth.CurrentUser(c) + + logger.Debug("Create chore", "currentUser", currentUser) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + // Validate chore: + var choreReq ChoreReq + if err := c.ShouldBindJSON(&choreReq); err != nil { + log.Print(err) + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + + circleUsers, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID) + for _, assignee := range choreReq.Assignees { + userFound := false + for _, circleUser := range circleUsers { + if assignee.UserID == circleUser.UserID { + userFound = true + + break + + } + } + if !userFound { + c.JSON(400, gin.H{ + "error": "Assignee not found in circle", + }) + return + } + + } + if choreReq.AssignedTo <= 0 && len(choreReq.Assignees) > 0 { + // if the assigned to field is not set, randomly assign the chore to one of the assignees + choreReq.AssignedTo = choreReq.Assignees[rand.Intn(len(choreReq.Assignees))].UserID + } + + var dueDate *time.Time + + if choreReq.DueDate != "" { + rawDueDate, err := time.Parse(time.RFC3339, choreReq.DueDate) + rawDueDate = rawDueDate.UTC() + dueDate = &rawDueDate + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid date", + }) + return + } + + } else { + c.JSON(400, gin.H{ + "error": "Due date is required", + }) + return + + } + + freqencyMetadataBytes, err := json.Marshal(choreReq.FrequencyMetadata) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error marshalling frequency metadata", + }) + return + } + stringFrequencyMetadata := string(freqencyMetadataBytes) + + notificationMetadataBytes, err := json.Marshal(choreReq.NotificationMetadata) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error marshalling notification metadata", + }) + return + } + stringNotificationMetadata := string(notificationMetadataBytes) + + var stringLabels *string + if len(choreReq.Labels) > 0 { + var escapedLabels []string + for _, label := range choreReq.Labels { + escapedLabels = append(escapedLabels, html.EscapeString(label)) + } + + labels := strings.Join(escapedLabels, ",") + stringLabels = &labels + } + createdChore := &chModel.Chore{ + + Name: choreReq.Name, + FrequencyType: choreReq.FrequencyType, + Frequency: choreReq.Frequency, + FrequencyMetadata: &stringFrequencyMetadata, + NextDueDate: dueDate, + AssignStrategy: choreReq.AssignStrategy, + AssignedTo: choreReq.AssignedTo, + IsRolling: choreReq.IsRolling, + UpdatedBy: currentUser.ID, + IsActive: true, + Notification: choreReq.Notification, + NotificationMetadata: &stringNotificationMetadata, + Labels: stringLabels, + CreatedBy: currentUser.ID, + CreatedAt: time.Now().UTC(), + CircleID: currentUser.CircleID, + } + id, err := h.choreRepo.CreateChore(c, createdChore) + createdChore.ID = id + + if err != nil { + c.JSON(500, gin.H{ + "error": "Error creating chore", + }) + return + } + + var choreAssignees []*chModel.ChoreAssignees + for _, assignee := range choreReq.Assignees { + choreAssignees = append(choreAssignees, &chModel.ChoreAssignees{ + ChoreID: id, + UserID: assignee.UserID, + }) + } + + if err := h.choreRepo.UpdateChoreAssignees(c, choreAssignees); err != nil { + c.JSON(500, gin.H{ + "error": "Error adding chore assignees", + }) + return + } + go func() { + h.nPlanner.GenerateNotifications(c, createdChore) + }() + shouldReturn := HandleThingAssociation(choreReq, h, c, currentUser) + if shouldReturn { + return + } + c.JSON(200, gin.H{ + "res": id, + }) +} + +func (h *Handler) editChore(c *gin.Context) { + // logger := logging.FromContext(c) + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + + var choreReq ChoreReq + if err := c.ShouldBindJSON(&choreReq); err != nil { + log.Print(err) + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + + circleUsers, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting circle users", + }) + return + } + + existedChoreAssignees, err := h.choreRepo.GetChoreAssignees(c, choreReq.ID) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting chore assignees", + }) + return + } + + var choreAssigneesToAdd []*chModel.ChoreAssignees + var choreAssigneesToDelete []*chModel.ChoreAssignees + + // filter assignees that not in the circle + for _, assignee := range choreReq.Assignees { + userFound := false + for _, circleUser := range circleUsers { + if assignee.UserID == circleUser.UserID { + userFound = true + break + } + } + if !userFound { + c.JSON(400, gin.H{ + "error": "Assignee not found in circle", + }) + return + } + userAlreadyAssignee := false + for _, existedChoreAssignee := range existedChoreAssignees { + if existedChoreAssignee.UserID == assignee.UserID { + userAlreadyAssignee = true + break + } + } + if !userAlreadyAssignee { + choreAssigneesToAdd = append(choreAssigneesToAdd, &chModel.ChoreAssignees{ + ChoreID: choreReq.ID, + UserID: assignee.UserID, + }) + } + } + + // remove assignees if they are not in the assignees list anymore + for _, existedChoreAssignee := range existedChoreAssignees { + userFound := false + for _, assignee := range choreReq.Assignees { + if existedChoreAssignee.UserID == assignee.UserID { + userFound = true + break + } + } + if !userFound { + choreAssigneesToDelete = append(choreAssigneesToDelete, existedChoreAssignee) + } + } + + var dueDate *time.Time + + if choreReq.DueDate != "" { + rawDueDate, err := time.Parse(time.RFC3339, choreReq.DueDate) + rawDueDate = rawDueDate.UTC() + dueDate = &rawDueDate + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid date", + }) + return + } + + } + + // validate assignedTo part of the assignees: + assigneeFound := false + for _, assignee := range choreReq.Assignees { + if assignee.UserID == choreReq.AssignedTo { + assigneeFound = true + break + } + } + if !assigneeFound { + c.JSON(400, gin.H{ + "error": "Assigned to not found in assignees", + }) + return + } + + if choreReq.AssignedTo <= 0 && len(choreReq.Assignees) > 0 { + // if the assigned to field is not set, randomly assign the chore to one of the assignees + choreReq.AssignedTo = choreReq.Assignees[rand.Intn(len(choreReq.Assignees))].UserID + } + oldChore, err := h.choreRepo.GetChore(c, choreReq.ID) + + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting chore", + }) + return + } + if currentUser.ID != oldChore.CreatedBy { + c.JSON(403, gin.H{ + "error": "You are not allowed to edit this chore", + }) + return + } + freqencyMetadataBytes, err := json.Marshal(choreReq.FrequencyMetadata) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error marshalling frequency metadata", + }) + return + } + + stringFrequencyMetadata := string(freqencyMetadataBytes) + + notificationMetadataBytes, err := json.Marshal(choreReq.NotificationMetadata) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error marshalling notification metadata", + }) + return + } + stringNotificationMetadata := string(notificationMetadataBytes) + + // escape special characters in labels and store them as a string : + var stringLabels *string + if len(choreReq.Labels) > 0 { + var escapedLabels []string + for _, label := range choreReq.Labels { + escapedLabels = append(escapedLabels, html.EscapeString(label)) + } + + labels := strings.Join(escapedLabels, ",") + stringLabels = &labels + } + updatedChore := &chModel.Chore{ + ID: choreReq.ID, + Name: choreReq.Name, + FrequencyType: choreReq.FrequencyType, + Frequency: choreReq.Frequency, + FrequencyMetadata: &stringFrequencyMetadata, + // Assignees: &assignees, + NextDueDate: dueDate, + AssignStrategy: choreReq.AssignStrategy, + AssignedTo: choreReq.AssignedTo, + IsRolling: choreReq.IsRolling, + IsActive: choreReq.IsActive, + Notification: choreReq.Notification, + NotificationMetadata: &stringNotificationMetadata, + Labels: stringLabels, + CircleID: oldChore.CircleID, + UpdatedBy: currentUser.ID, + CreatedBy: oldChore.CreatedBy, + CreatedAt: oldChore.CreatedAt, + } + if err := h.choreRepo.UpsertChore(c, updatedChore); err != nil { + c.JSON(500, gin.H{ + "error": "Error adding chore", + }) + return + } + if len(choreAssigneesToAdd) > 0 { + err = h.choreRepo.UpdateChoreAssignees(c, choreAssigneesToAdd) + + if err != nil { + c.JSON(500, gin.H{ + "error": "Error updating chore assignees", + }) + return + } + } + if len(choreAssigneesToDelete) > 0 { + err = h.choreRepo.DeleteChoreAssignees(c, choreAssigneesToDelete) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error deleting chore assignees", + }) + return + } + } + go func() { + h.nPlanner.GenerateNotifications(c, updatedChore) + }() + if oldChore.ThingChore.ThingID != 0 { + // TODO: Add check to see if dissociation is necessary + h.tRepo.DissociateThingWithChore(c, oldChore.ThingChore.ThingID, oldChore.ID) + + } + shouldReturn := HandleThingAssociation(choreReq, h, c, currentUser) + if shouldReturn { + return + } + + c.JSON(200, gin.H{ + "message": "Chore added successfully", + }) +} + +func HandleThingAssociation(choreReq ChoreReq, h *Handler, c *gin.Context, currentUser *uModel.User) bool { + if choreReq.ThingTrigger != nil { + thing, err := h.tRepo.GetThingByID(c, choreReq.ThingTrigger.ID) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting thing", + }) + return true + } + if thing.UserID != currentUser.ID { + c.JSON(403, gin.H{ + "error": "You are not allowed to trigger this thing", + }) + return true + } + if err := h.tRepo.AssociateThingWithChore(c, choreReq.ThingTrigger.ID, choreReq.ID, choreReq.ThingTrigger.TriggerState, choreReq.ThingTrigger.Condition); err != nil { + c.JSON(500, gin.H{ + "error": "Error associating thing with chore", + }) + return true + } + + } + return false +} + +func (h *Handler) deleteChore(c *gin.Context) { + // logger := logging.FromContext(c) + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + + rawID := c.Param("id") + id, err := strconv.Atoi(rawID) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid ID", + }) + return + } + // check if the user is the owner of the chore before deleting + if err := h.choreRepo.IsChoreOwner(c, id, currentUser.ID); err != nil { + c.JSON(403, gin.H{ + "error": "You are not allowed to delete this chore", + }) + return + } + + if err := h.choreRepo.DeleteChore(c, id); err != nil { + c.JSON(500, gin.H{ + "error": "Error deleting chore", + }) + return + } + h.nRepo.DeleteAllChoreNotifications(id) + c.JSON(200, gin.H{ + "message": "Chore deleted successfully", + }) +} + +// func (h *Handler) createChore(c *gin.Context) { +// logger := logging.FromContext(c) +// currentUser, ok := auth.CurrentUser(c) + +// logger.Debug("Create chore", "currentUser", currentUser) +// if !ok { +// c.JSON(500, gin.H{ +// "error": "Error getting current user", +// }) +// return +// } +// id, err := h.choreRepo.CreateChore(currentUser.ID, currentUser.CircleID) +// if err != nil { +// c.JSON(500, gin.H{ +// "error": "Error creating chore", +// }) +// return +// } + +// c.JSON(200, gin.H{ +// "res": id, +// }) +// } + +func (h *Handler) updateAssignee(c *gin.Context) { + rawID := c.Param("id") + id, err := strconv.Atoi(rawID) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid ID", + }) + return + } + type AssigneeReq struct { + AssignedTo int `json:"assignedTo" binding:"required"` + UpdatedBy int `json:"updatedBy" binding:"required"` + } + + var assigneeReq AssigneeReq + if err := c.ShouldBindJSON(&assigneeReq); err != nil { + log.Print(err) + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + chore, err := h.choreRepo.GetChore(c, id) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting chore", + }) + return + } + // confirm that the assignee is one of the assignees: + assigneeFound := false + for _, assignee := range chore.Assignees { + + if assignee.UserID == assigneeReq.AssignedTo { + assigneeFound = true + break + } + } + if !assigneeFound { + c.JSON(400, gin.H{ + "error": "Assignee not found in assignees", + }) + return + } + + chore.UpdatedBy = assigneeReq.UpdatedBy + chore.AssignedTo = assigneeReq.AssignedTo + if err := h.choreRepo.UpsertChore(c, chore); err != nil { + c.JSON(500, gin.H{ + "error": "Error updating assignee", + }) + return + } + + c.JSON(200, gin.H{ + "res": chore, + }) +} + +func (h *Handler) skipChore(c *gin.Context) { + rawID := c.Param("id") + id, err := strconv.Atoi(rawID) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid ID", + }) + return + } + + chore, err := h.choreRepo.GetChore(c, id) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting chore", + }) + return + } + newDueDate, err := scheduleNextDueDate(chore, chore.NextDueDate.UTC()) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error scheduling next due date", + }) + return + } + chore.NextDueDate = newDueDate + if err := h.choreRepo.UpsertChore(c, chore); err != nil { + c.JSON(500, gin.H{ + "error": "Error skipping chore", + }) + return + } + if err := h.choreRepo.UpsertChore(c, chore); err != nil { + c.JSON(500, gin.H{ + "error": "Error skipping chore", + }) + return + } + c.JSON(200, gin.H{ + "res": chore, + }) +} + +func (h *Handler) updateDueDate(c *gin.Context) { + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + + type DueDateReq struct { + DueDate string `json:"dueDate" binding:"required"` + } + + var dueDateReq DueDateReq + if err := c.ShouldBindJSON(&dueDateReq); err != nil { + log.Print(err) + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + + rawID := c.Param("id") + id, err := strconv.Atoi(rawID) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid ID", + }) + return + } + + rawDueDate, err := time.Parse(time.RFC3339, dueDateReq.DueDate) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid date", + }) + return + } + dueDate := rawDueDate.UTC() + chore, err := h.choreRepo.GetChore(c, id) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting chore", + }) + return + } + chore.NextDueDate = &dueDate + chore.UpdatedBy = currentUser.ID + if err := h.choreRepo.UpsertChore(c, chore); err != nil { + c.JSON(500, gin.H{ + "error": "Error updating due date", + }) + return + } + + c.JSON(200, gin.H{ + "res": chore, + }) +} +func (h *Handler) completeChore(c *gin.Context) { + type CompleteChoreReq struct { + Note string `json:"note"` + } + var req CompleteChoreReq + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + completeChoreID := c.Param("id") + var completedDate time.Time + rawCompletedDate := c.Query("completedDate") + if rawCompletedDate == "" { + completedDate = time.Now().UTC() + } else { + var err error + completedDate, err = time.Parse(time.RFC3339, rawCompletedDate) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid date", + }) + return + } + } + + var additionalNotes *string + _ = c.ShouldBind(&req) + + if req.Note != "" { + additionalNotes = &req.Note + } + + id, err := strconv.Atoi(completeChoreID) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid ID", + }) + return + } + chore, err := h.choreRepo.GetChore(c, id) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting chore", + }) + return + } + + nextDueDate, err := scheduleNextDueDate(chore, completedDate) + if err != nil { + log.Printf("Error scheduling next due date: %s", err) + c.JSON(500, gin.H{ + "error": "Error scheduling next due date", + }) + return + } + choreHistory, err := h.choreRepo.GetChoreHistory(c, chore.ID) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting chore history", + }) + return + } + + nextAssignedTo, err := checkNextAssignee(chore, choreHistory, currentUser.ID) + if err != nil { + log.Printf("Error checking next assignee: %s", err) + c.JSON(500, gin.H{ + "error": "Error checking next assignee", + }) + return + } + + if err := h.choreRepo.CompleteChore(c, chore, additionalNotes, currentUser.ID, nextDueDate, completedDate, nextAssignedTo); err != nil { + c.JSON(500, gin.H{ + "error": "Error completing chore", + }) + return + } + updatedChore, err := h.choreRepo.GetChore(c, id) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting chore", + }) + return + } + go func() { + h.notifier.SendChoreCompletion(c, chore, []*uModel.User{currentUser}) + h.nPlanner.GenerateNotifications(c, updatedChore) + }() + c.JSON(200, gin.H{ + "res": updatedChore, + }) +} + +func (h *Handler) GetChoreHistory(c *gin.Context) { + rawID := c.Param("id") + id, err := strconv.Atoi(rawID) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid ID", + }) + return + } + + choreHistory, err := h.choreRepo.GetChoreHistory(c, id) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting chore history", + }) + return + } + + c.JSON(200, gin.H{ + "res": choreHistory, + }) +} + +func checkNextAssignee(chore *chModel.Chore, choresHistory []*chModel.ChoreHistory, performerID int) (int, error) { + // copy the history to avoid modifying the original: + history := make([]*chModel.ChoreHistory, len(choresHistory)) + copy(history, choresHistory) + + assigneesMap := map[int]bool{} + for _, assignee := range chore.Assignees { + assigneesMap[assignee.UserID] = true + } + var nextAssignee int + if len(history) == 0 { + // if there is no history, just assume the current operation as the first + history = append(history, &chModel.ChoreHistory{ + AssignedTo: performerID, + }) + + } + + switch chore.AssignStrategy { + case "least_assigned": + // find the assignee with the least number of chores + assigneeChores := map[int]int{} + for _, performer := range chore.Assignees { + assigneeChores[performer.UserID] = 0 + } + for _, history := range history { + if ok := assigneesMap[history.AssignedTo]; !ok { + // calculate the number of chores assigned to each assignee + assigneeChores[history.AssignedTo]++ + } + } + + minChores := math.MaxInt64 + for assignee, numChores := range assigneeChores { + // if this is the first assignee or if the number of + // chores assigned to this assignee is less than the current minimum + if numChores < minChores { + minChores = numChores + // set the next assignee to this assignee + nextAssignee = assignee + } + } + case "least_completed": + // find the assignee who has completed the least number of chores + assigneeChores := map[int]int{} + for _, performer := range chore.Assignees { + assigneeChores[performer.UserID] = 0 + } + for _, history := range history { + // calculate the number of chores completed by each assignee + assigneeChores[history.CompletedBy]++ + } + + // max Int value + minChores := math.MaxInt64 + for assignee, numChores := range assigneeChores { + // if this is the first assignee or if the number of + // chores completed by this assignee is less than the current minimum + if numChores < minChores { + minChores = numChores + // set the next assignee to this assignee + nextAssignee = assignee + } + } + case "random": + nextAssignee = chore.Assignees[rand.Intn(len(chore.Assignees))].UserID + case "keep_last_assigned": + // keep the last assignee + nextAssignee = history[len(history)-1].AssignedTo + + default: + return chore.AssignedTo, fmt.Errorf("invalid assign strategy") + + } + return nextAssignee, nil +} + +func Routes(router *gin.Engine, h *Handler, auth *jwt.GinJWTMiddleware) { + + choresRoutes := router.Group("chores") + choresRoutes.Use(auth.MiddlewareFunc()) + { + choresRoutes.GET("/", h.getChores) + choresRoutes.PUT("/", h.editChore) + choresRoutes.POST("/", h.createChore) + choresRoutes.GET("/:id", h.getChore) + choresRoutes.GET("/:id/history", h.GetChoreHistory) + choresRoutes.POST("/:id/do", h.completeChore) + choresRoutes.POST("/:id/skip", h.skipChore) + choresRoutes.PUT("/:id/assignee", h.updateAssignee) + choresRoutes.PUT("/:id/dueDate", h.updateDueDate) + choresRoutes.DELETE("/:id", h.deleteChore) + } + +} diff --git a/internal/chore/model/model.go b/internal/chore/model/model.go new file mode 100644 index 0000000..4de7808 --- /dev/null +++ b/internal/chore/model/model.go @@ -0,0 +1,72 @@ +package model + +import ( + "time" + + tModel "donetick.com/core/internal/thing/model" +) + +type Chore struct { + ID int `json:"id" gorm:"primary_key"` + Name string `json:"name" gorm:"column:name"` // Chore description + FrequencyType string `json:"frequencyType" gorm:"column:frequency_type"` // "daily", "weekly", "monthly", "yearly", "adaptive",or "custom" + Frequency int `json:"frequency" gorm:"column:frequency"` // Number of days, weeks, months, or years between chores + FrequencyMetadata *string `json:"frequencyMetadata" gorm:"column:frequency_meta"` // Additional frequency information + NextDueDate *time.Time `json:"nextDueDate" gorm:"column:next_due_date;index"` // When the chore is due + IsRolling bool `json:"isRolling" gorm:"column:is_rolling"` // Whether the chore is rolling + AssignedTo int `json:"assignedTo" gorm:"column:assigned_to"` // Who the chore is assigned to + Assignees []ChoreAssignees `json:"assignees" gorm:"foreignkey:ChoreID;references:ID"` // Assignees of the chore + AssignStrategy string `json:"assignStrategy" gorm:"column:assign_strategy"` // How the chore is assigned + IsActive bool `json:"isActive" gorm:"column:is_active"` // Whether the chore is active + Notification bool `json:"notification" gorm:"column:notification"` // Whether the chore has notification + NotificationMetadata *string `json:"notificationMetadata" gorm:"column:notification_meta"` // Additional notification information + Labels *string `json:"labels" gorm:"column:labels"` // Labels for the chore + CircleID int `json:"circleId" gorm:"column:circle_id;index"` // The circle this chore is in + CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"` // When the chore was created + UpdatedAt time.Time `json:"updatedAt" gorm:"column:updated_at"` // When the chore was last updated + CreatedBy int `json:"createdBy" gorm:"column:created_by"` // Who created the chore + UpdatedBy int `json:"updatedBy" gorm:"column:updated_by"` // Who last updated the chore + ThingChore tModel.ThingChore `json:"thingChore" gorm:"foreignkey:chore_id;references:id;<-:false"` // ThingChore relationship +} +type ChoreAssignees struct { + ID int `json:"-" gorm:"primary_key"` + ChoreID int `json:"-" gorm:"column:chore_id;uniqueIndex:idx_chore_user"` // The chore this assignee is for + UserID int `json:"userId" gorm:"column:user_id;uniqueIndex:idx_chore_user"` // The user this assignee is for +} +type ChoreHistory struct { + ID int `json:"id" gorm:"primary_key"` // Unique identifier + ChoreID int `json:"choreId" gorm:"column:chore_id"` // The chore this history is for + CompletedAt time.Time `json:"completedAt" gorm:"column:completed_at"` // When the chore was completed + CompletedBy int `json:"completedBy" gorm:"column:completed_by"` // Who completed the chore + AssignedTo int `json:"assignedTo" gorm:"column:assigned_to"` // Who the chore was assigned to + Note *string `json:"notes" gorm:"column:notes"` // Notes about the chore + DueDate *time.Time `json:"dueDate" gorm:"column:due_date"` // When the chore was due +} + +type FrequencyMetadata struct { + Days []*string `json:"days,omitempty"` + Months []*string `json:"months,omitempty"` + Unit *string `json:"unit,omitempty"` +} + +type NotificationMetadata struct { + DueDate bool `json:"dueDate,omitempty"` + Completion bool `json:"completion,omitempty"` + Nagging bool `json:"nagging,omitempty"` + PreDue bool `json:"predue,omitempty"` +} + +type Tag struct { + ID int `json:"-" gorm:"primary_key"` + Name string `json:"name" gorm:"column:name;unique"` +} + +// type ChoreTag struct { +// ChoreID int `json:"choreId" gorm:"primaryKey;autoIncrement:false"` +// TagID int `json:"tagId" gorm:"primaryKey;autoIncrement:false"` +// } + +// type CircleTag struct { +// CircleID int `json:"circleId" gorm:"primaryKey;autoIncrement:false"` +// TagID int `json:"tagId" gorm:"primaryKey;autoIncrement:false"` +// } diff --git a/internal/chore/repo/repository.go b/internal/chore/repo/repository.go new file mode 100644 index 0000000..1ab0f0b --- /dev/null +++ b/internal/chore/repo/repository.go @@ -0,0 +1,216 @@ +package chore + +import ( + "context" + "fmt" + "time" + + config "donetick.com/core/config" + chModel "donetick.com/core/internal/chore/model" + "gorm.io/gorm" +) + +type ChoreRepository struct { + db *gorm.DB + dbType string +} + +func NewChoreRepository(db *gorm.DB, cfg *config.Config) *ChoreRepository { + return &ChoreRepository{db: db, dbType: cfg.Database.Type} +} + +func (r *ChoreRepository) UpsertChore(c context.Context, chore *chModel.Chore) error { + return r.db.WithContext(c).Model(&chore).Save(chore).Error +} + +func (r *ChoreRepository) UpdateChores(c context.Context, chores []*chModel.Chore) error { + return r.db.WithContext(c).Save(&chores).Error +} +func (r *ChoreRepository) CreateChore(c context.Context, chore *chModel.Chore) (int, error) { + if err := r.db.WithContext(c).Create(chore).Error; err != nil { + return 0, err + } + return chore.ID, nil +} + +func (r *ChoreRepository) GetChore(c context.Context, choreID int) (*chModel.Chore, error) { + var chore chModel.Chore + if err := r.db.Debug().WithContext(c).Model(&chModel.Chore{}).Preload("Assignees").Preload("ThingChore").First(&chore, choreID).Error; err != nil { + return nil, err + } + return &chore, nil +} + +func (r *ChoreRepository) GetChores(c context.Context, circleID int, userID int) ([]*chModel.Chore, error) { + var chores []*chModel.Chore + // if err := r.db.WithContext(c).Preload("Assignees").Where("is_active = ?", true).Order("next_due_date asc").Find(&chores, "circle_id = ?", circleID).Error; err != nil { + if err := r.db.WithContext(c).Preload("Assignees").Joins("left join chore_assignees on chores.id = chore_assignees.chore_id").Where("chores.circle_id = ? AND (chores.created_by = ? OR chore_assignees.user_id = ?)", circleID, userID, userID).Group("chores.id").Order("next_due_date asc").Find(&chores, "circle_id = ?", circleID).Error; err != nil { + return nil, err + } + return chores, nil +} +func (r *ChoreRepository) DeleteChore(c context.Context, id int) error { + r.db.WithContext(c).Where("chore_id = ?", id).Delete(&chModel.ChoreAssignees{}) + return r.db.WithContext(c).Delete(&chModel.Chore{}, id).Error +} + +func (r *ChoreRepository) SoftDelete(c context.Context, id int, userID int) error { + return r.db.WithContext(c).Model(&chModel.Chore{}).Where("id = ?", id).Where("created_by = ? ", userID).Update("is_active", false).Error + +} + +func (r *ChoreRepository) IsChoreOwner(c context.Context, choreID int, userID int) error { + var chore chModel.Chore + err := r.db.WithContext(c).Model(&chModel.Chore{}).Where("id = ? AND created_by = ?", choreID, userID).First(&chore).Error + return err +} + +// func (r *ChoreRepository) ListChores(circleID int) ([]*chModel.Chore, error) { +// var chores []*Chore +// if err := r.db.WithContext(c).Find(&chores).Where("is_active = ?", true).Order("next_due_date").Error; err != nil { +// return nil, err +// } +// return chores, nil +// } + +func (r *ChoreRepository) CompleteChore(c context.Context, chore *chModel.Chore, note *string, userID int, dueDate *time.Time, completedDate time.Time, nextAssignedTo int) error { + err := r.db.WithContext(c).Transaction(func(tx *gorm.DB) error { + ch := &chModel.ChoreHistory{ + ChoreID: chore.ID, + CompletedAt: completedDate, + CompletedBy: userID, + AssignedTo: chore.AssignedTo, + DueDate: chore.NextDueDate, + Note: note, + } + if err := tx.Create(ch).Error; err != nil { + return err + } + updates := map[string]interface{}{} + updates["next_due_date"] = dueDate + + if dueDate != nil { + updates["assigned_to"] = nextAssignedTo + } else { + updates["is_active"] = false + } + // Perform the update operation once, using the prepared updates map. + if err := tx.Model(&chModel.Chore{}).Where("id = ?", chore.ID).Updates(updates).Error; err != nil { + return err + } + + return nil + }) + return err +} + +func (r *ChoreRepository) GetChoreHistory(c context.Context, choreID int) ([]*chModel.ChoreHistory, error) { + var histories []*chModel.ChoreHistory + if err := r.db.WithContext(c).Where("chore_id = ?", choreID).Order("completed_at desc").Find(&histories).Error; err != nil { + return nil, err + } + return histories, nil +} + +func (r *ChoreRepository) UpdateChoreAssignees(c context.Context, assignees []*chModel.ChoreAssignees) error { + return r.db.WithContext(c).Save(&assignees).Error +} + +func (r *ChoreRepository) DeleteChoreAssignees(c context.Context, choreAssignees []*chModel.ChoreAssignees) error { + return r.db.WithContext(c).Delete(&choreAssignees).Error +} + +func (r *ChoreRepository) GetChoreAssignees(c context.Context, choreID int) ([]*chModel.ChoreAssignees, error) { + var assignees []*chModel.ChoreAssignees + if err := r.db.WithContext(c).Find(&assignees, "chore_id = ?", choreID).Error; err != nil { + return nil, err + } + return assignees, nil +} + +func (r *ChoreRepository) RemoveChoreAssigneeByCircleID(c context.Context, userID int, circleID int) error { + return r.db.WithContext(c).Where("user_id = ? AND chore_id IN (SELECT id FROM chores WHERE circle_id = ? and created_by != ?)", userID, circleID, userID).Delete(&chModel.ChoreAssignees{}).Error +} + +// func (r *ChoreRepository) getChoreDueToday(circleID int) ([]*chModel.Chore, error) { +// var chores []*Chore +// if err := r.db.WithContext(c).Where("next_due_date <= ?", time.Now().UTC()).Find(&chores).Error; err != nil { +// return nil, err +// } +// return chores, nil +// } + +func (r *ChoreRepository) GetAllActiveChores(c context.Context) ([]*chModel.Chore, error) { + var chores []*chModel.Chore + // query := r.db.WithContext(c).Table("chores").Joins("left join notifications n on n.chore_id = chores.id and n.scheduled_for < chores.next_due_date") + // if err := query.Where("chores.is_active = ? and chores.notification = ? and (n.is_sent = ? or n.is_sent is null)", true, true, false).Find(&chores).Error; err != nil { + // return nil, err + // } + return chores, nil +} + +func (r *ChoreRepository) GetChoresForNotification(c context.Context) ([]*chModel.Chore, error) { + var chores []*chModel.Chore + query := r.db.WithContext(c).Table("chores").Joins("left join notifications n on n.chore_id = chores.id and n.scheduled_for = chores.next_due_date and n.type = 1") + if err := query.Where("chores.is_active = ? and chores.notification = ? and n.id is null", true, true).Find(&chores).Error; err != nil { + return nil, err + } + return chores, nil +} + +// func (r *ChoreReposity) GetOverdueChoresForNotification(c context.Context, overdueDuration time.Duration, everyDuration time.Duration, untilDuration time.Duration) ([]*chModel.Chore, error) { +// var chores []*chModel.Chore +// query := r.db.Debug().WithContext(c).Table("chores").Select("chores.*, MAX(n.created_at) as max_notification_created_at").Joins("left join notifications n on n.chore_id = chores.id and n.scheduled_for = chores.next_due_date and n.type = 2") +// if err := query.Where("chores.is_active = ? and chores.notification = ? and chores.next_due_date < ? and chores.next_due_date > ?", true, true, time.Now().Add(overdueDuration).UTC(), time.Now().Add(untilDuration).UTC()).Where(readJSONBooleanField(r.dbType, "chores.notification_meta", "nagging")).Having("MAX(n.created_at) is null or MAX(n.created_at) < ?", time.Now().Add(everyDuration).UTC()).Group("chores.id").Find(&chores).Error; err != nil { +// return nil, err +// } +// return chores, nil +// } + +func (r *ChoreRepository) GetOverdueChoresForNotification(c context.Context, overdueFor time.Duration, everyDuration time.Duration, untilDuration time.Duration) ([]*chModel.Chore, error) { + var chores []*chModel.Chore + now := time.Now().UTC() + overdueTime := now.Add(-overdueFor) + everyTime := now.Add(-everyDuration) + untilTime := now.Add(-untilDuration) + + query := r.db.Debug().WithContext(c). + Table("chores"). + Select("chores.*, MAX(n.created_at) as max_notification_created_at"). + Joins("left join notifications n on n.chore_id = chores.id and n.type = 2"). + Where("chores.is_active = ? AND chores.notification = ? AND chores.next_due_date < ? AND chores.next_due_date > ?", true, true, overdueTime, untilTime). + Where(readJSONBooleanField(r.dbType, "chores.notification_meta", "nagging")). + Group("chores.id"). + Having("MAX(n.created_at) IS NULL OR MAX(n.created_at) < ?", everyTime) + + if err := query.Find(&chores).Error; err != nil { + return nil, err + } + + return chores, nil +} + +// a predue notfication is a notification send before the due date in 6 hours, 3 hours : +func (r *ChoreRepository) GetPreDueChoresForNotification(c context.Context, preDueDuration time.Duration, everyDuration time.Duration) ([]*chModel.Chore, error) { + var chores []*chModel.Chore + query := r.db.WithContext(c).Table("chores").Select("chores.*, MAX(n.created_at) as max_notification_created_at").Joins("left join notifications n on n.chore_id = chores.id and n.scheduled_for = chores.next_due_date and n.type = 3") + if err := query.Where("chores.is_active = ? and chores.notification = ? and chores.next_due_date > ? and chores.next_due_date < ?", true, true, time.Now().UTC(), time.Now().Add(everyDuration*2).UTC()).Where(readJSONBooleanField(r.dbType, "chores.notification_meta", "predue")).Having("MAX(n.created_at) is null or MAX(n.created_at) < ?", time.Now().Add(everyDuration).UTC()).Group("chores.id").Find(&chores).Error; err != nil { + return nil, err + } + return chores, nil +} + +func readJSONBooleanField(dbType string, columnName string, fieldName string) string { + if dbType == "postgres" { + return fmt.Sprintf("(%s::json->>'%s')::boolean", columnName, fieldName) + } + return fmt.Sprintf("JSON_EXTRACT(%s, '$.%s')", columnName, fieldName) +} + +func (r *ChoreRepository) SetDueDate(c context.Context, choreID int, dueDate time.Time) error { + return r.db.WithContext(c).Model(&chModel.Chore{}).Where("id = ?", choreID).Update("next_due_date", dueDate).Error +} + +func (r *ChoreRepository) SetDueDateIfNotExisted(c context.Context, choreID int, dueDate time.Time) error { + return r.db.WithContext(c).Model(&chModel.Chore{}).Where("id = ? and next_due_date is null", choreID).Update("next_due_date", dueDate).Error +} diff --git a/internal/chore/scheduler.go b/internal/chore/scheduler.go new file mode 100644 index 0000000..55cdf01 --- /dev/null +++ b/internal/chore/scheduler.go @@ -0,0 +1,145 @@ +package chore + +import ( + "encoding/json" + "fmt" + "math/rand" + "strings" + "time" + + chModel "donetick.com/core/internal/chore/model" +) + +func scheduleNextDueDate(chore *chModel.Chore, completedDate time.Time) (*time.Time, error) { + // if Chore is rolling then the next due date calculated from the completed date, otherwise it's calculated from the due date + var nextDueDate time.Time + var baseDate time.Time + var frequencyMetadata chModel.FrequencyMetadata + err := json.Unmarshal([]byte(*chore.FrequencyMetadata), &frequencyMetadata) + if err != nil { + return nil, fmt.Errorf("error unmarshalling frequency metadata") + } + if chore.FrequencyType == "once" { + return nil, nil + } + if chore.NextDueDate != nil { + // no due date set, use the current date + + baseDate = chore.NextDueDate.UTC() + } else { + baseDate = completedDate.UTC() + } + if chore.IsRolling && chore.NextDueDate.Before(completedDate) { + // we need to check if chore due date is before the completed date to handle this senario: + // if user trying to complete chore due in future (multiple time for insance) due date will be calculated + // from the last completed date and due date change only in seconds. + // this make sure that the due date is always in future if the chore is rolling + + baseDate = completedDate.UTC() + } + + if chore.FrequencyType == "daily" { + nextDueDate = baseDate.AddDate(0, 0, 1) + } else if chore.FrequencyType == "weekly" { + nextDueDate = baseDate.AddDate(0, 0, 7) + } else if chore.FrequencyType == "monthly" { + nextDueDate = baseDate.AddDate(0, 1, 0) + } else if chore.FrequencyType == "yearly" { + nextDueDate = baseDate.AddDate(1, 0, 0) + } else if chore.FrequencyType == "adaptive" { + // TODO: calculate next due date based on the history of the chore + // calculate the difference between the due date and now in days: + diff := completedDate.UTC().Sub(chore.NextDueDate.UTC()) + nextDueDate = completedDate.UTC().Add(diff) + } else if chore.FrequencyType == "once" { + // if the chore is a one-time chore, then the next due date is nil + } else if chore.FrequencyType == "interval" { + // calculate the difference between the due date and now in days: + if *frequencyMetadata.Unit == "hours" { + nextDueDate = baseDate.UTC().Add(time.Hour * time.Duration(chore.Frequency)) + } else if *frequencyMetadata.Unit == "days" { + nextDueDate = baseDate.UTC().AddDate(0, 0, chore.Frequency) + } else if *frequencyMetadata.Unit == "weeks" { + nextDueDate = baseDate.UTC().AddDate(0, 0, chore.Frequency*7) + } else if *frequencyMetadata.Unit == "months" { + nextDueDate = baseDate.UTC().AddDate(0, chore.Frequency, 0) + } else if *frequencyMetadata.Unit == "years" { + nextDueDate = baseDate.UTC().AddDate(chore.Frequency, 0, 0) + } else { + + return nil, fmt.Errorf("invalid frequency unit, cannot calculate next due date") + } + } else if chore.FrequencyType == "days_of_the_week" { + // TODO : this logic is bad, need to be refactored and be better. + // coding at night is almost always bad idea. + // calculate the difference between the due date and now in days: + var frequencyMetadata chModel.FrequencyMetadata + err := json.Unmarshal([]byte(*chore.FrequencyMetadata), &frequencyMetadata) + if err != nil { + + return nil, fmt.Errorf("error unmarshalling frequency metadata") + } + //we can only assign to days of the week that part of the frequency metadata.days + //it's array of days of the week, for example ["monday", "tuesday", "wednesday"] + + // we need to find the next day of the week in the frequency metadata.days that we can schedule + // if this the last or there is only one. will use same otherwise find the next one: + + // find the index of the chore day in the frequency metadata.days + // loop for next 7 days from the base, if the day in the frequency metadata.days then we can schedule it: + for i := 1; i <= 7; i++ { + nextDueDate = baseDate.AddDate(0, 0, i) + nextDay := strings.ToLower(nextDueDate.Weekday().String()) + for _, day := range frequencyMetadata.Days { + if strings.ToLower(*day) == nextDay { + nextDate := nextDueDate.UTC() + return &nextDate, nil + } + } + } + } else if chore.FrequencyType == "day_of_the_month" { + var frequencyMetadata chModel.FrequencyMetadata + err := json.Unmarshal([]byte(*chore.FrequencyMetadata), &frequencyMetadata) + if err != nil { + + return nil, fmt.Errorf("error unmarshalling frequency metadata") + } + + for i := 1; i <= 12; i++ { + nextDueDate = baseDate.AddDate(0, i, 0) + // set the date to the first day of the month: + nextDueDate = time.Date(nextDueDate.Year(), nextDueDate.Month(), chore.Frequency, nextDueDate.Hour(), nextDueDate.Minute(), 0, 0, nextDueDate.Location()) + nextMonth := strings.ToLower(nextDueDate.Month().String()) + for _, month := range frequencyMetadata.Months { + if *month == nextMonth { + nextDate := nextDueDate.UTC() + return &nextDate, nil + } + } + } + } else if chore.FrequencyType == "no_repeat" { + return nil, nil + } else if chore.FrequencyType == "trigger" { + // if the chore is a trigger chore, then the next due date is nil + return nil, nil + } else { + return nil, fmt.Errorf("invalid frequency type, cannot calculate next due date") + } + return &nextDueDate, nil + +} + +func RemoveAssigneeAndReassign(chore *chModel.Chore, userID int) { + for i, assignee := range chore.Assignees { + if assignee.UserID == userID { + chore.Assignees = append(chore.Assignees[:i], chore.Assignees[i+1:]...) + break + } + } + if len(chore.Assignees) == 0 { + chore.AssignedTo = chore.CreatedBy + } else { + chore.AssignedTo = chore.Assignees[rand.Intn(len(chore.Assignees))].UserID + } + chore.UpdatedAt = time.Now() +} diff --git a/internal/circle/handler.go b/internal/circle/handler.go new file mode 100644 index 0000000..c15d322 --- /dev/null +++ b/internal/circle/handler.go @@ -0,0 +1,442 @@ +package circle + +import ( + "log" + + "strconv" + "time" + + auth "donetick.com/core/internal/authorization" + "donetick.com/core/internal/chore" + chRepo "donetick.com/core/internal/chore/repo" + cModel "donetick.com/core/internal/circle/model" + cRepo "donetick.com/core/internal/circle/repo" + uModel "donetick.com/core/internal/user/model" + uRepo "donetick.com/core/internal/user/repo" + "donetick.com/core/logging" + jwt "github.com/appleboy/gin-jwt/v2" + "github.com/gin-gonic/gin" +) + +type Handler struct { + circleRepo *cRepo.CircleRepository + userRepo *uRepo.UserRepository + choreRepo *chRepo.ChoreRepository +} + +func NewHandler(cr *cRepo.CircleRepository, ur *uRepo.UserRepository, c *chRepo.ChoreRepository) *Handler { + return &Handler{ + circleRepo: cr, + userRepo: ur, + choreRepo: c, + } +} + +func (h *Handler) GetCircleMembers(c *gin.Context) { + // Get the circle ID from the JWT + log := logging.FromContext(c) + currentUser, ok := auth.CurrentUser(c) + if !ok { + log.Error("Error getting current user") + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + + // Get all the members of the circle + members, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID) + if err != nil { + log.Error("Error getting circle members:", err) + c.JSON(500, gin.H{ + "error": "Error getting circle members", + }) + return + } + + c.JSON(200, gin.H{ + "res": members, + }) +} + +func (h *Handler) JoinCircle(c *gin.Context) { + // Get the circle ID from the JWT + log := logging.FromContext(c) + log.Debug("handlder.go: JoinCircle") + currentUser, ok := auth.CurrentUser(c) + + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + + requestedCircleID := c.Query("invite_code") + if requestedCircleID == "" { + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + + circle, err := h.circleRepo.GetCircleByInviteCode(c, requestedCircleID) + + if circle.ID == currentUser.CircleID { + c.JSON(409, gin.H{ + "error": "You are already a member of this circle", + }) + return + } + + // Add the user to the circle + err = h.circleRepo.AddUserToCircle(c, &cModel.UserCircle{ + CircleID: circle.ID, + UserID: currentUser.ID, + Role: "member", + IsActive: false, + }) + + if err != nil { + log.Error("Error adding user to circle:", err) + c.JSON(500, gin.H{ + "error": "Error adding user to circle", + }) + return + } + + c.JSON(200, gin.H{ + "res": "User Requested to join circle successfully", + }) +} + +func (h *Handler) LeaveCircle(c *gin.Context) { + log := logging.FromContext(c) + log.Debug("handler.go: LeaveCircle") + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + rawCircleID := c.Query("circle_id") + circleID, err := strconv.Atoi(rawCircleID) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + + orginalCircleID, err := h.circleRepo.GetUserOriginalCircle(c, currentUser.ID) + if err != nil { + log.Error("Error getting user original circle:", err) + c.JSON(500, gin.H{ + "error": "Error getting user original circle", + }) + return + } + + // START : HANDLE USER LEAVING CIRCLE + // bulk update chores: + if err := handleUserLeavingCircle(h, c, currentUser, orginalCircleID); err != nil { + log.Error("Error handling user leaving circle:", err) + c.JSON(500, gin.H{ + "error": "Error handling user leaving circle", + }) + return + } + + // END: HANDLE USER LEAVING CIRCLE + + err = h.circleRepo.LeaveCircleByUserID(c, circleID, currentUser.ID) + if err != nil { + log.Error("Error leaving circle:", err) + c.JSON(500, gin.H{ + "error": "Error leaving circle", + }) + return + } + + if err := h.userRepo.UpdateUserCircle(c, currentUser.ID, orginalCircleID); err != nil { + log.Error("Error updating user circle:", err) + c.JSON(500, gin.H{ + "error": "Error updating user circle", + }) + return + } + c.JSON(200, gin.H{ + "res": "User left circle successfully", + }) +} + +func handleUserLeavingCircle(h *Handler, c *gin.Context, leavingUser *uModel.User, orginalCircleID int) error { + userAssignedCircleChores, err := h.choreRepo.GetChores(c, leavingUser.CircleID, leavingUser.ID) + if err != nil { + return err + } + for _, ch := range userAssignedCircleChores { + + if ch.CreatedBy == leavingUser.ID && ch.AssignedTo != leavingUser.ID { + ch.AssignedTo = leavingUser.ID + ch.UpdatedAt = time.Now() + ch.UpdatedBy = leavingUser.ID + ch.CircleID = orginalCircleID + } else if ch.CreatedBy != leavingUser.ID && ch.AssignedTo == leavingUser.ID { + chore.RemoveAssigneeAndReassign(ch, leavingUser.ID) + } + + } + + h.choreRepo.UpdateChores(c, userAssignedCircleChores) + h.choreRepo.RemoveChoreAssigneeByCircleID(c, leavingUser.ID, leavingUser.CircleID) + return nil +} + +func (h *Handler) DeleteCircleMember(c *gin.Context) { + log := logging.FromContext(c) + log.Debug("handler.go: DeleteCircleMember") + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + rawCircleID := c.Param("id") + circleID, err := strconv.Atoi(rawCircleID) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + rawMemeberIDToDeleted := c.Query("member_id") + memberIDToDeleted, err := strconv.Atoi(rawMemeberIDToDeleted) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + admins, err := h.circleRepo.GetCircleAdmins(c, circleID) + if err != nil { + log.Error("Error getting circle admins:", err) + c.JSON(500, gin.H{ + "error": "Error getting circle admins", + }) + return + } + isAdmin := false + for _, admin := range admins { + if admin.UserID == currentUser.ID { + isAdmin = true + break + } + } + if !isAdmin { + c.JSON(403, gin.H{ + "error": "You are not an admin of this circle", + }) + return + } + orginalCircleID, err := h.circleRepo.GetUserOriginalCircle(c, memberIDToDeleted) + if handleUserLeavingCircle(h, c, &uModel.User{ID: memberIDToDeleted, CircleID: circleID}, orginalCircleID) != nil { + log.Error("Error handling user leaving circle:", err) + c.JSON(500, gin.H{ + "error": "Error handling user leaving circle", + }) + return + } + + err = h.circleRepo.DeleteMemberByID(c, circleID, memberIDToDeleted) + if err != nil { + log.Error("Error deleting circle member:", err) + c.JSON(500, gin.H{ + "error": "Error deleting circle member", + }) + return + } + c.JSON(200, gin.H{ + "res": "User deleted from circle successfully", + }) +} + +func (h *Handler) GetUserCircles(c *gin.Context) { + log := logging.FromContext(c) + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + + circles, err := h.circleRepo.GetUserCircles(c, currentUser.ID) + if err != nil { + log.Error("Error getting user circles:", err) + c.JSON(500, gin.H{ + "error": "Error getting user circles", + }) + return + } + + c.JSON(200, gin.H{ + "res": circles, + }) +} + +func (h *Handler) GetPendingCircleMembers(c *gin.Context) { + log := logging.FromContext(c) + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + + currentMemebers, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID) + if err != nil { + log.Error("Error getting circle members:", err) + c.JSON(500, gin.H{ + "error": "Error getting circle members", + }) + return + } + + // confirm that the current user is an admin: + isAdmin := false + for _, member := range currentMemebers { + if member.UserID == currentUser.ID && member.Role == "admin" { + isAdmin = true + break + } + } + if !isAdmin { + c.JSON(403, gin.H{ + "error": "You are not an admin of this circle", + }) + return + } + + members, err := h.circleRepo.GetPendingJoinRequests(c, currentUser.CircleID) + if err != nil { + log.Error("Error getting pending circle members:", err) + c.JSON(500, gin.H{ + "error": "Error getting pending circle members", + }) + return + } + + c.JSON(200, gin.H{ + "res": members, + }) +} + +func (h *Handler) AcceptJoinRequest(c *gin.Context) { + log := logging.FromContext(c) + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + + rawRequestID := c.Query("requestId") + requestID, err := strconv.Atoi(rawRequestID) + if err != nil { + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + + currentMemebers, err := h.circleRepo.GetCircleUsers(c, currentUser.CircleID) + if err != nil { + log.Error("Error getting circle members:", err) + c.JSON(500, gin.H{ + "error": "Error getting circle members", + }) + return + } + + // confirm that the current user is an admin: + isAdmin := false + for _, member := range currentMemebers { + if member.UserID == currentUser.ID && member.Role == "admin" { + isAdmin = true + break + } + } + if !isAdmin { + c.JSON(403, gin.H{ + "error": "You are not an admin of this circle", + }) + return + } + pendingRequests, err := h.circleRepo.GetPendingJoinRequests(c, currentUser.CircleID) + if err != nil { + log.Error("Error getting pending circle members:", err) + c.JSON(500, gin.H{ + "error": "Error getting pending circle members", + }) + return + } + isActiveRequest := false + var requestedCircle *cModel.UserCircleDetail + for _, request := range pendingRequests { + if request.ID == requestID { + requestedCircle = request + isActiveRequest = true + break + } + } + if !isActiveRequest { + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + + err = h.circleRepo.AcceptJoinRequest(c, currentUser.CircleID, requestID) + if err != nil { + log.Error("Error accepting join request:", err) + c.JSON(500, gin.H{ + "error": "Error accepting join request", + }) + return + } + + if err := h.userRepo.UpdateUserCircle(c, requestedCircle.UserID, currentUser.CircleID); err != nil { + log.Error("Error updating user circle:", err) + c.JSON(500, gin.H{ + "error": "Error updating user circle", + }) + return + } + + c.JSON(200, gin.H{ + "res": "Join request accepted successfully", + }) +} + +func Routes(router *gin.Engine, h *Handler, auth *jwt.GinJWTMiddleware) { + log.Println("Registering routes") + + circleRoutes := router.Group("circles") + circleRoutes.Use(auth.MiddlewareFunc()) + { + circleRoutes.GET("/members", h.GetCircleMembers) + circleRoutes.GET("/members/requests", h.GetPendingCircleMembers) + circleRoutes.PUT("/members/requests/accept", h.AcceptJoinRequest) + circleRoutes.GET("/", h.GetUserCircles) + circleRoutes.POST("/join", h.JoinCircle) + circleRoutes.DELETE("/leave", h.LeaveCircle) + circleRoutes.DELETE("/:id/members/delete", h.DeleteCircleMember) + + } + +} diff --git a/internal/circle/model/model.go b/internal/circle/model/model.go new file mode 100644 index 0000000..bf26b34 --- /dev/null +++ b/internal/circle/model/model.go @@ -0,0 +1,35 @@ +package circle + +import "time" + +type Circle struct { + ID int `json:"id" gorm:"primary_key"` // Unique identifier + Name string `json:"name" gorm:"column:name"` // Full name + CreatedBy int `json:"created_by" gorm:"column:created_by"` // Created by + CreatedAt time.Time `json:"created_at" gorm:"column:created_at"` // Created at + UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"` // Updated at + InviteCode string `json:"invite_code" gorm:"column:invite_code"` // Invite code + Disabled bool `json:"disabled" gorm:"column:disabled"` // Disabled +} + +type CircleDetail struct { + Circle + UserRole string `json:"userRole" gorm:"column:role"` +} + +type UserCircle struct { + ID int `json:"id" gorm:"primary_key"` // Unique identifier + UserID int `json:"userId" gorm:"column:user_id"` // User ID + CircleID int `json:"circleId" gorm:"column:circle_id"` // Circle ID + Role string `json:"role" gorm:"column:role"` // Role + IsActive bool `json:"isActive" gorm:"column:is_active;default:false"` + CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"` // Created at + UpdatedAt time.Time `json:"updatedAt" gorm:"column:updated_at"` // Updated at +} + +type UserCircleDetail struct { + UserCircle + Username string `json:"username" gorm:"column:username"` + DisplayName string `json:"displayName" gorm:"column:display_name"` + ChatID int `json:"chatID" gorm:"column:chat_id"` +} diff --git a/internal/circle/repo/repository.go b/internal/circle/repo/repository.go new file mode 100644 index 0000000..712cc99 --- /dev/null +++ b/internal/circle/repo/repository.go @@ -0,0 +1,117 @@ +package repo + +import ( + "context" + + cModel "donetick.com/core/internal/circle/model" + "gorm.io/gorm" +) + +type ICircleRepository interface { + CreateCircle(circle *cModel.Circle) error + AddUserToCircle(circleUser *cModel.UserCircle) error + GetCircleUsers(circleID int) ([]*cModel.UserCircle, error) + GetUserCircles(userID int) ([]*cModel.Circle, error) + DeleteUserFromCircle(circleID, userID int) error + ChangeUserRole(circleID, userID int, role string) error + GetCircleByInviteCode(inviteCode string) (*cModel.Circle, error) + GetCircleByID(circleID int) (*cModel.Circle, error) +} + +type CircleRepository struct { + db *gorm.DB +} + +func NewCircleRepository(db *gorm.DB) *CircleRepository { + return &CircleRepository{db} +} + +func (r *CircleRepository) CreateCircle(c context.Context, circle *cModel.Circle) (*cModel.Circle, error) { + if err := r.db.WithContext(c).Save(&circle).Error; err != nil { + return nil, err + } + return circle, nil + +} + +func (r *CircleRepository) AddUserToCircle(c context.Context, circleUser *cModel.UserCircle) error { + return r.db.WithContext(c).Save(circleUser).Error +} + +func (r *CircleRepository) GetCircleUsers(c context.Context, circleID int) ([]*cModel.UserCircleDetail, error) { + var circleUsers []*cModel.UserCircleDetail + // join user table to get user details like username and display name: + if err := r.db.WithContext(c).Raw("SELECT * FROM user_circles LEFT JOIN users on users.id = user_circles.user_id WHERE user_circles.circle_id = ?", circleID).Scan(&circleUsers).Error; err != nil { + return nil, err + } + return circleUsers, nil +} + +func (r *CircleRepository) GetPendingJoinRequests(c context.Context, circleID int) ([]*cModel.UserCircleDetail, error) { + var pendingRequests []*cModel.UserCircleDetail + if err := r.db.WithContext(c).Raw("SELECT *, user_circles.id as id FROM user_circles LEFT JOIN users on users.id = user_circles.user_id WHERE user_circles.circle_id = ? AND user_circles.is_active = false", circleID).Scan(&pendingRequests).Error; err != nil { + return nil, err + } + return pendingRequests, nil +} + +func (r *CircleRepository) AcceptJoinRequest(c context.Context, circleID, requestID int) error { + + return r.db.WithContext(c).Model(&cModel.UserCircle{}).Where("circle_id = ? AND id = ?", circleID, requestID).Update("is_active", true).Error +} + +func (r *CircleRepository) GetUserCircles(c context.Context, userID int) ([]*cModel.CircleDetail, error) { + var circles []*cModel.CircleDetail + if err := r.db.WithContext(c).Raw("SELECT circles.*, user_circles.role as role, user_circles.created_at uc_created_at FROM circles Left JOIN user_circles on circles.id = user_circles.circle_id WHERE user_circles.user_id = ? ORDER BY uc_created_at desc", userID).Scan(&circles).Error; err != nil { + return nil, err + } + return circles, nil +} + +func (r *CircleRepository) DeleteUserFromCircle(c context.Context, circleID, userID int) error { + return r.db.WithContext(c).Where("circle_id = ? AND user_id = ?", circleID, userID).Delete(&cModel.UserCircle{}).Error +} + +func (r *CircleRepository) ChangeUserRole(c context.Context, circleID, userID int, role int) error { + return r.db.WithContext(c).Model(&cModel.UserCircle{}).Where("circle_id = ? AND user_id = ?", circleID, userID).Update("role", role).Error +} + +func (r *CircleRepository) GetCircleByInviteCode(c context.Context, inviteCode string) (*cModel.Circle, error) { + var circle cModel.Circle + if err := r.db.WithContext(c).Where("invite_code = ?", inviteCode).First(&circle).Error; err != nil { + return nil, err + } + return &circle, nil +} + +func (r *CircleRepository) GetCircleByID(c context.Context, circleID int) (*cModel.Circle, error) { + var circle cModel.Circle + if err := r.db.WithContext(c).First(&circle, circleID).Error; err != nil { + return nil, err + } + return &circle, nil +} + +func (r *CircleRepository) LeaveCircleByUserID(c context.Context, circleID, userID int) error { + return r.db.WithContext(c).Where("circle_id = ? AND user_id = ? AND role != 'admin'", circleID, userID).Delete(&cModel.UserCircle{}).Error +} + +func (r *CircleRepository) GetUserOriginalCircle(c context.Context, userID int) (int, error) { + var circleID int + if err := r.db.WithContext(c).Raw("SELECT circle_id FROM user_circles WHERE user_id = ? AND role = 'admin'", userID).Scan(&circleID).Error; err != nil { + return 0, err + } + return circleID, nil +} + +func (r *CircleRepository) DeleteMemberByID(c context.Context, circleID, userID int) error { + return r.db.WithContext(c).Where("circle_id = ? AND user_id = ?", circleID, userID).Delete(&cModel.UserCircle{}).Error +} + +func (r *CircleRepository) GetCircleAdmins(c context.Context, circleID int) ([]*cModel.UserCircleDetail, error) { + var circleAdmins []*cModel.UserCircleDetail + if err := r.db.WithContext(c).Raw("SELECT * FROM user_circles LEFT JOIN users on users.id = user_circles.user_id WHERE user_circles.circle_id = ? AND user_circles.role = 'admin'", circleID).Scan(&circleAdmins).Error; err != nil { + return nil, err + } + return circleAdmins, nil +} diff --git a/internal/database/database.go b/internal/database/database.go new file mode 100644 index 0000000..8fc8a68 --- /dev/null +++ b/internal/database/database.go @@ -0,0 +1,44 @@ +package database + +import ( + "fmt" + "time" + + "gorm.io/driver/postgres" + "gorm.io/driver/sqlite" // Sqlite driver based on CGO + "gorm.io/gorm/logger" + + // "github.com/glebarez/sqlite" // Pure go SQLite driver, checkout https://github.com/glebarez/sqlite for details + "donetick.com/core/config" + "donetick.com/core/logging" + "gorm.io/gorm" +) + +func NewDatabase(cfg *config.Config) (*gorm.DB, error) { + var db *gorm.DB + var err error + switch cfg.Database.Type { + case "postgres": + dsn := fmt.Sprintf("host=%s port=%v user=%s password=%s dbname=%s sslmode=disable TimeZone=Asia/Shanghai", cfg.Database.Host, cfg.Database.Port, cfg.Database.User, cfg.Database.Password, cfg.Database.Name) + for i := 0; i <= 30; i++ { + db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{ + Logger: logger.Default.LogMode(logger.Info), + }) + if err == nil { + break + } + logging.DefaultLogger().Warnf("failed to open database: %v", err) + time.Sleep(500 * time.Millisecond) + } + + default: + + db, err = gorm.Open(sqlite.Open("donetick.db"), &gorm.Config{}) + + } + + if err != nil { + return nil, err + } + return db, nil +} diff --git a/internal/email/sender.go b/internal/email/sender.go new file mode 100644 index 0000000..540e54a --- /dev/null +++ b/internal/email/sender.go @@ -0,0 +1,509 @@ +package email + +import ( + "context" + "encoding/base64" + "fmt" + "strings" + + "donetick.com/core/config" + gomail "gopkg.in/gomail.v2" +) + +type EmailSender struct { + client *gomail.Dialer + appHost string +} + +func NewEmailSender(conf *config.Config) *EmailSender { + + client := gomail.NewDialer(conf.EmailConfig.Host, conf.EmailConfig.Port, conf.EmailConfig.Email, conf.EmailConfig.Key) + + // format conf.EmailConfig.Host and port : + + // auth := smtp.PlainAuth("", conf.EmailConfig.Email, conf.EmailConfig.Password, host) + return &EmailSender{ + + client: client, + appHost: conf.EmailConfig.AppHost, + } +} + +func (es *EmailSender) SendVerificationEmail(to, code string) error { + // msg := []byte(fmt.Sprintf("To: %s\r\nSubject: %s\r\n\r\n%s\r\n", to, subject, body)) + msg := gomail.NewMessage() + msg.SetHeader("From", "no-reply@donetick.com") + msg.SetHeader("To", to) + msg.SetHeader("Subject", "Welcome to Donetick! Verifiy you email") + // text/html for a html email + htmlBody := ` + <!-- + ******************************************************** + * This email was built using Tabular. + * Create emails, that look perfect in every inbox. + * For more information, visit https://tabular.email + ******************************************************** + --> + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" lang="en"><head> + <title></title> + <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> + <!--[if !mso]><!--> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <!--<![endif]--> + <meta name="x-apple-disable-message-reformatting" content=""> + <meta content="target-densitydpi=device-dpi" name="viewport"> + <meta content="true" name="HandheldFriendly"> + <meta content="width=device-width" name="viewport"> + <meta name="format-detection" content="telephone=no, date=no, address=no, email=no, url=no"> + <style type="text/css"> + table { + border-collapse: separate; + table-layout: fixed; + mso-table-lspace: 0pt; + mso-table-rspace: 0pt + } + table td { + border-collapse: collapse + } + .ExternalClass { + width: 100% + } + .ExternalClass, + .ExternalClass p, + .ExternalClass span, + .ExternalClass font, + .ExternalClass td, + .ExternalClass div { + line-height: 100% + } + body, a, li, p, h1, h2, h3 { + -ms-text-size-adjust: 100%; + -webkit-text-size-adjust: 100%; + } + html { + -webkit-text-size-adjust: none !important + } + body, #innerTable { + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale + } + #innerTable img+div { + display: none; + display: none !important + } + img { + Margin: 0; + padding: 0; + -ms-interpolation-mode: bicubic + } + h1, h2, h3, p, a { + line-height: 1; + overflow-wrap: normal; + white-space: normal; + word-break: break-word + } + a { + text-decoration: none + } + h1, h2, h3, p { + min-width: 100%!important; + width: 100%!important; + max-width: 100%!important; + display: inline-block!important; + border: 0; + padding: 0; + margin: 0 + } + a[x-apple-data-detectors] { + color: inherit !important; + text-decoration: none !important; + font-size: inherit !important; + font-family: inherit !important; + font-weight: inherit !important; + line-height: inherit !important + } + a[href^="mailto"], + a[href^="tel"], + a[href^="sms"] { + color: inherit; + text-decoration: none + } + @media (min-width: 481px) { + .hd { display: none!important } + } + @media (max-width: 480px) { + .hm { display: none!important } + } + [style*="Inter Tight"] {font-family: 'Inter Tight', BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif !important;} [style*="Albert Sans"] {font-family: 'Albert Sans', BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif !important;} + @media only screen and (min-width: 481px) {.t20{width:720px!important}.t27{padding:40px 60px 50px!important}.t29{padding:40px 60px 50px!important;width:680px!important}.t43{width:600px!important}.t53,.t61{width:580px!important}.t65{width:600px!important}.t78{padding-left:0!important;padding-right:0!important}.t80{padding-left:0!important;padding-right:0!important;width:400px!important}.t84,.t94{width:600px!important}} + </style> + <style type="text/css" media="screen and (min-width:481px)">.moz-text-html .t20{width:720px!important}.moz-text-html .t27{padding:40px 60px 50px!important}.moz-text-html .t29{padding:40px 60px 50px!important;width:680px!important}.moz-text-html .t43{width:600px!important}.moz-text-html .t53,.moz-text-html .t61{width:580px!important}.moz-text-html .t65{width:600px!important}.moz-text-html .t78{padding-left:0!important;padding-right:0!important}.moz-text-html .t80{padding-left:0!important;padding-right:0!important;width:400px!important}.moz-text-html .t84,.moz-text-html .t94{width:600px!important}</style> + <!--[if !mso]><!--> + <link href="https://fonts.googleapis.com/css2?family=Inter+Tight:wght@400;600&family=Albert+Sans:wght@800&display=swap" rel="stylesheet" type="text/css"> + <!--<![endif]--> + <!--[if mso]> + <style type="text/css"> + td.t20{width:800px !important}td.t27{padding:40px 60px 50px !important}td.t29{padding:40px 60px 50px !important;width:800px !important}td.t43,td.t53{width:600px !important}td.t61{width:580px !important}td.t65{width:600px !important}td.t78,td.t80{padding-left:0 !important;padding-right:0 !important}td.t84,td.t94{width:600px !important} + </style> + <![endif]--> + <!--[if mso]> + <xml> + <o:OfficeDocumentSettings> + <o:AllowPNG/> + <o:PixelsPerInch>96</o:PixelsPerInch> + </o:OfficeDocumentSettings> + </xml> + <![endif]--> + </head> + <body class="t0" style="min-width:100%;Marg + if you did not sign up with Donetick please Ignore this email. in:0px;padding:0px;background-color:#FFFFFF;"><div class="t1" style="background-color:#FFFFFF;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" align="center"><tbody><tr><td class="t130" style="font-size:0;line-height:0;mso-line-height-rule:exactly;" valign="top" align="center"> + <!--[if mso]> + <v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false"> + <v:fill color="#FFFFFF"/> + </v:background> + <![endif]--> + <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" align="center" id="innerTable"><tbody><tr><td> + <table class="t118" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + + <!--<![endif]--> + <!--[if mso]><td class="t119" style="width:400px;padding:40px 40px 40px 40px;"><![endif]--> + </tr></tbody></table><table role="presentation" width="100%" cellpadding="0" cellspacing="0"></table></td> + </tr></tbody></table> + </td></tr><tr><td> + <table class="t10" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t11" style="background-color:#FFFFFF;width:400px;"> + <!--<![endif]--> + <!--[if mso]><td class="t11" style="background-color:#FFFFFF;width:400px;"><![endif]--> + <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td> + <table class="t19" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t20" style="background-color:#404040;width:400px;padding:40px 40px 40px 40px;"> + <!--<![endif]--> + <!--[if mso]><td class="t20" style="background-color:#404040;width:480px;padding:40px 40px 40px 40px;"><![endif]--> + <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td> + <table class="t103" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t104" style="width:200px;"> + <!--<![endif]--> + <!--[if mso]><td class="t104" style="width:200px;"><![endif]--> + <div style="font-size:0px;"><img class="t110" style="display:block;border:0;height:auto;width:100%;Margin:0;max-width:100%;" width="200" height="179.5" alt="" src="https://835a1b8e-557a-4713-8f1c-104febdb8808.b-cdn.net/e/30b4288c-4e67-4e3b-9527-1fc4c4ec2fdf/df3f012a-c060-4d59-b5fd-54a57dae1916.png"></div></td> + </tr></tbody></table> + </td></tr></tbody></table></td> + </tr></tbody></table> + </td></tr><tr><td> + <table class="t28" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t29" style="width:420px;padding:30px 30px 40px 30px;"> + <!--<![endif]--> + <!--[if mso]><td class="t29" style="width:480px;padding:30px 30px 40px 30px;"><![endif]--> + <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td> + <table class="t42" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t43" style="width:480px;"> + <!--<![endif]--> + <!--[if mso]><td class="t43" style="width:480px;"><![endif]--> + <h1 class="t49" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Albert Sans';line-height:35px;font-weight:800;font-style:normal;font-size:30px;text-decoration:none;text-transform:none;letter-spacing:-1.2px;direction:ltr;color:#333333;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">Welcome to Donetick!</h1></td> + </tr></tbody></table> + </td></tr><tr><td><div class="t41" style="mso-line-height-rule:exactly;mso-line-height-alt:16px;line-height:16px;font-size:1px;display:block;"> </div></td></tr><tr><td><p class="t39" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:21px;font-weight:400;font-style:normal;font-size:14px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">Thank you for joining us. We're excited to have you on board.To complete your registration, click the button below</p></td></tr><tr><td><div class="t31" style="mso-line-height-rule:exactly;mso-line-height-alt:30px;line-height:30px;font-size:1px;display:block;"> </div></td></tr><tr><td> + <table class="t52" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t53" style="background-color:#06b6d4;overflow:hidden;width:460px;text-align:center;line-height:24px;mso-line-height-rule:exactly;mso-text-raise:2px;padding:10px 10px 10px 10px;border-radius:10px 10px 10px 10px;"> + <!--<![endif]--> + <!--[if mso]><td class="t53" style="background-color:#06b6d4;overflow:hidden;width:480px;text-align:center;line-height:24px;mso-line-height-rule:exactly;mso-text-raise:2px;padding:10px 10px 10px 10px;border-radius:10px 10px 10px 10px;"><![endif]--> + <a class="t59" href="{{verifyURL}}" style="display:block;margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:24px;font-weight:600;font-style:normal;font-size:16px;text-decoration:none;direction:ltr;color:#FFFFFF;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;" target="_blank">Complete your registration</a></td> + </tr></tbody></table> + </td></tr><tr><td><div class="t62" style="mso-line-height-rule:exactly;mso-line-height-alt:12px;line-height:12px;font-size:1px;display:block;"> </div></td></tr><tr><td> + <table class="t64" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t65" style="width:480px;"> + <!--<![endif]--> + <!--[if mso]><td class="t65" style="width:480px;"><![endif]--> + <p class="t71" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:21px;font-weight:400;font-style:normal;font-size:14px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;"> </p></td> + </tr></tbody></table> + </td></tr></tbody></table></td> + </tr></tbody></table> + </td></tr></tbody></table></td> + </tr></tbody></table> + </td></tr><tr><td><div class="t4" style="mso-line-height-rule:exactly;mso-line-height-alt:30px;line-height:30px;font-size:1px;display:block;"> </div></td></tr><tr><td> + <table class="t79" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t80" style="width:320px;padding:0 40px 0 40px;"> + <!--<![endif]--> + <!--[if mso]><td class="t80" style="width:400px;padding:0 40px 0 40px;"><![endif]--> + <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td> + <table class="t93" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t94" style="width:480px;"> + <!--<![endif]--> + <!--[if mso]><td class="t94" style="width:480px;"><![endif]--> + <p class="t100" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:18px;font-weight:400;font-style:normal;font-size:12px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">if you did not sign up with Donetick please Ignore this email. </p></td> + </tr></tbody></table> + </td></tr><tr><td><div class="t81" style="mso-line-height-rule:exactly;mso-line-height-alt:8px;line-height:8px;font-size:1px;display:block;"> </div></td></tr><tr><td> + <table class="t83" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t84" style="width:480px;"> + <!--<![endif]--> + <!--[if mso]><td class="t84" style="width:480px;"><![endif]--> + <p class="t90" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:18px;font-weight:400;font-style:normal;font-size:12px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">Favoro LLC. All rights reserved</p></td> + </tr></tbody></table> + </td></tr></tbody></table></td> + </tr></tbody></table> + </td></tr><tr><td><div class="t73" style="mso-line-height-rule:exactly;mso-line-height-alt:100px;line-height:100px;font-size:1px;display:block;"> </div></td></tr></tbody></table></div> + + </body></html> +` + u := es.appHost + "/verify?c=" + encodeEmailAndCode(to, code) + htmlBody = strings.Replace(htmlBody, "{{verifyURL}}", u, 1) + + msg.SetBody("text/html", htmlBody) + + err := es.client.DialAndSend(msg) + if err != nil { + return err + } + return nil + +} + +func (es *EmailSender) SendResetPasswordEmail(c context.Context, to, code string) error { + msg := gomail.NewMessage() + msg.SetHeader("From", "no-reply@donetick.com") + msg.SetHeader("To", to) + msg.SetHeader("Subject", "Donetick! Password Reset") + htmlBody := ` + <!-- + ******************************************************** + * This email was built using Tabular. + * Create emails, that look perfect in every inbox. + * For more information, visit https://tabular.email + ******************************************************** + --> + <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> + <html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" lang="en"><head> + <title></title> + <meta content="text/html; charset=utf-8" http-equiv="Content-Type"> + <!--[if !mso]><!--> + <meta http-equiv="X-UA-Compatible" content="IE=edge"> + <!--<![endif]--> + <meta name="x-apple-disable-message-reformatting" content=""> + <meta content="target-densitydpi=device-dpi" name="viewport"> + <meta content="true" name="HandheldFriendly"> + <meta content="width=device-width" name="viewport"> + <meta name="format-detection" content="telephone=no, date=no, address=no, email=no, url=no"> + <style type="text/css"> + table { + border-collapse: separate; + table-layout: fixed; + mso-table-lspace: 0pt; + mso-table-rspace: 0pt + } + table td { + border-collapse: collapse + } + .ExternalClass { + width: 100% + } + .ExternalClass, + .ExternalClass p, + .ExternalClass span, + .ExternalClass font, + .ExternalClass td, + .ExternalClass div { + line-height: 100% + } + body, a, li, p, h1, h2, h3 { + -ms-text-size-adjust: 100%; + -webkit-text-size-adjust: 100%; + } + html { + -webkit-text-size-adjust: none !important + } + body, #innerTable { + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale + } + #innerTable img+div { + display: none; + display: none !important + } + img { + Margin: 0; + padding: 0; + -ms-interpolation-mode: bicubic + } + h1, h2, h3, p, a { + line-height: 1; + overflow-wrap: normal; + white-space: normal; + word-break: break-word + } + a { + text-decoration: none + } + h1, h2, h3, p { + min-width: 100%!important; + width: 100%!important; + max-width: 100%!important; + display: inline-block!important; + border: 0; + padding: 0; + margin: 0 + } + a[x-apple-data-detectors] { + color: inherit !important; + text-decoration: none !important; + font-size: inherit !important; + font-family: inherit !important; + font-weight: inherit !important; + line-height: inherit !important + } + a[href^="mailto"], + a[href^="tel"], + a[href^="sms"] { + color: inherit; + text-decoration: none + } + @media (min-width: 481px) { + .hd { display: none!important } + } + @media (max-width: 480px) { + .hm { display: none!important } + } + [style*="Inter Tight"] {font-family: 'Inter Tight', BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif !important;} [style*="Albert Sans"] {font-family: 'Albert Sans', BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif !important;} + @media only screen and (min-width: 481px) {.t20{width:720px!important}.t27{padding:40px 60px 50px!important}.t29{padding:40px 60px 50px!important;width:680px!important}.t43{width:600px!important}.t53,.t61{width:580px!important}.t65{width:600px!important}.t78{padding-left:0!important;padding-right:0!important}.t80{padding-left:0!important;padding-right:0!important;width:400px!important}.t84,.t94{width:600px!important}} + </style> + <style type="text/css" media="screen and (min-width:481px)">.moz-text-html .t20{width:720px!important}.moz-text-html .t27{padding:40px 60px 50px!important}.moz-text-html .t29{padding:40px 60px 50px!important;width:680px!important}.moz-text-html .t43{width:600px!important}.moz-text-html .t53,.moz-text-html .t61{width:580px!important}.moz-text-html .t65{width:600px!important}.moz-text-html .t78{padding-left:0!important;padding-right:0!important}.moz-text-html .t80{padding-left:0!important;padding-right:0!important;width:400px!important}.moz-text-html .t84,.moz-text-html .t94{width:600px!important}</style> + <!--[if !mso]><!--> + <link href="https://fonts.googleapis.com/css2?family=Inter+Tight:wght@400;600&family=Albert+Sans:wght@800&display=swap" rel="stylesheet" type="text/css"> + <!--<![endif]--> + <!--[if mso]> + <style type="text/css"> + td.t20{width:800px !important}td.t27{padding:40px 60px 50px !important}td.t29{padding:40px 60px 50px !important;width:800px !important}td.t43,td.t53{width:600px !important}td.t61{width:580px !important}td.t65{width:600px !important}td.t78,td.t80{padding-left:0 !important;padding-right:0 !important}td.t84,td.t94{width:600px !important} + </style> + <![endif]--> + <!--[if mso]> + <xml> + <o:OfficeDocumentSettings> + <o:AllowPNG/> + <o:PixelsPerInch>96</o:PixelsPerInch> + </o:OfficeDocumentSettings> + </xml> + <![endif]--> + </head> + <body class="t0" style="min-width:100%;Marg + if you did not sign up with Donetick please Ignore this email. in:0px;padding:0px;background-color:#FFFFFF;"><div class="t1" style="background-color:#FFFFFF;"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" align="center"><tbody><tr><td class="t130" style="font-size:0;line-height:0;mso-line-height-rule:exactly;" valign="top" align="center"> + <!--[if mso]> + <v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false"> + <v:fill color="#FFFFFF"/> + </v:background> + <![endif]--> + <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" align="center" id="innerTable"><tbody><tr><td> + <table class="t118" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + + <!--<![endif]--> + <!--[if mso]><td class="t119" style="width:400px;padding:40px 40px 40px 40px;"><![endif]--> + </tr></tbody></table><table role="presentation" width="100%" cellpadding="0" cellspacing="0"></table></td> + </tr></tbody></table> + </td></tr><tr><td> + <table class="t10" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t11" style="background-color:#FFFFFF;width:400px;"> + <!--<![endif]--> + <!--[if mso]><td class="t11" style="background-color:#FFFFFF;width:400px;"><![endif]--> + <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td> + <table class="t19" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t20" style="background-color:#404040;width:400px;padding:40px 40px 40px 40px;"> + <!--<![endif]--> + <!--[if mso]><td class="t20" style="background-color:#404040;width:480px;padding:40px 40px 40px 40px;"><![endif]--> + <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td> + <table class="t103" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t104" style="width:200px;"> + <!--<![endif]--> + <!--[if mso]><td class="t104" style="width:200px;"><![endif]--> + <div style="font-size:0px;"><img class="t110" style="display:block;border:0;height:auto;width:100%;Margin:0;max-width:100%;" width="200" height="179.5" alt="" src="https://835a1b8e-557a-4713-8f1c-104febdb8808.b-cdn.net/e/30b4288c-4e67-4e3b-9527-1fc4c4ec2fdf/df3f012a-c060-4d59-b5fd-54a57dae1916.png"></div></td> + </tr></tbody></table> + </td></tr></tbody></table></td> + </tr></tbody></table> + </td></tr><tr><td> + <table class="t28" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t29" style="width:420px;padding:30px 30px 40px 30px;"> + <!--<![endif]--> + <!--[if mso]><td class="t29" style="width:480px;padding:30px 30px 40px 30px;"><![endif]--> + <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td> + <table class="t42" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t43" style="width:480px;"> + <!--<![endif]--> + <!--[if mso]><td class="t43" style="width:480px;"><![endif]--> + <h1 class="t49" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Albert Sans';line-height:35px;font-weight:800;font-style:normal;font-size:30px;text-decoration:none;text-transform:none;letter-spacing:-1.2px;direction:ltr;color:#333333;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">Someone forgot their password 😔</h1></td> + </tr></tbody></table> + </td></tr><tr><td><div class="t41" style="mso-line-height-rule:exactly;mso-line-height-alt:16px;line-height:16px;font-size:1px;display:block;"> </div></td></tr><tr><td><p class="t39" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:21px;font-weight:400;font-style:normal;font-size:14px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">We have received a password reset request for this email address. If you initiated this request, please click the button below to reset your password. Otherwise, you may safely ignore this email.</p></td></tr><tr><td><div class="t31" style="mso-line-height-rule:exactly;mso-line-height-alt:30px;line-height:30px;font-size:1px;display:block;"> </div></td></tr><tr><td> + <table class="t52" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t53" style="background-color:#06b6d4;overflow:hidden;width:460px;text-align:center;line-height:24px;mso-line-height-rule:exactly;mso-text-raise:2px;padding:10px 10px 10px 10px;border-radius:10px 10px 10px 10px;"> + <!--<![endif]--> + <!--[if mso]><td class="t53" style="background-color:#06b6d4;overflow:hidden;width:480px;text-align:center;line-height:24px;mso-line-height-rule:exactly;mso-text-raise:2px;padding:10px 10px 10px 10px;border-radius:10px 10px 10px 10px;"><![endif]--> + <a class="t59" href="{{verifyURL}}" style="display:block;margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:24px;font-weight:600;font-style:normal;font-size:16px;text-decoration:none;direction:ltr;color:#FFFFFF;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;" target="_blank">Reset your Password</a></td> + </tr></tbody></table> + </td></tr><tr><td><div class="t62" style="mso-line-height-rule:exactly;mso-line-height-alt:12px;line-height:12px;font-size:1px;display:block;"> </div></td></tr><tr><td> + <table class="t64" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t65" style="width:480px;"> + <!--<![endif]--> + <!--[if mso]><td class="t65" style="width:480px;"><![endif]--> + <p class="t71" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:21px;font-weight:400;font-style:normal;font-size:14px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;"> </p></td> + </tr></tbody></table> + </td></tr></tbody></table></td> + </tr></tbody></table> + </td></tr></tbody></table></td> + </tr></tbody></table> + </td></tr><tr><td><div class="t4" style="mso-line-height-rule:exactly;mso-line-height-alt:30px;line-height:30px;font-size:1px;display:block;"> </div></td></tr><tr><td> + <table class="t79" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t80" style="width:320px;padding:0 40px 0 40px;"> + <!--<![endif]--> + <!--[if mso]><td class="t80" style="width:400px;padding:0 40px 0 40px;"><![endif]--> + <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tbody><tr><td> + <table class="t93" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t94" style="width:480px;"> + <!--<![endif]--> + <!--[if mso]><td class="t94" style="width:480px;"><![endif]--> + <p class="t100" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:18px;font-weight:400;font-style:normal;font-size:12px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">if you did not sign up with Donetick please Ignore this email. </p></td> + </tr></tbody></table> + </td></tr><tr><td><div class="t81" style="mso-line-height-rule:exactly;mso-line-height-alt:8px;line-height:8px;font-size:1px;display:block;"> </div></td></tr><tr><td> + <table class="t83" role="presentation" cellpadding="0" cellspacing="0" align="center"><tbody><tr> + <!--[if !mso]><!--><td class="t84" style="width:480px;"> + <!--<![endif]--> + <!--[if mso]><td class="t84" style="width:480px;"><![endif]--> + <p class="t90" style="margin:0;Margin:0;font-family:BlinkMacSystemFont,Segoe UI,Helvetica Neue,Arial,sans-serif,'Inter Tight';line-height:18px;font-weight:400;font-style:normal;font-size:12px;text-decoration:none;text-transform:none;direction:ltr;color:#555555;text-align:center;mso-line-height-rule:exactly;mso-text-raise:2px;">Favoro LLC. All rights reserved</p></td> + </tr></tbody></table> + </td></tr></tbody></table></td> + </tr></tbody></table> + </td></tr><tr><td><div class="t73" style="mso-line-height-rule:exactly;mso-line-height-alt:100px;line-height:100px;font-size:1px;display:block;"> </div></td></tr></tbody></table></div> + + </body></html> +` + u := es.appHost + "/password/update?c=" + encodeEmailAndCode(to, code) + + // logging.FromContext(c).Infof("Reset password URL: %s", u) + htmlBody = strings.Replace(htmlBody, "{{verifyURL}}", u, 1) + + msg.SetBody("text/html", htmlBody) + + err := es.client.DialAndSend(msg) + if err != nil { + return err + } + return nil + +} + +// func (es *EmailSender) SendFeedbackRequestEmail(to, code string) error { +// // msg := []byte(fmt.Sprintf("To: %s\r\nSubject: %s\r\n\r\n%s\r\n", to, subject, body)) +// msg := gomail.NewMessage() + +// } +func encodeEmailAndCode(email, code string) string { + data := email + ":" + code + return base64.StdEncoding.EncodeToString([]byte(data)) +} + +func DecodeEmailAndCode(encoded string) (string, string, error) { + data, err := base64.StdEncoding.DecodeString(encoded) + if err != nil { + return "", "", err + } + parts := string(data) + split := strings.Split(parts, ":") + if len(split) != 2 { + return "", "", fmt.Errorf("Invalid format") + } + return split[0], split[1], nil +} diff --git a/internal/notifier/model/model.go b/internal/notifier/model/model.go new file mode 100644 index 0000000..47c81df --- /dev/null +++ b/internal/notifier/model/model.go @@ -0,0 +1,15 @@ +package model + +import "time" + +type Notification struct { + ID int `json:"id" gorm:"primaryKey"` + ChoreID int `json:"chore_id" gorm:"column:chore_id"` + UserID int `json:"user_id" gorm:"column:user_id"` + TargetID string `json:"target_id" gorm:"column:target_id"` + Text string `json:"text" gorm:"column:text"` + IsSent bool `json:"is_sent" gorm:"column:is_sent;index;default:false"` + TypeID int `json:"type" gorm:"column:type"` + ScheduledFor time.Time `json:"scheduled_for" gorm:"column:scheduled_for;index"` + CreatedAt time.Time `json:"created_at" gorm:"column:created_at"` +} diff --git a/internal/notifier/repo/repository.go b/internal/notifier/repo/repository.go new file mode 100644 index 0000000..576a3f0 --- /dev/null +++ b/internal/notifier/repo/repository.go @@ -0,0 +1,43 @@ +package user + +import ( + "context" + "time" + + nModel "donetick.com/core/internal/notifier/model" + "gorm.io/gorm" +) + +type NotificationRepository struct { + db *gorm.DB +} + +func NewNotificationRepository(db *gorm.DB) *NotificationRepository { + return &NotificationRepository{db} +} + +func (r *NotificationRepository) DeleteAllChoreNotifications(choreID int) error { + return r.db.Where("chore_id = ?", choreID).Delete(&nModel.Notification{}).Error +} + +func (r *NotificationRepository) BatchInsertNotifications(notifications []*nModel.Notification) error { + return r.db.Create(¬ifications).Error +} +func (r *NotificationRepository) MarkNotificationsAsSent(notifications []*nModel.Notification) error { + // Extract IDs from notifications + var ids []int + for _, notification := range notifications { + ids = append(ids, notification.ID) + } + // Use the extracted IDs in the Where clause + return r.db.Model(&nModel.Notification{}).Where("id IN (?)", ids).Update("is_sent", true).Error +} +func (r *NotificationRepository) GetPendingNotificaiton(c context.Context, lookback time.Duration) ([]*nModel.Notification, error) { + var notifications []*nModel.Notification + start := time.Now().UTC().Add(-lookback) + end := time.Now().UTC() + if err := r.db.Debug().Where("is_sent = ? AND scheduled_for < ? AND scheduled_for > ?", false, end, start).Find(¬ifications).Error; err != nil { + return nil, err + } + return notifications, nil +} diff --git a/internal/notifier/scheduler.go b/internal/notifier/scheduler.go new file mode 100644 index 0000000..69470d2 --- /dev/null +++ b/internal/notifier/scheduler.go @@ -0,0 +1,89 @@ +package notifier + +import ( + "context" + "log" + "time" + + "donetick.com/core/config" + chRepo "donetick.com/core/internal/chore/repo" + nRepo "donetick.com/core/internal/notifier/repo" + notifier "donetick.com/core/internal/notifier/telegram" + uRepo "donetick.com/core/internal/user/repo" + "donetick.com/core/logging" +) + +type keyType string + +const ( + SchedulerKey keyType = "scheduler" +) + +type Scheduler struct { + choreRepo *chRepo.ChoreRepository + userRepo *uRepo.UserRepository + stopChan chan bool + notifier *notifier.TelegramNotifier + notificationRepo *nRepo.NotificationRepository + SchedulerJobs config.SchedulerConfig +} + +func NewScheduler(cfg *config.Config, ur *uRepo.UserRepository, cr *chRepo.ChoreRepository, n *notifier.TelegramNotifier, nr *nRepo.NotificationRepository) *Scheduler { + return &Scheduler{ + choreRepo: cr, + userRepo: ur, + stopChan: make(chan bool), + notifier: n, + notificationRepo: nr, + SchedulerJobs: cfg.SchedulerJobs, + } +} + +func (s *Scheduler) Start(c context.Context) { + log := logging.FromContext(c) + log.Debug("Scheduler started") + go s.runScheduler(c, " NOTIFICATION_SCHEDULER ", s.loadAndSendNotificationJob, 3*time.Minute) +} + +func (s *Scheduler) loadAndSendNotificationJob(c context.Context) (time.Duration, error) { + log := logging.FromContext(c) + startTime := time.Now() + getAllPendingNotifications, err := s.notificationRepo.GetPendingNotificaiton(c, time.Minute*15) + log.Debug("Getting pending notifications", " count ", len(getAllPendingNotifications)) + + if err != nil { + log.Error("Error getting pending notifications") + return time.Since(startTime), err + } + + for _, notification := range getAllPendingNotifications { + s.notifier.SendNotification(c, notification) + notification.IsSent = true + } + + s.notificationRepo.MarkNotificationsAsSent(getAllPendingNotifications) + return time.Since(startTime), nil +} +func (s *Scheduler) runScheduler(c context.Context, jobName string, job func(c context.Context) (time.Duration, error), interval time.Duration) { + + for { + logging.FromContext(c).Debug("Scheduler running ", jobName, " time", time.Now().String()) + + select { + case <-s.stopChan: + log.Println("Scheduler stopped") + return + default: + elapsedTime, err := job(c) + if err != nil { + logging.FromContext(c).Error("Error running scheduler job", err) + } + logging.FromContext(c).Debug("Scheduler job completed", jobName, " time", elapsedTime.String()) + } + time.Sleep(interval) + } +} + +func (s *Scheduler) Stop() { + s.stopChan <- true +} diff --git a/internal/notifier/service/planner.go b/internal/notifier/service/planner.go new file mode 100644 index 0000000..22502ab --- /dev/null +++ b/internal/notifier/service/planner.go @@ -0,0 +1,149 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "time" + + chModel "donetick.com/core/internal/chore/model" + cModel "donetick.com/core/internal/circle/model" + cRepo "donetick.com/core/internal/circle/repo" + nModel "donetick.com/core/internal/notifier/model" + nRepo "donetick.com/core/internal/notifier/repo" + "donetick.com/core/logging" +) + +type NotificationPlanner struct { + nRepo *nRepo.NotificationRepository + cRepo *cRepo.CircleRepository +} + +func NewNotificationPlanner(nr *nRepo.NotificationRepository, cr *cRepo.CircleRepository) *NotificationPlanner { + return &NotificationPlanner{nRepo: nr, + cRepo: cr, + } +} + +func (n *NotificationPlanner) GenerateNotifications(c context.Context, chore *chModel.Chore) bool { + log := logging.FromContext(c) + circleMembers, err := n.cRepo.GetCircleUsers(c, chore.CircleID) + assignees := make([]*cModel.UserCircleDetail, 0) + for _, member := range circleMembers { + if member.ID == chore.AssignedTo { + assignees = append(assignees, member) + } + } + + if err != nil { + log.Error("Error getting circle members", err) + return false + } + n.nRepo.DeleteAllChoreNotifications(chore.ID) + notifications := make([]*nModel.Notification, 0) + if !chore.Notification || chore.FrequencyType == "trigger" { + + return true + } + var mt *chModel.NotificationMetadata + if err := json.Unmarshal([]byte(*chore.NotificationMetadata), &mt); err != nil { + log.Error("Error unmarshalling notification metadata", err) + return true + } + if mt.DueDate { + notifications = append(notifications, generateDueNotifications(chore, assignees)...) + } + if mt.PreDue { + notifications = append(notifications, generatePreDueNotifications(chore, assignees)...) + } + if mt.Nagging { + notifications = append(notifications, generateOverdueNotifications(chore, assignees)...) + } + + n.nRepo.BatchInsertNotifications(notifications) + return true +} + +func generateDueNotifications(chore *chModel.Chore, users []*cModel.UserCircleDetail) []*nModel.Notification { + var assignee *cModel.UserCircleDetail + notifications := make([]*nModel.Notification, 0) + for _, user := range users { + if user.ID == chore.AssignedTo { + assignee = user + break + } + } + for _, user := range users { + + notification := &nModel.Notification{ + ChoreID: chore.ID, + IsSent: false, + ScheduledFor: *chore.NextDueDate, + CreatedAt: time.Now().UTC(), + TypeID: 1, + UserID: user.ID, + TargetID: fmt.Sprint(user.ChatID), + Text: fmt.Sprintf("📅 Reminder: '%s' is due today and assigned to %s.", chore.Name, assignee.DisplayName), + } + notifications = append(notifications, notification) + } + + return notifications +} + +func generatePreDueNotifications(chore *chModel.Chore, users []*cModel.UserCircleDetail) []*nModel.Notification { + var assignee *cModel.UserCircleDetail + for _, user := range users { + if user.ID == chore.AssignedTo { + assignee = user + break + } + } + notifications := make([]*nModel.Notification, 0) + for _, user := range users { + notification := &nModel.Notification{ + ChoreID: chore.ID, + IsSent: false, + ScheduledFor: *chore.NextDueDate, + CreatedAt: time.Now().UTC().Add(-time.Hour * 3), + TypeID: 3, + UserID: user.ID, + TargetID: fmt.Sprint(user.ChatID), + Text: fmt.Sprintf("📢 Heads up! Chore '%s' is due soon (on %s) and assigned to %s.", chore.Name, chore.NextDueDate.Format("January 2nd"), assignee.DisplayName), + } + notifications = append(notifications, notification) + + } + return notifications + +} + +func generateOverdueNotifications(chore *chModel.Chore, users []*cModel.UserCircleDetail) []*nModel.Notification { + var assignee *cModel.UserCircleDetail + for _, user := range users { + if user.ID == chore.AssignedTo { + assignee = user + break + } + } + notifications := make([]*nModel.Notification, 0) + for _, hours := range []int{24, 48, 72} { + scheduleTime := chore.NextDueDate.Add(time.Hour * time.Duration(hours)) + for _, user := range users { + notification := &nModel.Notification{ + ChoreID: chore.ID, + IsSent: false, + ScheduledFor: scheduleTime, + CreatedAt: time.Now().UTC(), + TypeID: 2, + UserID: user.ID, + TargetID: fmt.Sprint(user.ChatID), + Text: fmt.Sprintf("🚨 '%s' is now %d hours overdue. Please complete it as soon as possible. (Assigned to %s)", chore.Name, hours, assignee.DisplayName), + } + notifications = append(notifications, notification) + } + } + + return notifications + +} diff --git a/internal/notifier/telegram/telegram.go b/internal/notifier/telegram/telegram.go new file mode 100644 index 0000000..e35f0c8 --- /dev/null +++ b/internal/notifier/telegram/telegram.go @@ -0,0 +1,127 @@ +package telegram + +import ( + "context" + "fmt" + "strconv" + + "donetick.com/core/config" + chModel "donetick.com/core/internal/chore/model" + nModel "donetick.com/core/internal/notifier/model" + uModel "donetick.com/core/internal/user/model" + "donetick.com/core/logging" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +type TelegramNotifier struct { + bot *tgbotapi.BotAPI +} + +func NewTelegramNotifier(config *config.Config) *TelegramNotifier { + bot, err := tgbotapi.NewBotAPI(config.Telegram.Token) + if err != nil { + fmt.Println("Error creating bot: ", err) + return nil + } + + return &TelegramNotifier{ + bot: bot, + } +} + +func (tn *TelegramNotifier) SendChoreReminder(c context.Context, chore *chModel.Chore, users []*uModel.User) { + for _, user := range users { + var assignee *uModel.User + if user.ID == chore.AssignedTo { + if user.ChatID == 0 { + continue + } + assignee = user + text := fmt.Sprintf("*%s* is due today and assigned to *%s*", chore.Name, assignee.DisplayName) + msg := tgbotapi.NewMessage(user.ChatID, text) + msg.ParseMode = "Markdown" + _, err := tn.bot.Send(msg) + if err != nil { + fmt.Println("Error sending message to user: ", err) + } + break + } + } +} + +func (tn *TelegramNotifier) SendChoreCompletion(c context.Context, chore *chModel.Chore, users []*uModel.User) { + log := logging.FromContext(c) + for _, user := range users { + if user.ChatID == 0 { + continue + } + text := fmt.Sprintf("🎉 '%s' is completed! is off the list, %s! 🌟 ", chore.Name, user.DisplayName) + msg := tgbotapi.NewMessage(user.ChatID, text) + msg.ParseMode = "Markdown" + _, err := tn.bot.Send(msg) + if err != nil { + log.Error("Error sending message to user: ", err) + log.Debug("Error sending message, chore: ", chore.Name, " user: ", user.DisplayName, " chatID: ", user.ChatID, " user id: ", user.ID) + } + + } +} + +func (tn *TelegramNotifier) SendChoreOverdue(c context.Context, chore *chModel.Chore, users []*uModel.User) { + log := logging.FromContext(c) + for _, user := range users { + if user.ChatID == 0 { + continue + } + text := fmt.Sprintf("*%s* is overdue and assigned to *%s*", chore.Name, user.DisplayName) + msg := tgbotapi.NewMessage(user.ChatID, text) + msg.ParseMode = "Markdown" + _, err := tn.bot.Send(msg) + if err != nil { + log.Error("Error sending message to user: ", err) + log.Debug("Error sending message, chore: ", chore.Name, " user: ", user.DisplayName, " chatID: ", user.ChatID, " user id: ", user.ID) + } + } +} + +func (tn *TelegramNotifier) SendChorePreDue(c context.Context, chore *chModel.Chore, users []*uModel.User) { + log := logging.FromContext(c) + for _, user := range users { + if user.ID != chore.AssignedTo { + continue + } + if user.ChatID == 0 { + continue + } + text := fmt.Sprintf("*%s* is due tomorrow and assigned to *%s*", chore.Name, user.DisplayName) + msg := tgbotapi.NewMessage(user.ChatID, text) + msg.ParseMode = "Markdown" + _, err := tn.bot.Send(msg) + if err != nil { + log.Error("Error sending message to user: ", err) + log.Debug("Error sending message, chore: ", chore.Name, " user: ", user.DisplayName, " chatID: ", user.ChatID, " user id: ", user.ID) + } + } +} + +func (tn *TelegramNotifier) SendNotification(c context.Context, notification *nModel.Notification) { + + log := logging.FromContext(c) + if notification.TargetID == "" { + log.Error("Notification target ID is empty") + return + } + chatID, err := strconv.ParseInt(notification.TargetID, 10, 64) + if err != nil { + log.Error("Error parsing chatID: ", err) + return + } + + msg := tgbotapi.NewMessage(chatID, notification.Text) + msg.ParseMode = "Markdown" + _, err = tn.bot.Send(msg) + if err != nil { + log.Error("Error sending message to user: ", err) + log.Debug("Error sending message, notification: ", notification.Text, " chatID: ", chatID) + } +} diff --git a/internal/thing/handler.go b/internal/thing/handler.go new file mode 100644 index 0000000..5166157 --- /dev/null +++ b/internal/thing/handler.go @@ -0,0 +1,281 @@ +package thing + +import ( + "strconv" + "time" + + auth "donetick.com/core/internal/authorization" + chRepo "donetick.com/core/internal/chore/repo" + cRepo "donetick.com/core/internal/circle/repo" + nRepo "donetick.com/core/internal/notifier/repo" + nps "donetick.com/core/internal/notifier/service" + tModel "donetick.com/core/internal/thing/model" + tRepo "donetick.com/core/internal/thing/repo" + "donetick.com/core/logging" + jwt "github.com/appleboy/gin-jwt/v2" + "github.com/gin-gonic/gin" +) + +type Handler struct { + choreRepo *chRepo.ChoreRepository + circleRepo *cRepo.CircleRepository + nPlanner *nps.NotificationPlanner + nRepo *nRepo.NotificationRepository + tRepo *tRepo.ThingRepository +} + +type ThingRequest struct { + ID int `json:"id"` + Name string `json:"name" binding:"required"` + Type string `json:"type" binding:"required"` + State string `json:"state"` +} + +func NewHandler(cr *chRepo.ChoreRepository, circleRepo *cRepo.CircleRepository, + np *nps.NotificationPlanner, nRepo *nRepo.NotificationRepository, tRepo *tRepo.ThingRepository) *Handler { + return &Handler{ + choreRepo: cr, + circleRepo: circleRepo, + nPlanner: np, + nRepo: nRepo, + tRepo: tRepo, + } +} + +func (h *Handler) CreateThing(c *gin.Context) { + log := logging.FromContext(c) + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(401, gin.H{"error": "Unauthorized"}) + return + } + + var req ThingRequest + if err := c.BindJSON(&req); err != nil { + c.JSON(400, gin.H{"error": err.Error()}) + return + } + thing := &tModel.Thing{ + Name: req.Name, + UserID: currentUser.ID, + Type: req.Type, + State: req.State, + } + if !isValidThingState(thing) { + c.JSON(400, gin.H{"error": "Invalid state"}) + return + } + log.Debug("Creating thing", thing) + if err := h.tRepo.UpsertThing(c, thing); err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + c.JSON(201, gin.H{ + "res": thing, + }) +} + +func (h *Handler) UpdateThingState(c *gin.Context) { + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(401, gin.H{"error": "Unauthorized"}) + return + } + + thingIDRaw := c.Param("id") + thingID, err := strconv.Atoi(thingIDRaw) + if err != nil { + c.JSON(400, gin.H{"error": "Invalid thing id"}) + return + } + + val := c.Query("value") + if val == "" { + c.JSON(400, gin.H{"error": "state or increment query param is required"}) + return + } + thing, err := h.tRepo.GetThingByID(c, thingID) + if thing.UserID != currentUser.ID { + c.JSON(403, gin.H{"error": "Forbidden"}) + return + } + if err != nil { + c.JSON(500, gin.H{"error": "Unable to find thing"}) + return + } + thing.State = val + if !isValidThingState(thing) { + c.JSON(400, gin.H{"error": "Invalid state"}) + return + } + + if err := h.tRepo.UpdateThingState(c, thing); err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + + shouldReturn := EvaluateTriggerAndScheduleDueDate(h, c, thing) + if shouldReturn { + return + } + + c.JSON(200, gin.H{ + "res": thing, + }) +} + +func EvaluateTriggerAndScheduleDueDate(h *Handler, c *gin.Context, thing *tModel.Thing) bool { + thingChores, err := h.tRepo.GetThingChoresByThingId(c, thing.ID) + if err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return true + } + for _, tc := range thingChores { + triggered := EvaluateThingChore(tc, thing.State) + if triggered { + h.choreRepo.SetDueDateIfNotExisted(c, tc.ChoreID, time.Now().UTC()) + } + } + return false +} + +func (h *Handler) UpdateThing(c *gin.Context) { + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(401, gin.H{"error": "Unauthorized"}) + return + } + + var req ThingRequest + if err := c.BindJSON(&req); err != nil { + c.JSON(400, gin.H{"error": err.Error()}) + return + } + + thing, err := h.tRepo.GetThingByID(c, req.ID) + + if err != nil { + c.JSON(500, gin.H{"error": "Unable to find thing"}) + return + } + if thing.UserID != currentUser.ID { + c.JSON(403, gin.H{"error": "Forbidden"}) + return + } + thing.Name = req.Name + thing.Type = req.Type + if req.State != "" { + thing.State = req.State + if !isValidThingState(thing) { + c.JSON(400, gin.H{"error": "Invalid state"}) + return + } + } + + if err := h.tRepo.UpsertThing(c, thing); err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + c.JSON(200, gin.H{ + "res": thing, + }) +} + +func (h *Handler) GetAllThings(c *gin.Context) { + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(401, gin.H{"error": "Unauthorized"}) + return + } + + things, err := h.tRepo.GetUserThings(c, currentUser.ID) + if err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + c.JSON(200, gin.H{ + "res": things, + }) +} + +func (h *Handler) GetThingHistory(c *gin.Context) { + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(401, gin.H{"error": "Unauthorized"}) + return + } + + thingIDRaw := c.Param("id") + thingID, err := strconv.Atoi(thingIDRaw) + if err != nil { + c.JSON(400, gin.H{"error": "Invalid thing id"}) + return + } + + thing, err := h.tRepo.GetThingByID(c, thingID) + if err != nil { + c.JSON(500, gin.H{"error": "Unable to find thing"}) + return + } + if thing.UserID != currentUser.ID { + c.JSON(403, gin.H{"error": "Forbidden"}) + return + } + offsetRaw := c.Query("offset") + offset, err := strconv.Atoi(offsetRaw) + if err != nil { + c.JSON(400, gin.H{"error": "Invalid offset"}) + return + } + history, err := h.tRepo.GetThingHistoryWithOffset(c, thingID, offset, 10) + if err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + c.JSON(200, gin.H{ + "res": history, + }) +} + +func (h *Handler) DeleteThing(c *gin.Context) { + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(401, gin.H{"error": "Unauthorized"}) + return + } + + thingIDRaw := c.Param("id") + thingID, err := strconv.Atoi(thingIDRaw) + if err != nil { + c.JSON(400, gin.H{"error": "Invalid thing id"}) + return + } + + thing, err := h.tRepo.GetThingByID(c, thingID) + if err != nil { + c.JSON(500, gin.H{"error": "Unable to find thing"}) + return + } + if thing.UserID != currentUser.ID { + c.JSON(403, gin.H{"error": "Forbidden"}) + return + } + if err := h.tRepo.DeleteThing(c, thingID); err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + c.JSON(200, gin.H{}) +} +func Routes(r *gin.Engine, h *Handler, auth *jwt.GinJWTMiddleware) { + + thingRoutes := r.Group("things") + thingRoutes.Use(auth.MiddlewareFunc()) + { + thingRoutes.POST("", h.CreateThing) + thingRoutes.PUT("/:id/state", h.UpdateThingState) + thingRoutes.PUT("", h.UpdateThing) + thingRoutes.GET("", h.GetAllThings) + thingRoutes.GET("/:id/history", h.GetThingHistory) + thingRoutes.DELETE("/:id", h.DeleteThing) + } +} diff --git a/internal/thing/helper.go b/internal/thing/helper.go new file mode 100644 index 0000000..c3941ee --- /dev/null +++ b/internal/thing/helper.go @@ -0,0 +1,57 @@ +package thing + +import ( + "strconv" + + tModel "donetick.com/core/internal/thing/model" +) + +func isValidThingState(thing *tModel.Thing) bool { + switch thing.Type { + case "number": + _, err := strconv.Atoi(thing.State) + return err == nil + case "text": + return true + case "boolean": + return thing.State == "true" || thing.State == "false" + default: + return false + } +} + +func EvaluateThingChore(tchore *tModel.ThingChore, newState string) bool { + if tchore.Condition == "" { + return newState == tchore.TriggerState + } + + switch tchore.Condition { + case "eq": + return newState == tchore.TriggerState + case "neq": + return newState != tchore.TriggerState + } + + newStateInt, err := strconv.Atoi(newState) + if err != nil { + return false + } + TargetStateInt, err := strconv.Atoi(tchore.TriggerState) + if err != nil { + return false + } + + switch tchore.Condition { + case "gt": + return newStateInt > TargetStateInt + case "lt": + return newStateInt < TargetStateInt + case "gte": + return newStateInt >= TargetStateInt + case "lte": + return newStateInt <= TargetStateInt + default: + return newState == tchore.TriggerState + } + +} diff --git a/internal/thing/model/model.go b/internal/thing/model/model.go new file mode 100644 index 0000000..1780c64 --- /dev/null +++ b/internal/thing/model/model.go @@ -0,0 +1,30 @@ +package model + +import "time" + +type Thing struct { + ID int `json:"id" gorm:"primary_key"` + UserID int `json:"userID" gorm:"column:user_id"` + CircleID int `json:"circleId" gorm:"column:circle_id"` + Name string `json:"name" gorm:"column:name"` + State string `json:"state" gorm:"column:state"` + Type string `json:"type" gorm:"column:type"` + ThingChores []ThingChore `json:"thingChores" gorm:"foreignkey:ThingID;references:ID"` + UpdatedAt *time.Time `json:"updatedAt" gorm:"column:updated_at"` + CreatedAt *time.Time `json:"createdAt" gorm:"column:created_at"` +} + +type ThingHistory struct { + ID int `json:"id" gorm:"primary_key"` + ThingID int `json:"thingId" gorm:"column:thing_id"` + State string `json:"state" gorm:"column:state"` + UpdatedAt *time.Time `json:"updatedAt" gorm:"column:updated_at"` + CreatedAt *time.Time `json:"createdAt" gorm:"column:created_at"` +} + +type ThingChore struct { + ThingID int `json:"thingId" gorm:"column:thing_id;primaryKey;uniqueIndex:idx_thing_user"` + ChoreID int `json:"choreId" gorm:"column:chore_id;primaryKey;uniqueIndex:idx_thing_user"` + TriggerState string `json:"triggerState" gorm:"column:trigger_state"` + Condition string `json:"condition" gorm:"column:condition"` +} diff --git a/internal/thing/repo/repository.go b/internal/thing/repo/repository.go new file mode 100644 index 0000000..8b2dbaa --- /dev/null +++ b/internal/thing/repo/repository.go @@ -0,0 +1,117 @@ +package chore + +import ( + "context" + "time" + + config "donetick.com/core/config" + tModel "donetick.com/core/internal/thing/model" + "gorm.io/gorm" +) + +type ThingRepository struct { + db *gorm.DB + dbType string +} + +func NewThingRepository(db *gorm.DB, cfg *config.Config) *ThingRepository { + return &ThingRepository{db: db, dbType: cfg.Database.Type} +} + +func (r *ThingRepository) UpsertThing(c context.Context, thing *tModel.Thing) error { + return r.db.WithContext(c).Model(&thing).Save(thing).Error +} + +func (r *ThingRepository) UpdateThingState(c context.Context, thing *tModel.Thing) error { + // update the state of the thing where the id is the same: + if err := r.db.WithContext(c).Model(&thing).Where("id = ?", thing.ID).Updates(map[string]interface{}{ + "state": thing.State, + "updated_at": time.Now().UTC(), + }).Error; err != nil { + return err + } + // Create history Record of the thing : + createdAt := time.Now().UTC() + thingHistory := &tModel.ThingHistory{ + ThingID: thing.ID, + State: thing.State, + CreatedAt: &createdAt, + UpdatedAt: &createdAt, + } + + if err := r.db.WithContext(c).Create(thingHistory).Error; err != nil { + return err + } + + return nil +} +func (r *ThingRepository) GetThingByID(c context.Context, thingID int) (*tModel.Thing, error) { + var thing tModel.Thing + if err := r.db.WithContext(c).Model(&tModel.Thing{}).Preload("ThingChores").First(&thing, thingID).Error; err != nil { + return nil, err + } + return &thing, nil +} + +func (r *ThingRepository) GetThingByChoreID(c context.Context, choreID int) (*tModel.Thing, error) { + var thing tModel.Thing + if err := r.db.WithContext(c).Model(&tModel.Thing{}).Joins("left join thing_chores on things.id = thing_chores.thing_id").First(&thing, "thing_chores.chore_id = ?", choreID).Error; err != nil { + return nil, err + } + return &thing, nil +} + +func (r *ThingRepository) AssociateThingWithChore(c context.Context, thingID int, choreID int, triggerState string, condition string) error { + + return r.db.WithContext(c).Save(&tModel.ThingChore{ThingID: thingID, ChoreID: choreID, TriggerState: triggerState, Condition: condition}).Error +} + +func (r *ThingRepository) DissociateThingWithChore(c context.Context, thingID int, choreID int) error { + return r.db.WithContext(c).Where("thing_id = ? AND chore_id = ?", thingID, choreID).Delete(&tModel.ThingChore{}).Error +} + +func (r *ThingRepository) GetThingHistoryWithOffset(c context.Context, thingID int, offset int, limit int) ([]*tModel.ThingHistory, error) { + var thingHistory []*tModel.ThingHistory + if err := r.db.WithContext(c).Model(&tModel.ThingHistory{}).Where("thing_id = ?", thingID).Order("created_at desc").Offset(offset).Limit(limit).Find(&thingHistory).Error; err != nil { + return nil, err + } + return thingHistory, nil +} + +func (r *ThingRepository) GetUserThings(c context.Context, userID int) ([]*tModel.Thing, error) { + var things []*tModel.Thing + if err := r.db.WithContext(c).Model(&tModel.Thing{}).Where("user_id = ?", userID).Find(&things).Error; err != nil { + return nil, err + } + return things, nil +} + +func (r *ThingRepository) DeleteThing(c context.Context, thingID int) error { + // one transaction to delete the thing and its history : + return r.db.WithContext(c).Transaction(func(tx *gorm.DB) error { + if err := r.db.WithContext(c).Where("thing_id = ?", thingID).Delete(&tModel.ThingHistory{}).Error; err != nil { + return err + } + if err := r.db.WithContext(c).Delete(&tModel.Thing{}, thingID).Error; err != nil { + return err + } + return nil + }) +} + +// get ThingChores by thingID: +func (r *ThingRepository) GetThingChoresByThingId(c context.Context, thingID int) ([]*tModel.ThingChore, error) { + var thingChores []*tModel.ThingChore + if err := r.db.WithContext(c).Model(&tModel.ThingChore{}).Where("thing_id = ?", thingID).Find(&thingChores).Error; err != nil { + return nil, err + } + return thingChores, nil +} + +// func (r *ThingRepository) GetChoresByThingId(c context.Context, thingID int) ([]*chModel.Chore, error) { +// var chores []*chModel.Chore +// if err := r.db.WithContext(c).Model(&chModel.Chore{}).Joins("left join thing_chores on chores.id = thing_chores.chore_id").Where("thing_chores.thing_id = ?", thingID).Find(&chores).Error; err != nil { +// return nil, err +// } +// return chores, nil +// } diff --git a/internal/thing/webhook.go b/internal/thing/webhook.go new file mode 100644 index 0000000..0d110ab --- /dev/null +++ b/internal/thing/webhook.go @@ -0,0 +1,175 @@ +package thing + +import ( + "strconv" + "time" + + "donetick.com/core/config" + chRepo "donetick.com/core/internal/chore/repo" + cRepo "donetick.com/core/internal/circle/repo" + tModel "donetick.com/core/internal/thing/model" + tRepo "donetick.com/core/internal/thing/repo" + uRepo "donetick.com/core/internal/user/repo" + "donetick.com/core/internal/utils" + "donetick.com/core/logging" + jwt "github.com/appleboy/gin-jwt/v2" + "github.com/gin-gonic/gin" +) + +type Webhook struct { + choreRepo *chRepo.ChoreRepository + circleRepo *cRepo.CircleRepository + thingRepo *tRepo.ThingRepository + userRepo *uRepo.UserRepository + tRepo *tRepo.ThingRepository +} + +func NewWebhook(cr *chRepo.ChoreRepository, circleRepo *cRepo.CircleRepository, + thingRepo *tRepo.ThingRepository, userRepo *uRepo.UserRepository, tRepo *tRepo.ThingRepository) *Webhook { + return &Webhook{ + choreRepo: cr, + circleRepo: circleRepo, + thingRepo: thingRepo, + userRepo: userRepo, + tRepo: tRepo, + } +} + +func (h *Webhook) UpdateThingState(c *gin.Context) { + thing, shouldReturn := validateUserAndThing(c, h) + if shouldReturn { + return + } + + state := c.Query("state") + if state == "" { + c.JSON(400, gin.H{"error": "Invalid state value"}) + return + } + + thing.State = state + if !isValidThingState(thing) { + c.JSON(400, gin.H{"error": "Invalid state for thing"}) + return + } + + if err := h.thingRepo.UpdateThingState(c, thing); err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + c.JSON(200, gin.H{}) +} + +func (h *Webhook) ChangeThingState(c *gin.Context) { + thing, shouldReturn := validateUserAndThing(c, h) + if shouldReturn { + return + } + addRemoveRaw := c.Query("op") + setRaw := c.Query("set") + + if addRemoveRaw == "" && setRaw == "" { + c.JSON(400, gin.H{"error": "Invalid increment value"}) + return + } + var xValue int + var err error + if addRemoveRaw != "" { + xValue, err = strconv.Atoi(addRemoveRaw) + if err != nil { + c.JSON(400, gin.H{"error": "Invalid increment value"}) + return + } + currentState, err := strconv.Atoi(thing.State) + if err != nil { + c.JSON(400, gin.H{"error": "Invalid state for thing"}) + return + } + newState := currentState + xValue + thing.State = strconv.Itoa(newState) + } + if setRaw != "" { + thing.State = setRaw + } + + if !isValidThingState(thing) { + c.JSON(400, gin.H{"error": "Invalid state for thing"}) + return + } + if err := h.thingRepo.UpdateThingState(c, thing); err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return + } + + shouldReturn1 := WebhookEvaluateTriggerAndScheduleDueDate(h, c, thing) + if shouldReturn1 { + return + } + + c.JSON(200, gin.H{"state": thing.State}) +} + +func WebhookEvaluateTriggerAndScheduleDueDate(h *Webhook, c *gin.Context, thing *tModel.Thing) bool { + // handler should be interface to not duplicate both WebhookEvaluateTriggerAndScheduleDueDate and EvaluateTriggerAndScheduleDueDate + // this is bad code written Saturday at 2:25 AM + + log := logging.FromContext(c) + + thingChores, err := h.tRepo.GetThingChoresByThingId(c, thing.ID) + if err != nil { + c.JSON(500, gin.H{"error": err.Error()}) + return true + } + for _, tc := range thingChores { + triggered := EvaluateThingChore(tc, thing.State) + if triggered { + errSave := h.choreRepo.SetDueDate(c, tc.ChoreID, time.Now().UTC()) + if errSave != nil { + log.Error("Error setting due date for chore ", errSave) + log.Error("Chore ID ", tc.ChoreID, " Thing ID ", thing.ID, " State ", thing.State) + } + } + + } + return false +} + +func validateUserAndThing(c *gin.Context, h *Webhook) (*tModel.Thing, bool) { + apiToken := c.GetHeader("secretkey") + if apiToken == "" { + c.JSON(401, gin.H{"error": "Unauthorized"}) + return nil, true + } + thingID, err := strconv.Atoi(c.Param("id")) + if err != nil { + c.JSON(400, gin.H{"error": err.Error()}) + return nil, true + } + user, err := h.userRepo.GetUserByToken(c, apiToken) + if err != nil { + c.JSON(401, gin.H{"error": "Unauthorized"}) + return nil, true + } + thing, err := h.thingRepo.GetThingByID(c, thingID) + if err != nil { + c.JSON(400, gin.H{"error": "Invalid thing id"}) + return nil, true + } + if thing.UserID != user.ID { + c.JSON(401, gin.H{"error": "Unauthorized"}) + return nil, true + } + return thing, false +} + +func Webhooks(cfg *config.Config, w *Webhook, r *gin.Engine, auth *jwt.GinJWTMiddleware) { + + thingsAPI := r.Group("webhooks/things") + + thingsAPI.Use(utils.TimeoutMiddleware(cfg.Server.WriteTimeout)) + { + thingsAPI.GET("/:id/state/change", w.ChangeThingState) + thingsAPI.GET("/:id/state", w.UpdateThingState) + } + +} diff --git a/internal/user/handler.go b/internal/user/handler.go new file mode 100644 index 0000000..0eee6f2 --- /dev/null +++ b/internal/user/handler.go @@ -0,0 +1,511 @@ +package user + +import ( + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "fmt" + "html" + "net/http" + "time" + + auth "donetick.com/core/internal/authorization" + cModel "donetick.com/core/internal/circle/model" + cRepo "donetick.com/core/internal/circle/repo" + "donetick.com/core/internal/email" + uModel "donetick.com/core/internal/user/model" + uRepo "donetick.com/core/internal/user/repo" + "donetick.com/core/internal/utils" + "donetick.com/core/logging" + jwt "github.com/appleboy/gin-jwt/v2" + "github.com/gin-gonic/gin" + limiter "github.com/ulule/limiter/v3" + "google.golang.org/api/googleapi" + "google.golang.org/api/oauth2/v1" +) + +type Handler struct { + userRepo *uRepo.UserRepository + circleRepo *cRepo.CircleRepository + jwtAuth *jwt.GinJWTMiddleware + email *email.EmailSender +} + +func NewHandler(ur *uRepo.UserRepository, cr *cRepo.CircleRepository, jwtAuth *jwt.GinJWTMiddleware, email *email.EmailSender) *Handler { + return &Handler{ + userRepo: ur, + circleRepo: cr, + jwtAuth: jwtAuth, + email: email, + } +} + +func (h *Handler) GetAllUsers() gin.HandlerFunc { + return func(c *gin.Context) { + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting current user", + }) + return + } + + users, err := h.userRepo.GetAllUsers(c, currentUser.CircleID) + if err != nil { + c.JSON(500, gin.H{ + "error": "Error getting users", + }) + return + } + + c.JSON(200, gin.H{ + "res": users, + }) + } +} + +func (h *Handler) signUp(c *gin.Context) { + + type SignUpReq struct { + Username string `json:"username" binding:"required,min=4,max=20"` + Password string `json:"password" binding:"required,min=8,max=45"` + DisplayName string `json:"displayName"` + } + var signupReq SignUpReq + if err := c.BindJSON(&signupReq); err != nil { + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + if signupReq.DisplayName == "" { + signupReq.DisplayName = signupReq.Username + } + password, err := auth.EncodePassword(signupReq.Password) + signupReq.Username = html.EscapeString(signupReq.Username) + signupReq.DisplayName = html.EscapeString(signupReq.DisplayName) + + if err != nil { + c.JSON(500, gin.H{ + "error": "Error encoding password", + }) + return + } + var insertedUser *uModel.User + if insertedUser, err = h.userRepo.CreateUser(c, &uModel.User{ + Username: signupReq.Username, + Password: password, + DisplayName: signupReq.DisplayName, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + }); err != nil { + c.JSON(500, gin.H{ + "error": "Error creating user", + }) + return + } + // var userCircle *circle.Circle + // var userRole string + userCircle, err := h.circleRepo.CreateCircle(c, &cModel.Circle{ + Name: signupReq.DisplayName + "'s circle", + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + InviteCode: utils.GenerateInviteCode(c), + }) + + if err != nil { + c.JSON(500, gin.H{ + "error": "Error creating circle", + }) + return + } + + if err := h.circleRepo.AddUserToCircle(c, &cModel.UserCircle{ + UserID: insertedUser.ID, + CircleID: userCircle.ID, + Role: "admin", + IsActive: true, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + }); err != nil { + c.JSON(500, gin.H{ + "error": "Error adding user to circle", + }) + return + } + insertedUser.CircleID = userCircle.ID + if err := h.userRepo.UpdateUser(c, insertedUser); err != nil { + c.JSON(500, gin.H{ + "error": "Error updating user", + }) + return + } + + c.JSON(201, gin.H{}) +} + +func (h *Handler) GetUserProfile(c *gin.Context) { + user, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting user", + }) + return + } + c.JSON(200, gin.H{ + "res": user, + }) +} + +func (h *Handler) thirdPartyAuthCallback(c *gin.Context) { + + // read :provider from path param, if param is google check the token with google if it's valid and fetch the user details: + logger := logging.FromContext(c) + provider := c.Param("provider") + logger.Infow("account.handler.thirdPartyAuthCallback", "provider", provider) + + if provider == "google" { + c.Set("auth_provider", "3rdPartyAuth") + type OAuthRequest struct { + Token string `json:"token" binding:"required"` + Provider string `json:"provider" binding:"required"` + } + var body OAuthRequest + if err := c.ShouldBindJSON(&body); err != nil { + logger.Errorw("account.handler.thirdPartyAuthCallback failed to bind", "err", err) + c.JSON(http.StatusBadRequest, gin.H{ + "error": "Invalid request", + }) + return + } + + // logger.Infow("account.handler.thirdPartyAuthCallback", "token", token) + service, err := oauth2.New(http.DefaultClient) + + // tokenInfo, err := service.Tokeninfo().AccessToken(token).Do() + userinfo, err := service.Userinfo.Get().Do(googleapi.QueryParameter("access_token", body.Token)) + logger.Infow("account.handler.thirdPartyAuthCallback", "tokenInfo", userinfo) + if err != nil { + logger.Errorw("account.handler.thirdPartyAuthCallback failed to get token info", "err", err) + c.JSON(http.StatusBadRequest, gin.H{ + "error": "Invalid token", + }) + return + } + + acc, err := h.userRepo.FindByEmail(c, userinfo.Email) + + if err != nil { + // create a random password for the user using crypto/rand: + password := auth.GenerateRandomPassword(12) + encodedPassword, err := auth.EncodePassword(password) + acc = &uModel.User{ + Username: userinfo.Id, + Email: userinfo.Email, + Image: userinfo.Picture, + Password: encodedPassword, + DisplayName: userinfo.GivenName, + Provider: 2, + } + createdUser, err := h.userRepo.CreateUser(c, acc) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{ + "error": "Unable to create user", + }) + return + + } + // Create Circle for the user: + userCircle, err := h.circleRepo.CreateCircle(c, &cModel.Circle{ + Name: userinfo.GivenName + "'s circle", + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + InviteCode: utils.GenerateInviteCode(c), + }) + + if err != nil { + c.JSON(500, gin.H{ + "error": "Error creating circle", + }) + return + } + + if err := h.circleRepo.AddUserToCircle(c, &cModel.UserCircle{ + UserID: createdUser.ID, + CircleID: userCircle.ID, + Role: "admin", + IsActive: true, + CreatedAt: time.Now(), + UpdatedAt: time.Now(), + }); err != nil { + c.JSON(500, gin.H{ + "error": "Error adding user to circle", + }) + return + } + createdUser.CircleID = userCircle.ID + if err := h.userRepo.UpdateUser(c, createdUser); err != nil { + c.JSON(500, gin.H{ + "error": "Error updating user", + }) + return + } + } + // use auth to generate a token for the user: + c.Set("user_account", acc) + h.jwtAuth.Authenticator(c) + tokenString, expire, err := h.jwtAuth.TokenGenerator(acc) + if err != nil { + logger.Errorw("Unable to Generate a Token") + c.JSON(http.StatusInternalServerError, gin.H{ + "error": "Unable to Generate a Token", + }) + return + } + c.JSON(http.StatusOK, gin.H{"token": tokenString, "expire": expire}) + return + } +} + +func (h *Handler) resetPassword(c *gin.Context) { + log := logging.FromContext(c) + type ResetPasswordReq struct { + Email string `json:"email" binding:"required,email"` + } + var req ResetPasswordReq + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{ + "error": "Invalid request", + }) + return + } + user, err := h.userRepo.FindByEmail(c, req.Email) + if err != nil { + c.JSON(http.StatusNotFound, gin.H{ + "error": "User not found", + }) + return + } + if user.Provider != 0 { + // user create account thought login with Gmail. they can reset the password they just need to login with google again + c.JSON( + http.StatusForbidden, + gin.H{ + "error": "User account created with google login. Please login with google", + }, + ) + return + } + // generate a random password: + token, err := auth.GenerateEmailResetToken(c) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{ + "error": "Unable to generate token", + }) + return + } + + err = h.userRepo.SetPasswordResetToken(c, req.Email, token) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{ + "error": "Unable to generate password", + }) + return + } + // send an email to the user with the new password: + err = h.email.SendResetPasswordEmail(c, req.Email, token) + if err != nil { + log.Errorw("account.handler.resetPassword failed to send email", "err", err) + c.JSON(http.StatusInternalServerError, gin.H{ + "error": "Unable to send email", + }) + return + } + + // send an email to the user with the new password: + c.JSON(http.StatusOK, gin.H{}) +} + +func (h *Handler) updateUserPassword(c *gin.Context) { + logger := logging.FromContext(c) + // read the code from query param: + code := c.Query("c") + email, code, err := email.DecodeEmailAndCode(code) + if err != nil { + logger.Errorw("account.handler.verify failed to decode email and code", "err", err) + c.JSON(http.StatusBadRequest, gin.H{ + "error": "Invalid code", + }) + return + + } + // read password from body: + type RequestBody struct { + Password string `json:"password" binding:"required,min=8,max=32"` + } + var body RequestBody + if err := c.ShouldBindJSON(&body); err != nil { + logger.Errorw("user.handler.resetAccountPassword failed to bind", "err", err) + c.JSON(http.StatusBadRequest, gin.H{ + "error": "Invalid request", + }) + return + + } + password, err := auth.EncodePassword(body.Password) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{ + "error": "Unable to process password", + }) + return + } + + err = h.userRepo.UpdatePasswordByToken(c.Request.Context(), email, code, password) + if err != nil { + logger.Errorw("account.handler.resetAccountPassword failed to reset password", "err", err) + c.JSON(http.StatusInternalServerError, gin.H{ + "error": "Unable to reset password", + }) + return + } + c.JSON(http.StatusOK, gin.H{}) + +} + +func (h *Handler) UpdateUserDetails(c *gin.Context) { + type UpdateUserReq struct { + DisplayName *string `json:"displayName" binding:"omitempty"` + ChatID *int64 `json:"chatID" binding:"omitempty"` + Image *string `json:"image" binding:"omitempty"` + } + user, ok := auth.CurrentUser(c) + if !ok { + c.JSON(500, gin.H{ + "error": "Error getting user", + }) + return + } + var req UpdateUserReq + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(400, gin.H{ + "error": "Invalid request", + }) + return + } + // update non-nil fields: + if req.DisplayName != nil { + user.DisplayName = *req.DisplayName + } + if req.ChatID != nil { + user.ChatID = *req.ChatID + } + if req.Image != nil { + user.Image = *req.Image + } + + if err := h.userRepo.UpdateUser(c, user); err != nil { + c.JSON(500, gin.H{ + "error": "Error updating user", + }) + return + } + c.JSON(200, user) +} + +func (h *Handler) CreateLongLivedToken(c *gin.Context) { + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get current user"}) + return + } + type TokenRequest struct { + Name string `json:"name" binding:"required"` + } + var req TokenRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request"}) + return + } + + // Step 1: Generate a secure random number + randomBytes := make([]byte, 16) // 128 bits are enough for strong randomness + _, err := rand.Read(randomBytes) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate random part of the token"}) + return + } + + timestamp := time.Now().Unix() + hashInput := fmt.Sprintf("%s:%d:%x", currentUser.Username, timestamp, randomBytes) + hash := sha256.Sum256([]byte(hashInput)) + + token := hex.EncodeToString(hash[:]) + + tokenModel, err := h.userRepo.StoreAPIToken(c, currentUser.ID, req.Name, token) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to store the token"}) + return + } + + c.JSON(http.StatusOK, gin.H{"res": tokenModel}) +} + +func (h *Handler) GetAllUserToken(c *gin.Context) { + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get current user"}) + return + } + + tokens, err := h.userRepo.GetAllUserTokens(c, currentUser.ID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get user tokens"}) + return + } + + c.JSON(http.StatusOK, gin.H{"res": tokens}) + +} + +func (h *Handler) DeleteUserToken(c *gin.Context) { + currentUser, ok := auth.CurrentUser(c) + if !ok { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get current user"}) + return + } + + tokenID := c.Param("id") + + err := h.userRepo.DeleteAPIToken(c, currentUser.ID, tokenID) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete the token"}) + return + } + + c.JSON(http.StatusOK, gin.H{}) +} + +func Routes(router *gin.Engine, h *Handler, auth *jwt.GinJWTMiddleware, limiter *limiter.Limiter) { + + userRoutes := router.Group("users") + userRoutes.Use(auth.MiddlewareFunc(), utils.RateLimitMiddleware(limiter)) + { + userRoutes.GET("/", h.GetAllUsers()) + userRoutes.GET("/profile", h.GetUserProfile) + userRoutes.PUT("", h.UpdateUserDetails) + userRoutes.POST("/tokens", h.CreateLongLivedToken) + userRoutes.GET("/tokens", h.GetAllUserToken) + userRoutes.DELETE("/tokens/:id", h.DeleteUserToken) + } + + authRoutes := router.Group("auth") + authRoutes.Use(utils.RateLimitMiddleware(limiter)) + { + authRoutes.POST("/", h.signUp) + authRoutes.POST("login", auth.LoginHandler) + authRoutes.GET("refresh", auth.RefreshHandler) + authRoutes.POST("/:provider/callback", h.thirdPartyAuthCallback) + authRoutes.POST("reset", h.resetPassword) + authRoutes.POST("password", h.updateUserPassword) + } +} diff --git a/internal/user/model/model.go b/internal/user/model/model.go new file mode 100644 index 0000000..4874ac1 --- /dev/null +++ b/internal/user/model/model.go @@ -0,0 +1,38 @@ +package user + +import "time" + +type User struct { + ID int `json:"id" gorm:"primary_key"` // Unique identifier + DisplayName string `json:"displayName" gorm:"column:display_name"` // Display name + Username string `json:"username" gorm:"column:username;unique"` // Username (unique) + Email string `json:"email" gorm:"column:email;unique"` // Email (unique) + Provider int `json:"provider" gorm:"column:provider"` // Provider + Password string `json:"-" gorm:"column:password"` // Password + CircleID int `json:"circleID" gorm:"column:circle_id"` // Circle ID + ChatID int64 `json:"chatID" gorm:"column:chat_id"` // Telegram chat ID + Image string `json:"image" gorm:"column:image"` // Image + CreatedAt time.Time `json:"created_at" gorm:"column:created_at"` // Created at + UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"` // Updated at + Disabled bool `json:"disabled" gorm:"column:disabled"` // Disabled + // Email string `json:"email" gorm:"column:email"` // Email + CustomerID *string `gorm:"column:customer_id;<-:false"` // read one column + Subscription *string `json:"subscription" gorm:"column:subscription;<-:false"` // read one column + Expiration *string `json:"expiration" gorm:"column:expiration;<-:false"` // read one column +} + +type UserPasswordReset struct { + ID int `gorm:"column:id"` + UserID int `gorm:"column:user_id"` + Email string `gorm:"column:email"` + Token string `gorm:"column:token"` + ExpirationDate time.Time `gorm:"column:expiration_date"` +} + +type APIToken struct { + ID int `json:"id" gorm:"primary_key"` // Unique identifier + Name string `json:"name" gorm:"column:name;unique"` // Name (unique) + UserID int `json:"userId" gorm:"column:user_id;index"` // Index on userID + Token string `json:"token" gorm:"column:token;index"` // Index on token + CreatedAt time.Time `json:"createdAt" gorm:"column:created_at"` +} diff --git a/internal/user/repo/repository.go b/internal/user/repo/repository.go new file mode 100644 index 0000000..fa53753 --- /dev/null +++ b/internal/user/repo/repository.go @@ -0,0 +1,160 @@ +package user + +import ( + "context" + "fmt" + "time" + + "donetick.com/core/config" + uModel "donetick.com/core/internal/user/model" + "donetick.com/core/logging" + "gorm.io/gorm" +) + +type IUserRepository interface { + GetUserByUsername(username string) (*uModel.User, error) + GetUser(id int) (*uModel.User, error) + GetAllUsers() ([]*uModel.User, error) + CreateUser(user *uModel.User) error + UpdateUser(user *uModel.User) error + UpdateUserCircle(userID, circleID int) error + FindByEmail(email string) (*uModel.User, error) +} + +type UserRepository struct { + db *gorm.DB + isDonetickDotCom bool +} + +func NewUserRepository(db *gorm.DB, cfg *config.Config) *UserRepository { + return &UserRepository{db, cfg.IsDoneTickDotCom} +} + +func (r *UserRepository) GetAllUsers(c context.Context, circleID int) ([]*uModel.User, error) { + var users []*uModel.User + if err := r.db.WithContext(c).Where("circle_id = ?", circleID).Find(&users).Error; err != nil { + return nil, err + } + return users, nil +} + +func (r *UserRepository) GetAllUsersForSystemOnly(c context.Context) ([]*uModel.User, error) { + var users []*uModel.User + if err := r.db.WithContext(c).Find(&users).Error; err != nil { + return nil, err + } + return users, nil +} +func (r *UserRepository) CreateUser(c context.Context, user *uModel.User) (*uModel.User, error) { + if err := r.db.WithContext(c).Save(user).Error; err != nil { + return nil, err + } + return user, nil +} +func (r *UserRepository) GetUserByUsername(c context.Context, username string) (*uModel.User, error) { + var user *uModel.User + if r.isDonetickDotCom { + if err := r.db.WithContext(c).Table("users u").Select("u.*, ss.status as subscription, ss.expired_at as expiration").Joins("left join stripe_customers sc on sc.user_id = u.id ").Joins("left join stripe_subscriptions ss on sc.customer_id = ss.customer_id").Where("username = ?", username).First(&user).Error; err != nil { + return nil, err + } + } else { + if err := r.db.WithContext(c).Where("username = ?", username).First(&user).Error; err != nil { + return nil, err + } + } + + return user, nil +} + +func (r *UserRepository) UpdateUser(c context.Context, user *uModel.User) error { + return r.db.WithContext(c).Save(user).Error +} + +func (r *UserRepository) UpdateUserCircle(c context.Context, userID, circleID int) error { + return r.db.WithContext(c).Model(&uModel.User{}).Where("id = ?", userID).Update("circle_id", circleID).Error +} + +func (r *UserRepository) FindByEmail(c context.Context, email string) (*uModel.User, error) { + var user *uModel.User + if err := r.db.WithContext(c).Where("email = ?", email).First(&user).Error; err != nil { + return nil, err + } + return user, nil +} + +func (r *UserRepository) SetPasswordResetToken(c context.Context, email, token string) error { + // confirm user exists with email: + user, err := r.FindByEmail(c, email) + if err != nil { + return err + } + // save new token: + if err := r.db.WithContext(c).Model(&uModel.UserPasswordReset{}).Save(&uModel.UserPasswordReset{ + UserID: user.ID, + Token: token, + Email: email, + ExpirationDate: time.Now().UTC().Add(time.Hour * 24), + }).Error; err != nil { + return err + } + return nil +} + +func (r *UserRepository) UpdatePasswordByToken(ctx context.Context, email string, token string, password string) error { + logger := logging.FromContext(ctx) + + logger.Debugw("account.db.UpdatePasswordByToken", "email", email) + upr := &uModel.UserPasswordReset{ + Email: email, + Token: token, + } + result := r.db.WithContext(ctx).Where("email = ?", email).Where("token = ?", token).Delete(upr) + if result.RowsAffected <= 0 { + return fmt.Errorf("invalid token") + } + // find account by email and update password: + chain := r.db.WithContext(ctx).Model(&uModel.User{}).Where("email = ?", email).UpdateColumns(map[string]interface{}{"password": password}) + if chain.Error != nil { + return chain.Error + } + if chain.RowsAffected == 0 { + return fmt.Errorf("account not found") + } + + return nil +} + +func (r *UserRepository) StoreAPIToken(c context.Context, userID int, name string, tokenCode string) (*uModel.APIToken, error) { + token := &uModel.APIToken{ + UserID: userID, + Name: name, + Token: tokenCode, + CreatedAt: time.Now().UTC(), + } + if err := r.db.WithContext(c).Model(&uModel.APIToken{}).Save( + token).Error; err != nil { + return nil, err + + } + return token, nil +} + +func (r *UserRepository) GetUserByToken(c context.Context, token string) (*uModel.User, error) { + var user *uModel.User + if err := r.db.WithContext(c).Table("users u").Select("u.*").Joins("left join api_tokens at on at.user_id = u.id").Where("at.token = ?", token).First(&user).Error; err != nil { + return nil, err + } + return user, nil +} + +func (r *UserRepository) GetAllUserTokens(c context.Context, userID int) ([]*uModel.APIToken, error) { + var tokens []*uModel.APIToken + if err := r.db.WithContext(c).Where("user_id = ?", userID).Find(&tokens).Error; err != nil { + return nil, err + } + return tokens, nil +} + +func (r *UserRepository) DeleteAPIToken(c context.Context, userID int, tokenID string) error { + return r.db.WithContext(c).Where("id = ? AND user_id = ?", tokenID, userID).Delete(&uModel.APIToken{}).Error +} diff --git a/internal/utils/key_generator.go b/internal/utils/key_generator.go new file mode 100644 index 0000000..1f88be9 --- /dev/null +++ b/internal/utils/key_generator.go @@ -0,0 +1,28 @@ +package utils + +import ( + "encoding/base64" + + crand "crypto/rand" + + "donetick.com/core/logging" + "github.com/gin-gonic/gin" +) + +func GenerateInviteCode(c *gin.Context) string { + logger := logging.FromContext(c) + // Define the length of the token (in bytes). For example, 32 bytes will result in a 44-character base64-encoded token. + tokenLength := 12 + + // Generate a random byte slice. + tokenBytes := make([]byte, tokenLength) + _, err := crand.Read(tokenBytes) + if err != nil { + logger.Errorw("utility.GenerateEmailResetToken failed to generate random bytes", "err", err) + } + + // Encode the byte slice to a base64 string. + token := base64.URLEncoding.EncodeToString(tokenBytes) + + return token +} diff --git a/internal/utils/middleware.go b/internal/utils/middleware.go new file mode 100644 index 0000000..f31184b --- /dev/null +++ b/internal/utils/middleware.go @@ -0,0 +1,72 @@ +package utils + +import ( + "context" + "net/http" + "strconv" + "time" + + "donetick.com/core/config" + "github.com/gin-gonic/gin" + "github.com/ulule/limiter/v3" + "github.com/ulule/limiter/v3/drivers/store/memory" +) + +const ( + XRequestIdKey = "X-Request-ID" // request id header key +) + +func NewRateLimiter(cfg *config.Config) *limiter.Limiter { + + store := memory.NewStore() + + // rate, err := limiter.NewRateFromFormatted("10-H") + rate := limiter.Rate{ + Period: cfg.Server.RatePeriod, + Limit: int64(cfg.Server.RateLimit), + } + + // Then, create the limiter instance which takes the store and the rate as arguments. + // Now, you can give this instance to any supported middleware. + return limiter.New(store, rate) + +} + +// wrapper ratelimiter and have it as a middkewatr function: +func RateLimitMiddleware(limiter *limiter.Limiter) gin.HandlerFunc { + return func(c *gin.Context) { + // Use the IP as the key, which is the client IP. + // And set the expiration time to 10 seconds. + context, err := limiter.Get(c.Request.Context(), c.ClientIP()) + if err != nil { + panic(err) // perhaps handle this nicer + } + // Check if the client is ratelimited. + if context.Reached { + c.AbortWithStatusJSON(http.StatusTooManyRequests, gin.H{"message": "Too many requests"}) + return + } + // Add a header in response to inform the current quota. + c.Header("X-RateLimit-Limit", strconv.FormatInt(context.Limit, 10)) + // Add a header in response to inform the remaining quota. + c.Header("X-RateLimit-Remaining", strconv.FormatInt(context.Remaining, 10)) + // Add a header in response to inform the time to wait before retry. + c.Header("X-RateLimit-Reset", strconv.FormatInt(context.Reset, 10)) + c.Next() + } +} + +func TimeoutMiddleware(timeout time.Duration) gin.HandlerFunc { + return func(c *gin.Context) { + ctx, cancel := context.WithTimeout(c.Request.Context(), timeout) + + defer func() { + if ctx.Err() == context.DeadlineExceeded { + c.AbortWithStatus(http.StatusGatewayTimeout) + } + cancel() + }() + c.Request = c.Request.WithContext(ctx) + c.Next() + } +} diff --git a/logging/logging.go b/logging/logging.go new file mode 100644 index 0000000..59916b4 --- /dev/null +++ b/logging/logging.go @@ -0,0 +1,95 @@ +package logging + +import ( + "context" + "sync" + + "github.com/gin-gonic/gin" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +type contextKey = string + +const loggerKey = contextKey("logger") + +var ( + defaultLogger *zap.SugaredLogger + defaultLoggerOnce sync.Once +) + +var conf = &Config{ + Encoding: "console", + Level: zapcore.InfoLevel, + Development: true, +} + +type Config struct { + Encoding string + Level zapcore.Level + Development bool +} + +// SetConfig sets given logging configs for DefaultLogger's logger. +// Must set configs before calling DefaultLogger() +func SetConfig(c *Config) { + conf = &Config{ + Encoding: c.Encoding, + Level: c.Level, + Development: c.Development, + } +} + +func SetLevel(l zapcore.Level) { + conf.Level = l +} + +// NewLogger creates a new logger with the given log level +func NewLogger(conf *Config) *zap.SugaredLogger { + ec := zap.NewProductionEncoderConfig() + ec.EncodeTime = zapcore.ISO8601TimeEncoder + cfg := zap.Config{ + Encoding: conf.Encoding, + EncoderConfig: ec, + Level: zap.NewAtomicLevelAt(conf.Level), + Development: conf.Development, + OutputPaths: []string{"stdout"}, + ErrorOutputPaths: []string{"stderr"}, + } + logger, err := cfg.Build() + if err != nil { + logger = zap.NewNop() + } + return logger.Sugar() +} + +// DefaultLogger returns the default logger for the package. +func DefaultLogger() *zap.SugaredLogger { + defaultLoggerOnce.Do(func() { + defaultLogger = NewLogger(conf) + }) + return defaultLogger +} + +// WithLogger creates a new context with the provided logger attached. +func WithLogger(ctx context.Context, logger *zap.SugaredLogger) context.Context { + if gCtx, ok := ctx.(*gin.Context); ok { + ctx = gCtx.Request.Context() + } + return context.WithValue(ctx, loggerKey, logger) +} + +// FromContext returns the logger stored in the context. If no such logger +// exists, a default logger is returned. +func FromContext(ctx context.Context) *zap.SugaredLogger { + if ctx == nil { + return DefaultLogger() + } + if gCtx, ok := ctx.(*gin.Context); ok && gCtx != nil { + ctx = gCtx.Request.Context() + } + if logger, ok := ctx.Value(loggerKey).(*zap.SugaredLogger); ok { + return logger + } + return DefaultLogger() +} @@ -0,0 +1,139 @@ +package main + +import ( + "context" + "fmt" + "log" + "net/http" + + "donetick.com/core/config" + "github.com/gin-contrib/cors" + "github.com/gin-gonic/gin" + "go.uber.org/fx" + "go.uber.org/zap/zapcore" + "gorm.io/gorm" + + auth "donetick.com/core/internal/authorization" + "donetick.com/core/internal/chore" + chRepo "donetick.com/core/internal/chore/repo" + "donetick.com/core/internal/circle" + cRepo "donetick.com/core/internal/circle/repo" + "donetick.com/core/internal/database" + "donetick.com/core/internal/email" + notifier "donetick.com/core/internal/notifier" + nRepo "donetick.com/core/internal/notifier/repo" + nps "donetick.com/core/internal/notifier/service" + telegram "donetick.com/core/internal/notifier/telegram" + "donetick.com/core/internal/thing" + tRepo "donetick.com/core/internal/thing/repo" + "donetick.com/core/internal/user" + uRepo "donetick.com/core/internal/user/repo" + "donetick.com/core/internal/utils" + "donetick.com/core/logging" + "donetick.com/core/migration" +) + +func main() { + logging.SetConfig(&logging.Config{ + Encoding: "console", + Level: zapcore.Level(zapcore.DebugLevel), + Development: true, + }) + + app := fx.New( + fx.Supply(config.LoadConfig()), + fx.Supply(logging.DefaultLogger().Desugar()), + + // fx.Provide(config.NewConfig), + fx.Provide(auth.NewAuthMiddleware), + + // fx.Provide(NewBot), + fx.Provide(database.NewDatabase), + fx.Provide(chRepo.NewChoreRepository), + fx.Provide(chore.NewHandler), + fx.Provide(uRepo.NewUserRepository), + fx.Provide(user.NewHandler), + fx.Provide(cRepo.NewCircleRepository), + fx.Provide(circle.NewHandler), + + fx.Provide(nRepo.NewNotificationRepository), + fx.Provide(nps.NewNotificationPlanner), + + // add notifier + fx.Provide(telegram.NewTelegramNotifier), + + // Rate limiter + fx.Provide(utils.NewRateLimiter), + + // add email sender: + fx.Provide(email.NewEmailSender), + // add handlers also + fx.Provide(newServer), + fx.Provide(notifier.NewScheduler), + + // things + fx.Provide(tRepo.NewThingRepository), + + fx.Provide(thing.NewWebhook), + fx.Provide(thing.NewHandler), + + // fx.Invoke(RunApp), + fx.Invoke( + chore.Routes, + user.Routes, + circle.Routes, + thing.Routes, + thing.Webhooks, + + func(r *gin.Engine) {}, + ), + ) + + if err := app.Err(); err != nil { + log.Fatal(err) + } + + app.Run() + +} + +func newServer(lc fx.Lifecycle, cfg *config.Config, db *gorm.DB, notifier *notifier.Scheduler) *gin.Engine { + gin.SetMode(gin.DebugMode) + // log when http request is made: + + r := gin.New() + srv := &http.Server{ + Addr: fmt.Sprintf(":%d", cfg.Server.Port), + Handler: r, + ReadTimeout: cfg.Server.ReadTimeout, + WriteTimeout: cfg.Server.WriteTimeout, + } + config := cors.DefaultConfig() + config.AllowAllOrigins = true + config.AllowCredentials = true + config.AddAllowHeaders("Authorization", "secretkey") + r.Use(cors.New(config)) + + lc.Append(fx.Hook{ + OnStart: func(context.Context) error { + if cfg.Database.Migration { + migration.Migration(db) + } + notifier.Start(context.Background()) + go func() { + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + log.Fatalf("listen: %s\n", err) + } + }() + return nil + }, + OnStop: func(context.Context) error { + if err := srv.Shutdown(context.Background()); err != nil { + log.Fatalf("Server Shutdown: %s", err) + } + return nil + }, + }) + + return r +} diff --git a/migration/migration.go b/migration/migration.go new file mode 100644 index 0000000..ee829a8 --- /dev/null +++ b/migration/migration.go @@ -0,0 +1,29 @@ +package migration + +import ( + chModel "donetick.com/core/internal/chore/model" + cModel "donetick.com/core/internal/circle/model" + nModel "donetick.com/core/internal/notifier/model" + tModel "donetick.com/core/internal/thing/model" + uModel "donetick.com/core/internal/user/model" + "gorm.io/gorm" +) + +func Migration(db *gorm.DB) error { + if err := db.AutoMigrate(uModel.User{}, chModel.Chore{}, + chModel.ChoreHistory{}, + cModel.Circle{}, + cModel.UserCircle{}, + chModel.ChoreAssignees{}, + nModel.Notification{}, + uModel.UserPasswordReset{}, + tModel.Thing{}, + tModel.ThingChore{}, + tModel.ThingHistory{}, + uModel.APIToken{}, + ); err != nil { + return err + } + + return nil +} |