diff --git a/.prettierrc.js b/.prettierrc.js index 1f50f3e..3c2169e 100644 --- a/.prettierrc.js +++ b/.prettierrc.js @@ -1,10 +1,7 @@ "use strict"; module.exports = { - plugins: [ - "@trivago/prettier-plugin-sort-imports", - "prettier-plugin-tailwindcss", - ], - printWidth: 80, + plugins: ["@trivago/prettier-plugin-sort-imports", "prettier-plugin-tailwindcss"], + printWidth: 120, tabWidth: 2, useTabs: false, semi: true, @@ -31,6 +28,7 @@ module.exports = { "^~/(utils|hooks|context)/(.*)$", "^~/types/(.*)$", "^~/(config|styles)/(.*)$", + "^(config|actions)$", "^[./]", ], importOrderSeparation: true, diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3972c30 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) 2024 + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published + by the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index 36ff322..21d862f 100644 --- a/README.md +++ b/README.md @@ -1,201 +1,175 @@ -![next-gdrive-index](./public/og.png) +![banner](/public/og.png)

- Demo - · - Deploying Guide - · - FAQ + Demo Site + · + Deploy / Version Upgrade Guide + · + FAQ +

+

+ Demo version + Dev

-## Version 2 is here! +--- -It seems there are some bugs on mobile devices that prevent the files list from rendering properly. -So I will use this chance to upgrade the project to `Next.js 14`, use `shadcn/ui`, and also add some new features. + -There also some changes on the configuration file, so make sure to read the [Migration Guide](#migration-guide) if you're upgrading from version 1.x. +## Table of Contents -Here's what changed in version 2: - -### New Features - -- **Theme Select**, light mode? dark mode? you choose. -- **[shadcn/ui](https://ui.shadcn.com/)**, change the UI library to `shadcn/ui`. -- **Faster Response Time**, added cache to improve the response time. -- **Revalidate Data**, data fetching now utilizing revalidate. (can be changed from config file) - > You can manually revalidate the data by sending POST request to `/api/revalidate` with `Authorization` header set to `{{ process.env.SITE_PASSWORD }}`. - -### Changed - -- **General Layout**, New fresh look with `shadcn/ui`. -- **Download Link**, Added token that will be expired after x hour(s). (can be changed from config file) -- **Raw Link**, Raw link only available for image, video, and audio files. Raw link are recommended for hosting web project assets or comments on forum. -- **Footer**, now you can customize the footer from config file, also added support for Markdown. -- **Data Fetching**, now using `Server Actions` instead of `API Routes`. -- **Encryption**, moved to `Server Actions`. -- **Typescript Config**, target changed from `ES5` to `ES2021`. -- **Environment Variable**, now focus on Server Side Environment Variable. - - `NEXT_PUBLIC_ENCRYPTION_KEY` changed to `ENCRYPTION_KEY`. - - `NEXT_PUBLIC_SITE_PASSWORD` changed to `SITE_PASSWORD`. - - `MASTER_KEY` added. -- **Configuration File**, things are changed: - - `version` bumped to `2.0`. - - `masterKey` moved to `Environment Variable`. - - `apiConfig.revalidate` added. - - `siteConfig.siteNameTemplate` added. - - `siteConfig.siteAuthor` added. - - `siteConfig.robots` added. - - `siteConfig.footer` added. - - `siteConfig.defaultAccentColor` deprecated. - - `siteConfig.breadcrumbMax` added. - - `siteConfig.toaster` added. - - `siteConfig.navbarItems[number].icons` changed to `lucide icons`. - - `siteConfig.supports` added. - -### Fixed - -- Rendering issue on mobile devices. - -### Dependency Update - -- `@iconify/react` switched to `lucide-react`. -- `@mdx-js/loader` removed. -- `@mdx-js/react` removed. -- `@next/mdx` removed. -- `@popperjs/core` removed. -- `next` updated to `^14.1.4`. -- `next-seo` removed. -- `tailwind-merge` updated to `^2.2.2`. +- [What is this?](#what-is-this) +- [Why I made this?](#why-i-made-this) +- [Features](#features) +- [Known Issues](#known-issues) + - [File size limit](#file-size-limit) + - [No support for Google Docs, Sheets, and Slides](#no-support-for-google-docs-sheets-and-slides) + - [Can't seek on audio and video preview](#cant-seek-on-audio-and-video-preview) + - [Shared Drive is not supported](#shared-drive-is-not-supported) +- [Might be Implemented](#might-be-implemented) + - [Internationalization / i18n](#internationalization--i18n) + - [Multiple drive](#multiple-drive) + - [Authentication](#authentication) +- [Running on Local](#running-on-local) +- [How to Contribute](#how-to-contribute) +- [Support and Donations](#support-and-donations) +- [License](#license) ## What is this? -`next-gdrive-index` is an indexer for Google Drive, it's a simple project that I made to index my files in Google Drive. -It's aim to simplify the process of sharing files using Google Drive, and also implements some features that I think is useful for sharing files. +`next-gdrive-index` is a Google Drive directory index. +The aim of this project is to simplify the process of sharing files using Google Drive, and also add some features that _I think_ is useful when sharing a files. -This project are **HEAVILY INSPIRED** by [onedrive-vercel-index](https://github.com/spencerwooo/onedrive-vercel-index) by SpencerWooo. +> This project are **HEAVILY INSPIRED** by [onedrive-vercel-index](https://github.com/spencerwooo/onedrive-vercel-index) by [SpencerWooo](https://github.com/spencerwooo). -### Why I made this? +## Why I made this? -when I compare the price between these two services, Google Drive still cheaper than Onedrive. -For 100GB plan, Google Drive is IDR 269.000 / ~$18 USD annually, and Onedrive is IDR 319.000 / ~$21 USD annually. -For free plan, Google Drive offering 15GB of storage, and Onedrive offering 5GB of storage. +> **TLDR;** +> It is cheaper to use Google Drive than other similar service -I know there are a lot of people selling cheap edu account for Google Drive and Onedrive, but most of the time those account doesn't last long, especially Google Drive account. So I want to do it legit without buying cheap edu account or anything similar this time. +There are a lot cloud storage service like Onedrive, Dropbox, Mega, etc. +But, between all those service, I think Google Drive is a lot cheaper than others (at least in my region). + +Here are the pricing comparison between free and cheapest plan +_Price are converted to IDR, since it's easier for me to compare this using my own currency_ + +| Service | Free plan | Paid plan | Price | Price to Storage | Transfer Quota | +| :--------------- | :-------------- | :-------- | :--------------------- | :------------------------------------------ | :------------: | +| **Google Drive** | 15GB | 2TB | 135k IDR
~112k IDR | 14.8GB / 1k / mo
17.8GB / 1k / yr
| **X** | +| **Onedrive**\*\* | 5GB | 1TB | 96k IDR
80k IDR | 10.4GB / 1k / mo
12.5GB / 1k / yr | **X** | +| **Dropbox**\* | 2GB | 2TB | ~191k IDR
~159k IDR | 10.5GB / 1k / mo
12.5GB / 1k / yr | O | +| **MEGA** | **20GB** | 2TB | ~174k IDR
~145k IDR | 11.5GB / 1k / mo
13.8GB / 1k / yr | O | + +\* Price are in USD, and there are no regional price for IDR +\*\* There are no 2TB plan + +By using this data, I picked Google Drive instead other service. +I know there are a lot of people selling cheap education account especially for Google Drive and Onedrive, but most of the time those account doesn't last long. ## Features -- **Private Index**, lock the whole index site with password. -- **Folder and file protection**, you can protect your folder and files with password. -- **Readme file**, you can add readme file for your folder, so you can add some description for your folder. -- **File preview**, you can preview some file types directly from the browser, without downloading it first. +- **Private Index**, protect the whole site with a password +- **Folder and file protection**, protect certain path with a password +- **Readme file**, add description (or whatever) inside a readme to be rendered when you open the folder +- **File preview**, preview the file before download ( Preview file size limit can be adjusted ) - Image preview - Video preview - Audio preview - - Markdown preview - - PDF preview - - Document preview (docx, pptx, xlsx) - - Code preview - - Text preview + - Document preview + - Code / Text / Markdown preview - Manga preview (cbz) -- **File search**, you can search for files and folders easily. -- **Direct download**, you can download files directly from index site without opening Google Drive. -- **Raw file link**, you can use the raw file link for hosting your web project assets or comments on forum. +- **File search**, search by the file or folder name +- **Direct download**, download directly via API route instead of google drive link ( Size limit can be adjusted ) +- **Raw file link**, embed your media files +- **Light/Dark mode**, choose your side! +- **Customizable Theme**, we are using `shadcn/ui` now! you can customize your site [https;//drive-demo.mbaharip.com/deploy#theme] +- **Links**, add social, or information link on the navbar +- **Sponsors**, using this for thing for community? add a sponsor / donate button on your navbar! -## File Security - -> This only apply if `maxFileSize` is enabled. - -You need to set the file sharing permission to `Anyone with the link can view` for the files that you want to share. - -**Why?** because the download link will be redirected to the Google Drive download link, and it can only be accessed if the file is shared with `Anyone with the link can view` permission. - -If not, the download link will be redirected to the Google Drive web content link, and it can be accessed without sharing the file. - -But this might expose the file ID, so people might be able to access the files directly from Google Drive. (But I'm sure they can't access the folder itself, only the file that are being downloaded) - -## Known Issue +## Known Issues ### File size limit -> This only apply if you're using platform that have file size limit, like Vercel. -> If you're using VPS or other platform that doesn't have file size limit, you can disable `maxFileSize` inside config file. +> This only apply if `maxFileSize` is enabled / more than 0 -File size limit causing some files can't be previewed, and the download will be redirected to the raw file link. -**This won't be fixed**, because it's a limitation from the deployment platform itself. +You need to set the file sharing permission to `Anyone with the link can view` on the root folder. -### Long Response Time +**Why?** +The download link will be redirected if the file you're trying to download is bigger than the `maxFileSize`, and most of platform are limiting the response body size (ex: Vercel limit is 4MB). +If you don't set the permission, people can't access or download the file. -From version 2.0, We are using Cache to improve the response time. -It might take a long time for deep nested folders, but once the data is fetched, it will be cached and the response time will be faster. - -I also add [revalidate](https://nextjs.org/docs/app/building-your-application/data-fetching/fetching-caching-and-revalidating#revalidating-data) config on page file to 5 minutes. You can change the value inside `src/app/page.tsx` & `src/app/[...rest]/page.tsx`. - -~~The flow of the project are:~~ - -- ~~Validate the path is valid or not. (Only applied for `/...[path]`)~~ -- ~~Fetch the password, readme, and files from Google Drive.~~ -- ~~Show to the user.~~ - -~~So, if you have a lot of files in your Google Drive, it might take a long time to fetch all the files. -To improve the response time, I added a cache to the response, so the next time you access the same path, it will be faster.~~ - -~~ATM, it roughly take around 600 - 2 seconds to fetch all the data on my Google Drive.~~ - -### Can't seek on audio and video preview - -It looks like the audio and video preview can't seek, so you need to listen/watch from the beginning. -I'm still looking for a solution for this. - -### ~~Shared Drive is now supported~~ - -~~I don't have Google Shared Drive, so I can't test it and implement it.~~ -Implemented by [@loadingthedev](https://github.com/loadingthedev) [(PR #4)](https://github.com/mbahArip/next-gdrive-index/pull/4) +This will expose the file ID, and people can access the file directly from Google Drive. +But it only apply to the file, and they can't see or browse the folder directly from Google Drive. ### No support for Google Docs, Sheets, and Slides -For now, I don't have any plan to implement this, because I think it's not necessary. -All Google Drive files like Docs, Sheets, and Slides are hidden from the list. +For now, I don't have any plan to implement this, because I think it's not necessary. -**PR are welcome if you want to implement this.** +### ~~Can't seek on audio and video preview~~ -## Migration Guide +~~It looks like you can't seek the audio and video preview, so you need to listen / watch from the beginning.~~ +Fixed on v2.0.2 -If you're upgrading from version 1.x to version 2, there are some changes that you need to do: +### ~~Shared Drive is not supported~~ -### Configuration File +~~I don't have Shared Drive, so I can't test it and implement it~~ +Implemented by [@loadingthedev](https://github.com/loadingthedev) [(PR #4)](https://github.com/mbahArip/next-gdrive-index/pull/4) -> You can check the new Configuration Schema on `/src/schema.ts` +## Might be Implemented -There are some changes on the configuration file, here's the list of changes: +Here are things that I want, and might be implemented on the future -- `masterKey` **REMOVED**, we don't need this anymore +### Internationalization / i18n -- `apiConfig.rootFolder` **CHANGED**, you need to encrypt the folder ID on your localhost first - `http://localhost:3000/api/internal/encrypt?q={{ folderId }}` +It should be a good idea to have the site and deploying guide with multiple language support. -- `apiConfig.proxyThumbnail` **ADDED**, default value is `true` -- `siteConfig.siteNameTemplate` **ADDED**, default value is `%s - next-gdrive-index` -- `siteConfig.siteAuthor` **ADDED**, default value is `mbahArip` -- `siteConfig.robots` **ADDED**, default value is `noindex, nofollow` -- `siteConfig.footer` **ADDED**, default value is `Powered by next-gdrive-index` -- `siteConfig.defaultAccentColor` **REMOVED**, you can set the theme from `/src/app/globals.css` (more information about [shadcn/ui theme](https://ui.shadcn.com/docs/theming)) -- `siteConfig.breadcrumbMax` **ADDED**, default value is `3` -- `siteConfig.toaster` **ADDED**, default value is `{ position: "bottom-right', duration: 3000 }` -- `siteConfig.navbarItems[number].icons` **CHANGED**, you need to use [Lucide Icons](https://lucide.dev/icons) now -- `siteConfig.supports` **ADDED**, you can leave it empty if you don't want to use it +### Multiple drive -### Environment Variable +It's either from multiple Google Drive account with multiple Service Account, or a basic single Google Drive account with multiple root start point either in their own Drive or Shared Drive -Now all the environment variable are on the server side, so you need to change the environment variable: +### Authentication -- `NEXT_PUBLIC_ENCRYPTION_KEY` **CHANGED** to `ENCRYPTION_KEY` -- `NEXT_PUBLIC_SITE_PASSWORD` **CHANGED** to `SITE_PASSWORD` -- `NEXT_PUBLIC_VERCEL_URL` **CHANGED** to `NEXT_PUBLIC_DOMAIN` +Probably a good feature if you are a content creator that only want the one who subscribed to you get the files. +It might need a database, but idk if I can implement it without the need of database -## Sponsors and Donations +## Running on Local + +- **Clone the repository** + `git clone https://github.com/mbaharip/next-gdrive-index.git` + `cd next-gdrive-index` +- **Install required dependencies** + `npm install` + `yarn install` +- **Add environment file** + - **Using Configuration** + - Open [Deploy guide page](https://drive-demo.mbaharip.com/deploy#config) + - Scroll to the bottom to see the configuration form + - Fill out the form and download the file + - Extract the `.env` file to the root folder + - **Using example file** + - `cp .env.example .env` + - Fill out everything +- Run the app + `npm run dev` + `yarn dev` +- Check the app on `http://localhost:3000` + +## How to Contribute + +Want to add new feature or improve the existing one? or you find a bug and fixed it yourself? + +- Please check the issue tab first to see if someone already reporting a bug, or if you want to check any new feature / enhancement that not yet implemented +- Use code base from `v2` branch instead of the `main`, since it was made for development on current version +- Create a Pull Request, and wait for me checking your code + +## Support and Donations If you think I deserve it, you can support me by: - [Paypal (USD)](https://paypal.me/mbaharip) - [Ko-fi (USD)](https://ko-fi.com/mbaharip) - [Saweria (IDR)](https://saweria.co/mbaharip) + +## License + +This project is licensed under the AGPL-3.0 License - see the [LICENSE](LICENSE) file for details. diff --git a/components.json b/components.json index e048066..848837b 100644 --- a/components.json +++ b/components.json @@ -12,6 +12,6 @@ }, "aliases": { "components": "~/components", - "utils": "~/utils" + "utils": "~/utils/cn" } } diff --git a/data/mockFiles.ts b/data/mockFiles.ts deleted file mode 100644 index 6b435f9..0000000 --- a/data/mockFiles.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { IGDriveFiles } from "types/api/files"; -import { APIFilesResponse } from "types/api/response"; - -const mockFiles: APIFilesResponse = { - timestamp: Date.now(), - responseTime: 0, - folders: [], - files: [], - nextPageToken: "nextpageToken", - readmeExists: true, - bannerExists: true, - passwordExists: false, -}; -const mockFilesProtected: APIFilesResponse = { - timestamp: Date.now(), - responseTime: 0, - folders: [], - files: [], - nextPageToken: "nextpageToken", - readmeExists: true, - bannerExists: true, - passwordExists: true, -}; - -for (let i = 0; i < 10; i++) { - const folder: IGDriveFiles = { - mimeType: "application/vnd.google-apps.folder", - encryptedId: `encryptedId${i + 1}`, - name: `folder${i + 1}`, - trashed: false, - modifiedTime: new Date().toISOString(), - }; - const file: IGDriveFiles = { - mimeType: "application/vnd.google-apps.file", - encryptedId: `encryptedId${i + 1}`, - name: `file${i + 1}`, - trashed: false, - modifiedTime: new Date().toISOString(), - fileExtension: "txt", - encryptedWebContentLink: "encryptedWebContentLink", - size: Math.floor(Math.random() * 1000000000), - thumbnailLink: "/og.png", - imageMediaMetadata: - Math.random() > 0.5 - ? { - width: 1920, - height: 1080, - rotation: 0, - } - : null, - videoMediaMetadata: - Math.random() > 0.5 - ? { - width: 1920, - height: 1080, - durationMillis: 100000, - } - : null, - }; - - mockFiles.folders.push(folder); - mockFiles.files.push(file); - - folder.name = `folder${i + 1}protected`; - file.name = `file${i + 1}protected`; - mockFilesProtected.folders.push(folder); - mockFilesProtected.files.push(file); -} - -export { mockFiles, mockFilesProtected }; diff --git a/package.json b/package.json index 06ccf5e..0fe4e26 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "next-gdrive-index", - "version": "2.0.1", + "version": "2.0.3", "private": true, "scripts": { "dev": "next dev -p 3000", diff --git a/public/fonts/Exo2-Bold.ttf b/public/fonts/Exo2-Bold.ttf deleted file mode 100644 index 8404285..0000000 Binary files a/public/fonts/Exo2-Bold.ttf and /dev/null differ diff --git a/public/fonts/Exo2-Regular.ttf b/public/fonts/Exo2-Regular.ttf deleted file mode 100644 index 63bc4bb..0000000 Binary files a/public/fonts/Exo2-Regular.ttf and /dev/null differ diff --git a/public/images/setup/google-cloud-1.png b/public/images/setup/google-cloud-1.png deleted file mode 100644 index f603793..0000000 Binary files a/public/images/setup/google-cloud-1.png and /dev/null differ diff --git a/public/next.svg b/public/next.svg deleted file mode 100644 index 5174b28..0000000 --- a/public/next.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/public/setup/googleCloud.md b/public/setup/googleCloud.md deleted file mode 100644 index e69de29..0000000 diff --git a/public/vercel.svg b/public/vercel.svg deleted file mode 100644 index d2f8422..0000000 --- a/public/vercel.svg +++ /dev/null @@ -1 +0,0 @@ - \ No newline at end of file diff --git a/src/app/@explorer.tsx b/src/app/@explorer.tsx deleted file mode 100644 index 9acdbc8..0000000 --- a/src/app/@explorer.tsx +++ /dev/null @@ -1,189 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { usePathname } from "next/navigation"; -import { useContext, useEffect, useMemo, useState } from "react"; -import toast from "react-hot-toast"; -import { z } from "zod"; -import { Schema_File } from "~/schema"; -import { cn } from "~/utils"; - -import Icon from "~/components/Icon"; -import { Button } from "~/components/ui/button"; -import { Separator } from "~/components/ui/separator"; - -import { LayoutContext } from "~/context/layoutContext"; - -import config from "~/config/gIndex.config"; - -import FileGrid from "./@file.grid"; -import FileList from "./@file.list"; -import { GetFiles } from "./actions"; - -type Props = { - files: z.infer[]; - nextPageToken?: string; - root?: boolean; -}; -export default function FileBrowser({ files, nextPageToken, root }: Props) { - const { layout } = useContext(LayoutContext); - const pathname = usePathname(); - const prevPath = useMemo(() => { - const path = pathname - .split("/") - .slice(0, -1) - .join("/") - .replace(/\/+/g, "/"); - - return new URL(path, config.basePath).pathname; - }, [pathname]); - - const [fileList, setFileList] = - useState[]>(files); - const [nextToken, setNextToken] = useState(nextPageToken); - const [loadMoreLoading, setLoadMoreLoading] = useState(false); - - const [loading, setLoading] = useState(true); - - useEffect(() => { - setLoading(false); - }, []); - - const onLoadMore = async () => { - setLoadMoreLoading(true); - try { - if (!nextToken) throw new Error("No more files to load"); - const data = await GetFiles({ pageToken: nextToken }); - const uniqueData = [...fileList, ...data.files].filter( - (item, index, array) => - index === array.findIndex((i) => i.encryptedId === item.encryptedId), - ); - setFileList(uniqueData); - // const uniqueData = new Set([...fileList, ...data.files]); - // setFileList([...uniqueData]); - setNextToken(data.nextPageToken); - } catch (error) { - const e = error as Error; - console.error(e.message); - toast.error(e.message); - } finally { - setLoadMoreLoading(false); - } - }; - - if (loading) { - return ( -
- -

Wait a moment while we load your files...

-
- ); - } - - return ( -
- {!root && ( - - )} - {!fileList.length && ( -
- - - There are no files in this folder - -
- )} - {layout === "list" && ( -
- {fileList.map((file) => ( -
- - -
- ))} -
- )} - {layout === "grid" && ( -
- {fileList.map((file) => ( -
- -
- ))} -
- )} - - {nextToken && ( - - )} -
- ); -} diff --git a/src/app/@file.grid.tsx b/src/app/@file.grid.tsx deleted file mode 100644 index ac5d9ba..0000000 --- a/src/app/@file.grid.tsx +++ /dev/null @@ -1,320 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { usePathname } from "next/navigation"; -import { useMemo, useState } from "react"; -import toast from "react-hot-toast"; -import { z } from "zod"; -import { Schema_File } from "~/schema"; -import { cn } from "~/utils"; - -import Icon from "~/components/Icon"; -import { Button } from "~/components/ui/button"; -import { - Drawer, - DrawerClose, - DrawerContent, - DrawerDescription, - DrawerFooter, - DrawerHeader, - DrawerTitle, - DrawerTrigger, -} from "~/components/ui/drawer"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "~/components/ui/dropdown-menu"; - -import useMediaQuery from "~/hooks/useMediaQuery"; -import bytesToReadable from "~/utils/bytesFormat"; -import { durationToReadable } from "~/utils/durationFormat"; -import { getPreviewIcon } from "~/utils/previewHelper"; - -import config from "~/config/gIndex.config"; - -import { CreateDownloadToken } from "./actions"; - -type Props = { - data: z.infer; -}; -export default function FileGrid({ data }: Props) { - const pathname = usePathname(); - const filePath = useMemo(() => { - // const currentPath = pathname.startsWith("/e") ? pathname : `/e${pathname}`; - // Set to pathname to remove the /e prefix - const path = [pathname, encodeURIComponent(data.name)] - .join("/") - .replace(/\/+/g, "/"); - - return new URL(path, config.basePath).pathname; - }, [data, pathname]); - - const [thumbnailURL, setThumbnailURL] = useState( - `/api/thumb/${data.encryptedId}?size=2`, - ); - const [actionOpen, setActionOpen] = useState(false); - const isDesktop = useMediaQuery("(min-width: 768px)"); - - const onCopy = async (e: React.MouseEvent) => { - e.stopPropagation(); - try { - toast.promise( - navigator.clipboard.writeText( - new URL(filePath, config.basePath).toString(), - ), - { - loading: "Copying link...", - success: "Link copied!", - error: "Failed to copy link", - }, - ); - } catch (error) { - const e = error as Error; - console.error(e.message); - } - }; - const onDownload = async (e: React.MouseEvent) => { - e.stopPropagation(); - toast.loading("Creating download token...", { - id: `download-${data.encryptedId}`, - }); - try { - const token = await CreateDownloadToken(); - if (!token) throw new Error("Failed to create download token"); - toast.success("Opening download link...", { - id: `download-${data.encryptedId}`, - }); - - const timeout = setTimeout(() => { - clearTimeout(timeout); - window.open(`/api/download/${data.encryptedId}?token=${token}`); - }, 1000); - } catch (error) { - const e = error as Error; - console.error(e.message); - toast.error(e.message, { - id: `download-${data.encryptedId}`, - }); - } - }; - - return ( -
- {isDesktop ? ( - - - - - - - - Copy link - - {data.mimeType.includes("folder") ? null : ( - - - Download - - )} - - - ) : ( - - - - - - - Actions - - What would you like to do with this file? - - -
- - - - {data.mimeType.includes("folder") ? null : ( - - - - )} -
- - - - - - -
-
- )} - -
- {/* If it's media, show thumbnail */} -
- {data.thumbnailLink && - (data.mimeType.startsWith("video") || - data.mimeType.startsWith("image")) ? ( - <> - {data.name} { - if (thumbnailURL.includes("size=2")) { - setThumbnailURL(`/api/thumb/${data.encryptedId}`); - } - }} - className='rounded-top-[var(--radius)] absolute -z-0 h-32 w-full flex-shrink-0 flex-grow-0 object-cover opacity-50' - /> - {data.name} { - if (thumbnailURL.includes("size=2")) { - setThumbnailURL(`/api/thumb/${data.encryptedId}`); - } - }} - className='relative z-0 h-32 w-full flex-shrink-0 flex-grow-0 object-contain backdrop-blur' - /> - - {data.mimeType.startsWith("video") && ( - <> - -
- {durationToReadable( - data.videoMediaMetadata?.durationMillis || 0, - )} -
- - )} - - ) : ( - - )} -
- - {/* File data */} -
- - {config.siteConfig.showFileExtension - ? data.name - : data.fileExtension - ? data.name.replace(new RegExp(`.${data.fileExtension}$`), "") - : data.name} - -
- - {data.mimeType.includes("folder") - ? "folder" - : data.fileExtension} - - {!data.mimeType.includes("folder") && ( - <> - {config.siteConfig.showFileExtension ? null : ( - - )} - - {bytesToReadable(data.size || 0)} - - - )} -
-
- - {new Date(data.modifiedTime).toLocaleDateString()} - -
-
-
- -
- ); -} diff --git a/src/app/@file.list.tsx b/src/app/@file.list.tsx deleted file mode 100644 index 0513e51..0000000 --- a/src/app/@file.list.tsx +++ /dev/null @@ -1,308 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { usePathname } from "next/navigation"; -import { useMemo, useState } from "react"; -import toast from "react-hot-toast"; -import { z } from "zod"; -import { Schema_File } from "~/schema"; -import { cn } from "~/utils"; - -import Icon from "~/components/Icon"; -import { Button } from "~/components/ui/button"; -import { - Drawer, - DrawerClose, - DrawerContent, - DrawerDescription, - DrawerFooter, - DrawerHeader, - DrawerTitle, - DrawerTrigger, -} from "~/components/ui/drawer"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "~/components/ui/dropdown-menu"; - -import useMediaQuery from "~/hooks/useMediaQuery"; -import bytesToReadable from "~/utils/bytesFormat"; -import { durationToReadable } from "~/utils/durationFormat"; -import { getPreviewIcon } from "~/utils/previewHelper"; - -import config from "~/config/gIndex.config"; - -import { CreateDownloadToken } from "./actions"; - -type Props = { - data: z.infer; -}; -export default function FileList({ data }: Props) { - const pathname = usePathname(); - - const filePath = useMemo(() => { - const path = [pathname, encodeURIComponent(data.name)] - .join("/") - .replace(/\/+/g, "/"); - - return new URL(path, config.basePath).pathname; - }, [data, pathname]); - - const [thumbnailURL, setThumbnailURL] = useState( - `/api/thumb/${data.encryptedId}?size=2`, - ); - const [actionOpen, setActionOpen] = useState(false); - const isDesktop = useMediaQuery("(min-width: 768px)"); - - const onCopy = async (e: React.MouseEvent) => { - e.stopPropagation(); - try { - toast.promise( - navigator.clipboard.writeText( - new URL(filePath, config.basePath).toString(), - ), - { - loading: "Copying link...", - success: "Link copied!", - error: "Failed to copy link", - }, - ); - } catch (error) { - const e = error as Error; - console.error(e.message); - } - }; - const onDownload = async (e: React.MouseEvent) => { - e.stopPropagation(); - toast.loading("Creating download token...", { - id: `download-${data.encryptedId}`, - }); - try { - const token = await CreateDownloadToken(); - if (!token) throw new Error("Failed to create download token"); - toast.success("Opening download link...", { - id: `download-${data.encryptedId}`, - }); - - const timeout = setTimeout(() => { - clearTimeout(timeout); - window.open(`/api/download/${data.encryptedId}?token=${token}`); - }, 1000); - } catch (error) { - const e = error as Error; - console.error(e.message); - toast.error(e.message, { - id: `download-${data.encryptedId}`, - }); - } - }; - - return ( -
-
- {isDesktop ? ( - - - - - - - - Copy link - - {data.mimeType.includes("folder") ? null : ( - - - Download - - )} - - - ) : ( - - - - - - - Actions - - What would you like to do with this file? - - -
- - - - {data.mimeType.includes("folder") ? null : ( - - - - )} -
- - - - - - -
-
- )} -
- -
- {/* If it's media, show thumbnail */} -
- {data.thumbnailLink && - (data.mimeType.startsWith("video") || - data.mimeType.startsWith("image")) ? ( - <> - {data.name} { - if (thumbnailURL.includes("size=2")) { - setThumbnailURL(`/api/thumb/${data.encryptedId}`); - } - }} - className='size-16 flex-shrink-0 flex-grow-0 rounded-[var(--radius)] object-cover tablet:size-20' - /> - - {data.mimeType.startsWith("video") && ( - <> - -
- {durationToReadable( - data.videoMediaMetadata?.durationMillis || 0, - )} -
- - )} - - ) : ( - - )} -
- - {/* File data */} -
- - {config.siteConfig.showFileExtension - ? data.name - : data.fileExtension - ? data.name.replace(new RegExp(`.${data.fileExtension}$`), "") - : data.name} - -
- - {data.mimeType.includes("folder") - ? "folder" - : data.fileExtension} - - {!data.mimeType.includes("folder") && ( - <> - {config.siteConfig.showFileExtension ? null : ( - - )} - - {bytesToReadable(data.size || 0)} - - - )} -
-
- - {new Date(data.modifiedTime).toLocaleDateString()} - -
-
-
- -
- ); -} diff --git a/src/app/@header.breadcrumb.tsx b/src/app/@header.breadcrumb.tsx deleted file mode 100644 index d371315..0000000 --- a/src/app/@header.breadcrumb.tsx +++ /dev/null @@ -1,185 +0,0 @@ -"use client"; - -import { DropdownMenuTrigger } from "@radix-ui/react-dropdown-menu"; -import Link from "next/link"; -import { Fragment, useState } from "react"; -import { z } from "zod"; -import { Schema_Breadcrumb } from "~/schema"; - -import Icon from "~/components/Icon"; -import { - Breadcrumb, - BreadcrumbEllipsis, - BreadcrumbItem, - BreadcrumbLink, - BreadcrumbList, - BreadcrumbPage, - BreadcrumbSeparator, -} from "~/components/ui/breadcrumb"; -import { Button } from "~/components/ui/button"; -import { - Drawer, - DrawerClose, - DrawerContent, - DrawerFooter, - DrawerHeader, - DrawerTitle, - DrawerTrigger, -} from "~/components/ui/drawer"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, -} from "~/components/ui/dropdown-menu"; -import { Separator } from "~/components/ui/separator"; -import { Skeleton } from "~/components/ui/skeleton"; - -import useMediaQuery from "~/hooks/useMediaQuery"; - -import config from "~/config/gIndex.config"; - -type Props = { - data: z.infer[]; - loading?: boolean; -}; -export default function HeaderBreadcrumb({ data, loading }: Props) { - const [open, setOpen] = useState(false); - const isDesktop = useMediaQuery("(min-width: 768px)"); - - if (loading) return ; - - return ( -
- - - - - -
- - ~ -
- -
-
- {!!data.length ? ( - <> - - - {data.length > config.siteConfig.breadcrumbMax ? ( - <> - {isDesktop ? ( - - - - - - {data - .slice(0, -config.siteConfig.breadcrumbMax + 1) - .map((item, _, array) => ( - - - item.href) - .join("/")}`} - className='w-full' - > - {item.label} - - - - ))} - - - ) : ( - - - - - - - - Navigate to parent directories - - - -
- {data - .slice(0, -config.siteConfig.breadcrumbMax + 1) - .map((item, _, array) => ( - - - item.href) - .join("/")}`} - className='w-full py-1.5' - > - {item.label} - - - - ))} -
- - - - - - -
-
- )} - - - - ) : null} - - {data.slice(-config.siteConfig.breadcrumbMax + 1).map((item) => ( - - - {item.href ? ( - <> - - item.href) - .join("/") - .replace(/\/\//g, "/")}`} - > - {item.label} - - - - ) : ( - - {item.label} - - )} - - {item.href && } - - ))} - - ) : null} -
-
-
- ); -} diff --git a/src/app/@header.title.tsx b/src/app/@header.title.tsx deleted file mode 100644 index 3a9da84..0000000 --- a/src/app/@header.title.tsx +++ /dev/null @@ -1,26 +0,0 @@ -"use client"; - -import { PropsWithChildren } from "react"; - -import { Skeleton } from "~/components/ui/skeleton"; -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "~/components/ui/tooltip"; - -export default function HeaderTitle({ - children, - loading, -}: PropsWithChildren<{ loading?: boolean }>) { - if (loading) return ; - - return ( - - -

{children}

-
- {children} -
- ); -} diff --git a/src/app/@header.tsx b/src/app/@header.tsx deleted file mode 100644 index 9ef6071..0000000 --- a/src/app/@header.tsx +++ /dev/null @@ -1,44 +0,0 @@ -"use client"; - -import { useEffect, useState } from "react"; -import { z } from "zod"; -import { Schema_Breadcrumb } from "~/schema"; -import { cn } from "~/utils"; - -import HeaderBreadcrumb from "./@header.breadcrumb"; - -type Props = { - name: string; - breadcrumb?: z.infer[]; -}; -export default function Header({ name, breadcrumb }: Props) { - const [loading, setLoading] = useState(true); - - useEffect(() => { - setLoading(false); - }, []); - - return ( -
-
- {/* {name} */} - - - {/* */} -
-
- ); -} diff --git a/src/app/@not-found.tsx b/src/app/@not-found.tsx deleted file mode 100644 index 9b73830..0000000 --- a/src/app/@not-found.tsx +++ /dev/null @@ -1,45 +0,0 @@ -"use client"; - -import { cn } from "~/utils"; - -import Icon from "~/components/Icon"; -import { Button } from "~/components/ui/button"; - -import useRouter from "~/hooks/usePRouter"; - -export default function NotFoundComponent() { - const router = useRouter(); - return ( -
- - - The file you are looking for does not exist - - -
- - -
-
- ); -} diff --git a/src/app/@preview.audio.tsx b/src/app/@preview.audio.tsx deleted file mode 100644 index ba5d2dc..0000000 --- a/src/app/@preview.audio.tsx +++ /dev/null @@ -1,132 +0,0 @@ -"use client"; - -import dynamic from "next/dynamic"; -import { useEffect, useState } from "react"; -import "react-h5-audio-player/lib/styles.css"; -import { z } from "zod"; -import { Schema_File } from "~/schema"; -import { cn } from "~/utils"; - -import Icon from "~/components/Icon"; - -import { CreateDownloadToken } from "./actions"; - -// import "./r5-style.css"; - -const Plyr = dynamic(() => import("plyr-react"), { - ssr: false, - loading: () => ( -
- -

Loading player...

-
- ), -}); - -type Props = { - file: z.infer; -}; -export default function PreviewAudio({ file }: Props) { - const [audioSrc, setAudioSrc] = useState(""); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(""); - - useEffect(() => { - (async () => { - try { - if (!file.encryptedWebContentLink) { - setError("No audio to preview"); - return; - } - const token = await CreateDownloadToken(); - setAudioSrc(`/api/stream/${file.encryptedId}?token=${token}`); - } catch (error) { - const e = error as Error; - console.error(e); - setError(e.message); - } finally { - setLoading(false); - } - })(); - }, [file]); - - return ( -
- {loading ? ( -
- -

Loading player...

-
- ) : error ? ( -
- - {error} -
- ) : ( -
- -
- )} -
- ); -} diff --git a/src/app/@preview.image.tsx b/src/app/@preview.image.tsx deleted file mode 100644 index 0d60d27..0000000 --- a/src/app/@preview.image.tsx +++ /dev/null @@ -1,130 +0,0 @@ -"use client"; - -import { useEffect, useState } from "react"; -import { z } from "zod"; -import { Schema_File } from "~/schema"; -import { cn } from "~/utils"; - -import Icon from "~/components/Icon"; -import { Alert, AlertDescription, AlertTitle } from "~/components/ui/alert"; - -import config from "~/config/gIndex.config"; - -import { CreateDownloadToken } from "./actions"; - -type Props = { - file: z.infer; -}; -export default function PreviewImage({ file }: Props) { - const [imgSrc, setImgSrc] = useState( - `/api/thumb/${file.encryptedId}?size=4`, - ); - const [imgLoaded, setImgLoaded] = useState(false); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(""); - - useEffect(() => { - (async () => { - try { - if (!file.encryptedWebContentLink) { - setError("No image to preview"); - return; - } - const token = await CreateDownloadToken(); - - const streamURL = new URL( - `/api/thumb/${file.encryptedId}?size=1000`, - config.basePath, - ); - streamURL.searchParams.set("token", token); - fetch(streamURL, { - headers: { - Range: `bytes=0-${(file.size || 1) - 1}`, - }, - }) - .then((res) => { - if (!res.ok) { - throw new Error("Could not load image"); - } - return res.blob(); - }) - .then((blob) => { - const urlobject = URL.createObjectURL(blob); - setImgSrc(urlobject); - const timeout = setTimeout(() => { - setImgLoaded(true); - clearTimeout(timeout); - }, 150); // Add a delay to show the image - }); - } catch (error) { - const e = error as Error; - console.error(e); - setError(e.message); - } finally { - setLoading(false); - } - })(); - }, [file]); - - return ( -
- {loading ? ( -
- -

Loading image...

-
- ) : error ? ( -
- - {error} -
- ) : ( -
- {file.name} { - console.error(e); - setError( - "Could not preview this image, try downloading the file", - ); - }} - /> - - -
- -
- Preview Only - - This image is a preview and may not be the full resolution. - Please download the file for the full resolution. - -
-
-
-
- )} -
- ); -} diff --git a/src/app/@preview.layout.tsx b/src/app/@preview.layout.tsx deleted file mode 100644 index 01119cf..0000000 --- a/src/app/@preview.layout.tsx +++ /dev/null @@ -1,107 +0,0 @@ -"use client"; - -import { useState } from "react"; -import { z } from "zod"; -import { Schema_File } from "~/schema"; -import { cn } from "~/utils"; - -import Icon from "~/components/Icon"; -import { Card, CardContent } from "~/components/ui/card"; - -import { getFileType } from "~/utils/previewHelper"; - -import config from "~/config/gIndex.config"; - -import PreviewAction from "./@preview.action"; -import PreviewAudio from "./@preview.audio"; -import PreviewDoc from "./@preview.doc"; -import PreviewImage from "./@preview.image"; -import PreviewManga from "./@preview.manga"; -import PreviewRich from "./@preview.rich"; -import PreviewUnknown from "./@preview.unknown"; -import PreviewVideo from "./@preview.video"; -import RichHeader from "./@rich-header"; - -type Props = { - data: z.infer; - fileType: "unknown" | ReturnType; -}; -export default function FilePreviewLayout({ data, fileType }: Props) { - const [view, setView] = useState<"markdown" | "raw">("markdown"); - - return ( -
- - - - {config.apiConfig.streamMaxSize && - Number(data.size || 0) > config.apiConfig.streamMaxSize ? ( -
- -

Preview not available

-

- Looks like this file size exceed the preview size limit -

-
- ) : ( - /** - * TODO: Might need a better way to handle large files preview - * like manga, pdf, etc - * - * For now it's downloading the whole file and then previewing it - * which is not a good implementation - */ -
- {fileType === "image" ? ( - - ) : fileType === "audio" ? ( - - ) : fileType === "video" ? ( - - ) : fileType === "code" ? ( - - ) : fileType === "text" ? ( - - ) : fileType === "markdown" ? ( - - ) : fileType === "document" ? ( - - ) : fileType === "pdf" ? ( - - ) : fileType === "manga" ? ( - - ) : ( - - )} -
- )} -
-
- -
- ); -} diff --git a/src/app/@preview.rich.tsx b/src/app/@preview.rich.tsx deleted file mode 100644 index 1d56239..0000000 --- a/src/app/@preview.rich.tsx +++ /dev/null @@ -1,128 +0,0 @@ -"use client"; - -import { useEffect, useState } from "react"; -import { z } from "zod"; -import { Schema_File } from "~/schema"; -import { cn } from "~/utils"; - -import Icon from "~/components/Icon"; -import { Button } from "~/components/ui/button"; - -import Markdown from "./@markdown"; -import { GetContent } from "./actions"; - -type Props = { - file: z.infer; - view: "markdown" | "raw"; - code?: boolean; -}; -export default function PreviewRich({ file, code, view }: Props) { - const [fetchedContent, setFetchedContent] = useState(""); - const [content, setContent] = useState(""); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(""); - - const [expand, setExpand] = useState(false); - - useEffect(() => { - (async () => { - try { - const text = await GetContent(file.encryptedId); - if (!text) { - setError("Looks like there is no content to preview"); - return; - } - // setFetchedContent(text); - // if (code) { - // setContent(`\`\`\`${file.fileExtension}\n${text}\`\`\``); - // } else { - setContent(text.trim()); - // } - } catch (error) { - const e = error as Error; - console.error(e); - setError(e.message); - } finally { - setLoading(false); - } - })(); - }, [file, code]); - - return ( -
- {loading ? ( -
- -

Loading content...

-
- ) : error ? ( -
- - {error} -
- ) : ( -
-
- -
-
- -
-
- )} -
- ); -} diff --git a/src/app/@preview.unknown.tsx b/src/app/@preview.unknown.tsx deleted file mode 100644 index b044810..0000000 --- a/src/app/@preview.unknown.tsx +++ /dev/null @@ -1,52 +0,0 @@ -"use client"; - -import { useEffect, useState } from "react"; -import { cn } from "~/utils"; - -import Icon from "~/components/Icon"; - -export default function PreviewUnknown() { - const [loading, setLoading] = useState(true); - - useEffect(() => { - setLoading(false); - }, []); - - return ( -
- {loading ? ( -
- -

Loading content...

-
- ) : ( -
- -

Preview not available

-

- This file type is not supported for preview, try downloading the - file instead. -

-
- )} -
- ); -} diff --git a/src/app/@preview.video.tsx b/src/app/@preview.video.tsx deleted file mode 100644 index 1a4e634..0000000 --- a/src/app/@preview.video.tsx +++ /dev/null @@ -1,130 +0,0 @@ -"use client"; - -import dynamic from "next/dynamic"; -import { useEffect, useState } from "react"; -import { z } from "zod"; -import { Schema_File } from "~/schema"; -import { cn } from "~/utils"; - -import Icon from "~/components/Icon"; - -import { CreateDownloadToken } from "./actions"; - -const Plyr = dynamic(() => import("plyr-react"), { - ssr: false, - loading: () => ( -
- -

Loading player...

-
- ), -}); - -type Props = { - file: z.infer; -}; -export default function PreviewVideo({ file }: Props) { - const [videoSrc, setVideoSrc] = useState(""); - const [loading, setLoading] = useState(true); - const [error, setError] = useState(""); - - useEffect(() => { - (async () => { - try { - if (!file.encryptedWebContentLink) { - setError("No video to preview"); - return; - } - const token = await CreateDownloadToken(); - setVideoSrc(`/api/stream/${file.encryptedId}?token=${token}`); - } catch (error) { - const e = error as Error; - console.error(e); - setError(e.message); - } finally { - setLoading(false); - } - })(); - }, [file]); - - return ( -
- {loading ? ( -
- -

Loading video...

-
- ) : error ? ( -
- - {error} -
- ) : ( -
- -
- )} -
- ); -} diff --git a/src/app/@readme.tsx b/src/app/@readme.tsx deleted file mode 100644 index 8990720..0000000 --- a/src/app/@readme.tsx +++ /dev/null @@ -1,38 +0,0 @@ -"use client"; - -import { useState } from "react"; - -import { Card, CardContent } from "~/components/ui/card"; - -import Markdown from "./@markdown"; -import RichHeader from "./@rich-header"; - -type Props = { - content: string; - title: string; -}; -export default function Readme({ content, title }: Props) { - const [view, setView] = useState<"markdown" | "raw">("markdown"); - - return ( -
- - - - - - -
- ); -} diff --git a/src/app/@rich-header.tsx b/src/app/@rich-header.tsx deleted file mode 100644 index 3c984f5..0000000 --- a/src/app/@rich-header.tsx +++ /dev/null @@ -1,53 +0,0 @@ -"use client"; - -import { Button } from "~/components/ui/button"; -import { CardHeader } from "~/components/ui/card"; -import { Separator } from "~/components/ui/separator"; - -import { getFileType } from "~/utils/previewHelper"; - -type Props = { - title: string; - view: "markdown" | "raw"; - onViewChange: (value: "markdown" | "raw") => void; - fileType: ReturnType | "unknown"; -}; -export default function RichHeader({ - title, - view, - onViewChange, - fileType, -}: Props) { - return ( - -
- {/* */} -

- {title} -

- {/*
*/} - {["markdown", "code", "text"].includes(fileType) && ( -
- - -
- )} -
- -
- ); -} diff --git a/src/app/[...rest]/deploy/@form.api-config.tsx b/src/app/[...rest]/deploy/@form.api-config.tsx deleted file mode 100644 index def64e0..0000000 --- a/src/app/[...rest]/deploy/@form.api-config.tsx +++ /dev/null @@ -1,403 +0,0 @@ -"use client"; - -import toast from "react-hot-toast"; -import { z } from "zod"; -import { - ConfigurationCategory, - ConfigurationKeys, - ConfigurationValue, - Schema_App_Configuration, -} from "~/schema"; - -import { Button } from "~/components/ui/button"; -import { Input } from "~/components/ui/input"; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "~/components/ui/select"; -import { Separator } from "~/components/ui/separator"; - -import { decryptData } from "~/utils/encryptionHelper/hash"; -import { parseConfigFile } from "~/utils/parseConfigFile"; - -import ConfigInput from "./@form.input"; - -type Props = { - state: { - get: z.input; - set: < - T extends ConfigurationCategory = ConfigurationCategory, - K extends ConfigurationKeys = ConfigurationKeys, - >( - category: T, - key: K, - value: ConfigurationValue, - ) => void; - }; - error: { - get: Partial, string>>; - set: >(key: T, value: string) => void; - }; - onReset: (category: ConfigurationCategory) => void; -}; -export default function ApiConfig({ - state: { get, set }, - error, - onReset, -}: Props) { - return ( -
{ - e.preventDefault(); - onReset("api"); - }} - > -
-

API

-
- - -
-
- - - -
- > - key='rootFolder' - title='Root Folder ID' - description={`Starting point of the drive, will be used as the root folder to display files and folders. -This ID will be encrypted in the config file.`} - error={error.get.rootFolder} - required - > - { - if (error.get.rootFolder) { - error.set("rootFolder", ""); - } - set("api", "rootFolder", e.target.value); - }} - onBlur={async () => { - try { - const value = get.api.rootFolder; - error.set("rootFolder", ""); - - if (!value) throw new Error("Root Folder ID is required"); - } catch (err) { - const e = err as Error; - error.set("rootFolder", e.message); - } - }} - /> - - - > - key='isTeamDrive' - title='Use Team Drive' - description={`If you are using Shared Drive, you NEED to enable this option.`} - error={error.get.isTeamDrive} - required - > - - - - {get.api.isTeamDrive && ( - > - key='sharedDrive' - title='Shared Drive ID' - description={`The Drive ID of the Shared Drive. -This ID will be encrypted in the config file`} - error={error.get.sharedDrive} - required={get.api.isTeamDrive} - > - { - if (error.get.sharedDrive) { - error.set("sharedDrive", ""); - } - set("api", "sharedDrive", e.target.value); - }} - onBlur={async () => { - try { - const value = get.api.sharedDrive; - const isTeamDrive = get.api.isTeamDrive; - error.set("sharedDrive", ""); - - if (!isTeamDrive) return; - if (!value) - throw new Error( - "Shared Drive ID is required if using Team Drive", - ); - } catch (err) { - const e = err as Error; - error.set("sharedDrive", e.message); - } - }} - /> - - )} - - > - key='proxyThumbnail' - title='Proxy Thumbnail' - description={`Proxy the thumbnail image via API route. - -If your files thumbnail are not accessible, you can set this to true. -This will fetch the thumbnail image via API route, but it will increase the load on your server.`} - error={error.get.proxyThumbnail} - required - > - - - - > - key='allowDownloadProtectedFile' - title='Allow Download Protected File' - description={`Allow users to download password protected files. - -If set to true, users will be able to download the file without entering password as long as they have the link -If set to false, the download link will have a temporary token attached to it, the token will expire after certain duration (default is 6 hours)`} - error={error.get.allowDownloadProtectedFile} - required - > - - - - > - key='temporaryTokenDuration' - title='Temporary Token Duration (in hours)' - description={`Duration of the temporary token used for protected files download link.`} - error={error.get.temporaryTokenDuration} - required - > - { - if (error.get.temporaryTokenDuration) { - error.set("temporaryTokenDuration", ""); - } - set("api", "temporaryTokenDuration", parseInt(e.target.value)); - }} - onBlur={async () => { - try { - const value = get.api.temporaryTokenDuration; - error.set("temporaryTokenDuration", ""); - - if (value <= 0) - throw new Error( - "Temporary Token Duration must be more than 0", - ); - } catch (err) { - const e = err as Error; - error.set("temporaryTokenDuration", e.message); - } - }} - /> - - - > - key='maxFileSize' - title='Max Direct Download Size (in MB)' - description={`Max file size that can be downloaded directly from the server, instead of download link from Google Drive. -Please refer to your deploy platform for the maximum response size limit. -If you are using Vercel, the maximum response size is around 4 - 4.5MB. - -Set to 0 to disable the limit.`} - error={error.get.maxFileSize} - required - > - { - if (error.get.maxFileSize) { - error.set("maxFileSize", ""); - } - set("api", "maxFileSize", parseInt(e.target.value) * 1024 * 1024); - }} - onBlur={async () => { - try { - const value = get.api.maxFileSize; - error.set("maxFileSize", ""); - - if (value < 0) - throw new Error( - "Max file size must be more than or equal to 0", - ); - } catch (err) { - const e = err as Error; - error.set("maxFileSize", e.message); - } - }} - /> - -
- - ); -} diff --git a/src/app/[...rest]/deploy/@form.env-config.tsx b/src/app/[...rest]/deploy/@form.env-config.tsx deleted file mode 100644 index d3a8361..0000000 --- a/src/app/[...rest]/deploy/@form.env-config.tsx +++ /dev/null @@ -1,359 +0,0 @@ -"use client"; - -import { useState } from "react"; -import toast from "react-hot-toast"; -import { z } from "zod"; -import { - ConfigState, - ConfigurationCategory, - ConfigurationKeys, - ConfigurationValue, - Schema_App_Configuration, - Schema_ServiceAccount, -} from "~/schema"; - -import { GenerateAESKey, VerifyAESKey } from "~/app/actions"; -import { Button } from "~/components/ui/button"; -import { Input } from "~/components/ui/input"; -import { Separator } from "~/components/ui/separator"; - -import ConfigInput from "./@form.input"; - -type Props = { - state: { - get: z.input; - set: < - T extends ConfigurationCategory = ConfigurationCategory, - K extends ConfigurationKeys = ConfigurationKeys, - >( - category: T, - key: K, - value: ConfigurationValue, - ) => void; - }; - error: { - get: Partial, string>>; - set: >( - key: T, - value: string, - ) => void; - }; - onReset: (category: ConfigurationCategory) => void; -}; -export default function EnvironmentConfig({ - state: { get, set }, - error, - onReset, -}: Props) { - const [encryptionState, setEncryptionState] = useState("idle"); - const [gdServiceState, setGdServiceState] = useState("idle"); - const [revealPassword, setRevealPassword] = useState(false); - - return ( -
{ - e.preventDefault(); - onReset("environment"); - }} - > -
-

Environment

-
- - -
-
- - - -
- > - key='ENCRYPTION_KEY' - title='Encryption Key' - description='The encryption key for the site, must be a alphanumeric string without spaces' - error={error.get.ENCRYPTION_KEY} - required - action={{ - label: "Generate", - async onClick(e) { - e.preventDefault(); - setEncryptionState("loading"); - error.set("ENCRYPTION_KEY", ""); - - try { - const keyStr = await GenerateAESKey(); - const valid = await VerifyAESKey("This is a test", keyStr); - if (!valid) - throw new Error("Invalid key generated, please try again"); - - set("environment", "ENCRYPTION_KEY", keyStr); - } catch (err) { - const e = err as Error; - console.error(e); - error.set("ENCRYPTION_KEY", e.message); - toast.error(e.message); - } finally { - setEncryptionState("idle"); - } - }, - state: encryptionState, - }} - > - { - if (error.get.ENCRYPTION_KEY) { - error.set("ENCRYPTION_KEY", ""); - } - set("environment", "ENCRYPTION_KEY", e.target.value); - }} - onBlur={async () => { - try { - const value = get.environment.ENCRYPTION_KEY; - error.set("ENCRYPTION_KEY", ""); - - if (!value) throw new Error("Encryption key is required"); - - if (value.includes(" ")) - throw new Error("Encryption key must not contain spaces"); - - const valid = await VerifyAESKey("This is a test", value); - if (!valid) - throw new Error( - "The encryption key is invalid, please generate a new one", - ); - } catch (err) { - const e = err as Error; - error.set("ENCRYPTION_KEY", e.message); - } - }} - /> - - - > - key='GD_SERVICE_B64' - title='Google Drive Service Account' - description={`The base64 encoded Google Drive Service Account JSON file -To avoid error when inputting, please use the "Load JSON" button to load the file directly`} - error={error.get.GD_SERVICE_B64} - required - action={{ - label: "Load JSON", - async onClick(e) { - e.preventDefault(); - setGdServiceState("loading"); - - try { - const fileInput = document.createElement("input"); - fileInput.type = "file"; - fileInput.accept = ".json"; - fileInput.onchange = async (fileEvent) => { - const file = (fileEvent.target as HTMLInputElement) - .files?.[0]; - if (!file) return toast.error("No file selected"); - - const reader = new FileReader(); - reader.onload = async (readerEvent) => { - const result = readerEvent.target?.result as string; - if (!result) return toast.error("Failed to read file"); - - const objectFile = JSON.parse(result); - const parse = Schema_ServiceAccount.safeParse(objectFile); - if (!parse.success) - return toast.error( - "Invalid Service Account JSON, please select a valid Google Drive Service Account JSON file", - ); - - set("environment", "GD_SERVICE_B64", btoa(result)); - error.set("GD_SERVICE_B64", ""); - - toast.success( - "Google Drive Service Account JSON file loaded", - ); - fileInput.value = ""; - }; - reader.readAsText(file); - }; - fileInput.click(); - } catch (err) { - const e = err as Error; - console.error(e); - error.set("GD_SERVICE_B64", e.message); - toast.error(e.message); - } finally { - setGdServiceState("idle"); - } - }, - state: gdServiceState, - }} - > - { - if (error.get.GD_SERVICE_B64) { - error.set("GD_SERVICE_B64", ""); - } - set("environment", "GD_SERVICE_B64", e.target.value); - }} - /> - - - > - key='NEXT_PUBLIC_DOMAIN' - title='Domain' - description={`The domain for the site, without the protocol -(e.g. drive-demo.mbaharip.com or mbaharip.com)`} - error={error.get.NEXT_PUBLIC_DOMAIN} - > - { - if (error.get.NEXT_PUBLIC_DOMAIN) { - error.set("NEXT_PUBLIC_DOMAIN", ""); - } - set("environment", "NEXT_PUBLIC_DOMAIN", e.target.value); - }} - onBlur={async () => { - try { - error.set("NEXT_PUBLIC_DOMAIN", ""); - } catch (err) { - const e = err as Error; - error.set("NEXT_PUBLIC_DOMAIN", e.message); - } - }} - /> - - - > - key='SITE_PASSWORD' - title='Site Password' - description='The password to access the site' - error={error.get.SITE_PASSWORD} - required={get.site.privateIndex} - action={{ - label: revealPassword ? "Hide" : "Reveal", - onClick(e) { - e.preventDefault(); - setRevealPassword((prev) => !prev); - }, - state: "idle", - }} - > - { - if (error.get.SITE_PASSWORD) { - error.set("SITE_PASSWORD", ""); - } - set("environment", "SITE_PASSWORD", e.target.value); - }} - onBlur={async () => { - try { - error.set("SITE_PASSWORD", ""); - if (get.site.privateIndex && !get.environment.SITE_PASSWORD) { - throw new Error( - "Site Password is required when Private Index is enabled", - ); - } - } catch (err) { - const e = err as Error; - console.error(e); - error.set("SITE_PASSWORD", e.message); - } - }} - /> - -
- - ); -} diff --git a/src/app/[...rest]/deploy/@form.input.tsx b/src/app/[...rest]/deploy/@form.input.tsx deleted file mode 100644 index 880bc01..0000000 --- a/src/app/[...rest]/deploy/@form.input.tsx +++ /dev/null @@ -1,120 +0,0 @@ -"use client"; - -import { PropsWithChildren } from "react"; -import { ConfigState } from "~/schema"; -import { cn } from "~/utils"; - -import Icon from "~/components/Icon"; -import { Button } from "~/components/ui/button"; -import { Label } from "~/components/ui/label"; -import { - Tooltip, - TooltipContent, - TooltipTrigger, -} from "~/components/ui/tooltip"; - -type Props = { - key: T extends string ? T : string; - title: string; - description?: string; - required?: boolean; - action?: { - label: string; - onClick: (e: React.MouseEvent) => void; - state: ConfigState; - }; - error?: string; -}; -export default function ConfigInput(props: PropsWithChildren>) { - return ( -
-
- - {!props.required && ( - (optional) - )} - {props.description && ( - - e.preventDefault()} - className='cursor-default' - > - - - -

- {props.description} -

-
-
- )} -
- -
-
- {props.children} -
- {props.action && ( - - )} -
- -
- - {props.error} - -
-
- ); -} diff --git a/src/app/[...rest]/deploy/@form.site-config.tsx b/src/app/[...rest]/deploy/@form.site-config.tsx deleted file mode 100644 index 36f2e46..0000000 --- a/src/app/[...rest]/deploy/@form.site-config.tsx +++ /dev/null @@ -1,418 +0,0 @@ -import toast from "react-hot-toast"; -import { z } from "zod"; -import { - ConfigurationCategory, - ConfigurationKeys, - ConfigurationValue, - Schema_App_Configuration, -} from "~/schema"; - -import { Button } from "~/components/ui/button"; -import { Input } from "~/components/ui/input"; -import { - Select, - SelectContent, - SelectItem, - SelectTrigger, - SelectValue, -} from "~/components/ui/select"; -import { Separator } from "~/components/ui/separator"; - -import { parseConfigFile } from "~/utils/parseConfigFile"; - -import config from "~/config/gIndex.config"; - -import ConfigInput from "./@form.input"; - -type Props = { - state: { - get: z.input; - set: < - T extends ConfigurationCategory = ConfigurationCategory, - K extends ConfigurationKeys = ConfigurationKeys, - >( - category: T, - key: K, - value: ConfigurationValue, - ) => void; - }; - error: { - get: Partial, string>>; - set: >(key: T, value: string) => void; - }; - onReset: (category: ConfigurationCategory) => void; -}; -export default function SiteConfig({ - state: { get, set }, - error, - onReset, -}: Props) { - return ( -
{ - e.preventDefault(); - onReset("site"); - }} - > -
-

Site

-
- - -
-
- - - -
-
-
-
- favicon - {get.site.siteName} -
- -
- favicon - - {get.site - .siteNameTemplate!.replace("%s", "Page Title") - .replace("%t", get.site.siteName)} - -
-
- -
- -
-
- > - key='siteName' - title='Index Site Name' - error={error.get.siteName} - required - > - { - if (error.get.siteName) { - error.set("siteName", ""); - } - set("site", "siteName", e.target.value); - }} - onBlur={async () => { - try { - const value = get.site.siteName; - error.set("siteName", ""); - - if (!value) throw new Error("Site name is required"); - } catch (err) { - const e = err as Error; - error.set("siteName", e.message); - } - }} - /> - - - > - key='siteNameTemplate' - title='Site Name Template' - description={`The template for the site name. - -Usable variables: -%s - Page Title -%t - Site Name`} - error={error.get.siteNameTemplate} - > - { - if (error.get.siteNameTemplate) { - error.set("siteNameTemplate", ""); - } - set("site", "siteNameTemplate", e.target.value); - }} - onBlur={async () => { - try { - const value = get.site.siteNameTemplate; - error.set("siteNameTemplate", ""); - } catch (err) { - const e = err as Error; - error.set("siteNameTemplate", e.message); - } - }} - /> - - - > - key='siteDescription' - title='Site Description' - error={error.get.siteDescription} - required - > - { - if (error.get.siteDescription) { - error.set("siteDescription", ""); - } - set("site", "siteDescription", e.target.value); - }} - onBlur={async () => { - try { - const value = get.site.siteDescription; - error.set("siteDescription", ""); - - if (!value) throw new Error("Site description is required"); - } catch (err) { - const e = err as Error; - error.set("siteDescription", e.message); - } - }} - /> - - -
- > - key='siteAuthor' - title='Site Author' - error={error.get.siteAuthor} - description={`Will be used for metadata, and also affect the footer variable`} - > - { - if (error.get.siteAuthor) { - error.set("siteAuthor", ""); - } - set("site", "siteAuthor", e.target.value); - }} - onBlur={async () => { - try { - const value = get.site.siteAuthor; - error.set("siteAuthor", ""); - } catch (err) { - const e = err as Error; - error.set("siteAuthor", e.message); - } - }} - /> - - - > - key='twitterHandle' - title='Twitter Handle' - error={error.get.twitterHandle} - description={`Will be used for metadata, and also affect the footer variable`} - > - { - if (error.get.twitterHandle) { - error.set("twitterHandle", ""); - } - set("site", "twitterHandle", e.target.value); - }} - onBlur={async () => { - try { - const value = get.site.twitterHandle; - error.set("twitterHandle", ""); - } catch (err) { - const e = err as Error; - error.set("twitterHandle", e.message); - } - }} - /> - -
-
- -
- Opengraph Preview -
- - {(get.site.siteNameTemplate || "%s") - .replace("%s", "Page Title") - .replace("%t", get.site.siteName)} - - - {get.environment.NEXT_PUBLIC_DOMAIN || "http://localhost:3000"} - - - {get.site.siteDescription} - -
-
-
- - - - > - key='privateIndex' - title='Private Index' - description={`Lock the whole site behind a password -Will use the site password set in the "Environment" category`} - error={error.get.privateIndex} - required - > - - - - > - key='showFileExtension' - title='Show File Extension' - description={`Show file extension in file explorer - -e.g. "file.mp4" instead of "file"`} - error={error.get.showFileExtension} - required - > - - -
- - ); -} diff --git a/src/app/[...rest]/deploy/docs.tsx b/src/app/[...rest]/deploy/docs.tsx deleted file mode 100644 index c77424d..0000000 --- a/src/app/[...rest]/deploy/docs.tsx +++ /dev/null @@ -1,793 +0,0 @@ -"use client"; - -import { useEffect, useRef, useState } from "react"; -import toast from "react-hot-toast"; -import { z } from "zod"; -import { - ConfigState, - ConfigurationCategory, - ConfigurationKeys, - ConfigurationValue, - Schema_App_Configuration, -} from "~/schema"; -import { cn } from "~/utils"; - -import Markdown from "~/app/@markdown"; -import Icon from "~/components/Icon"; -import { Button } from "~/components/ui/button"; -import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card"; -import { Separator } from "~/components/ui/separator"; - -import { encryptData } from "~/utils/encryptionHelper/hash"; - -import config from "~/config/gIndex.config"; - -import ApiConfig from "./@form.api-config"; -import EnvironmentConfig from "./@form.env-config"; -import SiteConfig from "./@form.site-config"; - -export const getting_started = `Welcome to the deployment guide! This guide will help you to deploy the application to Vercel or similar services. - -If you are new to this project, you can follow along from the beginning. -But if you've already deployed the app before and want to upgrade from v1, you can skip to the [Migrating from v1](#migrating) section. -You can also use this guide to [configure the app](#config) and [customize the theme](#theme). - -**We recommend you to use this deployment guide on a desktop browser for optimal experience.** - -_**Note:** This guide assumes you have a basic understanding of how to deploy a Next.js app on Vercel or other platforms._`; - -export const new_user_guide = `Prerequisites: -- A basic understanding of Vercel (or similar services) -- Google Cloud Platform account - -### Fork or Clone the repository -It's pretty obvious, but you need to fork the repository to your account. -You can [click here](https://github.com/mbahArip/next-gdrive-index/fork) to fork the repository. -You can choose any repository name, description, and visibility. - -But if you want to run it locally, you can clone the repository instead. - -### Create a Google Cloud Platform project and enable Google Drive API -We need an access to Google Drive API to get the files from Google Drive. -So you need to create a project in Google Cloud Platform and enable Google Drive API to get your own credentials. - -1. Go to [Google Cloud Platform](https://console.cloud.google.com/) -2. Click the \`New Project\` button -3. Enter a project name, and click the \`Create\` button -4. After the project is created, click the \`Enable APIs and Services\` button -5. Search for Google Drive API, and click the \`Enable\` button - -### Create a Service Account and get the credentials -After enabling the Google Drive API, we need to create a service account to get the credentials. -The credentials will be used to authenticate the application to access the Google Drive API and get the files. - -1. On [APIs & Services](https://console.cloud.google.com/apis/dashboard) page, click the \`Credentials\` menu on the sidebar -2. Click the \`Create Credentials\` button, and choose \`Service account\` -3. Enter your service account name and description, and then click the \`Done\` button -4. You will see the service account you just created on \`Service Account\` table, click the name of the service account to open the details -5. Go to \`Keys\` tab, then click the \`Add Key\` button and choose the \`Create new key\` -6. Pick \`JSON\` as the key type and click the \`Create\` button -7. The JSON file will be downloaded to your computer, and **keep it safe**. We will use it later on the configuration - -_**Note:** The JSON file contains sensitive information, don't share it with anyone_ - -### Create shared folder in Google Drive -Since the service account can't access your Root folder, you need to create a new folder, and share it with the service account. -This folder will be used as the root folder for the application. - -> If you're using or the folder you want to share inside Shared Drive, you can skip this step and go to the [Shared Drive Guide](#shared-drive) - -1. Go to [Google Drive](https://drive.google.com/) -2. Click the \`New\` button, and choose \`Folder\` to create a new folder, you can name it anything you want -3. Right-click the folder you just created, and choose \`Share\` -4. Enter the email address of the service account you just created (you can find it on the JSON file, or on the service account details page) -5. To allow download files larger than deployment limit, you need to enable \`Link sharing\` and set it to \`Anyone with the link\` -6. Copy the folder ID from the URL, it's the part after \`/folders/\` in the URL (e.g: https://drive.google.com/drive/u/0/folders/ \`\` ) - -### Configuring the app and Customizing the theme -Now we need to configure the app to use the credentials and folder ID we just created. -You can follow the [App Configuration](#config) and [Customize Theme](#theme) sections to configure the app and customize the theme. - -_**Note:** You can skip the theme customization, but you **NEED** to configure the app_ - -### Deploy the app -On this guide we will use Vercel to deploy the app, but you can use other platforms like Netlify, Heroku, etc. -But don't forget to adjust the \`fileSizeLimit\` on the [configuration](#config) if you use other platforms. - -> Before deploying, make sure you have pushed the changes to your repository - - -1. Go to [Vercel](https://vercel.com/) -2. Click on the \`Add new\` button, and choose \`Project\` -3. Choose the repository you just forked -4. On the \`Environment Variables\` section, copy the whole content from \`.env.local\` you just downloaded from [configuration](#config) section, and paste it on the key fields. It will automatically add all the environment variables needed -5. Click the \`Deploy\` button -6. Wait for the deployment to finish, and open project -7. Go to \`Settings\` tab, and click the \`Functions\` menu, and select your \`Function Region\` to the nearest region to your location for optimal speed -8. Go to \`Deployment\` tab, click the 3 dots on the right side of the latest \`Production\` deployment, and click the \`Redeploy\` button to apply the changes - -For other platforms, you can check their own documentation for Next.js deployment guide. - -### Done! 🎉 -Congratulations! You have successfully deployed the app.`; - -export const shared_drive_guide = `I'm separating this guide in case someone who already using v1 can see this guide easily. - -As of version 2.0.2 we added support for Shared Drive, and the demo actually using a Shared Drive. -You can follow this guide to use Shared Drive as the root folder for the application. - -1. Go to [Google Drive](https://drive.google.com/) -2. Open the \`Shared Drives\` menu from the sidebar -3. Right click on the Shared Drive you want to use, and choose \`Manage members\` -4. Add your service account email address to the members list, and give it at least \`Viewer\` permission -5. Open the \`Shared Drive\`, and copy the ID from the URL, it's the part after \`/drive/u/0/folders/\` in the URL (e.g: https://drive.google.com/drive/u/0/folders/ \`\` ) -6. Paste the ID to \`Shared Drive\` field on the [configuration](#config) section, and set the \`is Team Drive\` to \`true\` -7. For the root folder, you can set it to the folder ID inside the Shared Drive, or use the Shared Drive ID as the root folder ID -8. Update the configuration file, and redeploy the app to apply the changes -9. Done! 🎉 - -If you don't want to use the configuration section below, you can encrypt your \`Shared Drive\` ID using the \`/api/internal/encrypt?q=\` endpoint, and update the config file directly. -`; - -export const migration_guide = `If you've already deployed the app before and want to upgrade from v1, you can follow this guide to migrate the app to the latest version. - -### Update your environment and configuration -If you still have the \`.env.local file\`, you can go to the [configuration](#config) section, and load the file to update the environment variables. -If you don't have it, go to your deployment platform and copy the environment variables from the platform to the [configuration](#config) section. - -You can also load the old \`gindex.config.ts\` file to the [configuration](#config) section to set the default configuration. - -### Update the repository -First, you need to update the repository to the latest version. -If you open your forked repository, you will see a notification that the repository is behind the original repository. -You can sync the repository by clicking the \`Sync fork\` button. -After the repository is updated, you can replace the \`gindex.config.ts\` file with the new one. - -### Update deployment -Now go to your Vercel project page (or other platforms). -Go to the \`Settings\` tab, and click the \`Environment Variables\` menu. -You can delete all the old environment variables, and copy the new environment variables from the updated \`.env.local\` file. -Now you can redeploy the app to apply the changes. -`; -const initialConfiguration: z.input = { - environment: { - GD_SERVICE_B64: "", - ENCRYPTION_KEY: "", - SITE_PASSWORD: "", - NEXT_PUBLIC_DOMAIN: "", - }, - api: { - ...config.apiConfig, - rootFolder: "", - isTeamDrive: false, - sharedDrive: "", - proxyThumbnail: true, - - allowDownloadProtectedFile: false, - temporaryTokenDuration: 6, - maxFileSize: 4 * 1024 * 1024, - }, - site: { - ...config.siteConfig, - siteName: "next-gdrive-index", - siteNameTemplate: "%s", - siteDescription: "A simple Google Drive Index using Next.js", - siteAuthor: "mbahArip", - twitterHandle: "@mbahArip", - - showFileExtension: false, - footer: [ - "{{ siteName }} *v{{ version }}* @ {{ repository }}", - "{{ year }} - Made with ❤️ by **{{ author }}**", - ], - - privateIndex: false, - breadcrumbMax: 3, - - toaster: { - position: "bottom-right", - duration: 3000, - }, - - navbarItems: [], - supports: [], - }, -}; - -export function Configuration() { - const fileConfigRef = useRef(null); - const fileEnvRef = useRef(null); - - const [loading, setLoading] = useState(true); - const [configuration, setConfiguration] = - useState>(initialConfiguration); - const [error, setError] = useState<{ - environment: Partial, string>>; - api: Partial, string>>; - site: Partial, string>>; - }>({ - environment: {}, - api: {}, - site: {}, - }); - const [downloadState, setDownloadState] = useState("idle"); - - useEffect(() => { - setLoading(false); - }, []); - - // It's been a year I'm learning TS, and this thing still scares me - function onConfigurationChange< - T extends ConfigurationCategory = ConfigurationCategory, - K extends ConfigurationKeys = ConfigurationKeys, - >(category: T, key: K, value: ConfigurationValue) { - setConfiguration((prev) => ({ - ...prev, - [category]: { - ...prev[category], - [key]: value, - }, - })); - } - function onReset(category: ConfigurationCategory) { - setConfiguration((prev) => ({ - ...prev, - [category]: initialConfiguration[category], - })); - setError((prev) => ({ - ...prev, - [category]: {}, - })); - } - async function onDownload( - e: React.MouseEvent, - ) { - e.preventDefault(); - setDownloadState("loading"); - toast.loading("Generating configuration file...", { - id: "download-config", - }); - - try { - // Check required section first - const requiredEmpty = [ - !configuration.environment.ENCRYPTION_KEY.length, - !configuration.environment.GD_SERVICE_B64.length, - !configuration.api.rootFolder.length, - configuration.api.isTeamDrive && !configuration.api.sharedDrive?.length, - !configuration.site.siteName.length, - !configuration.site.siteDescription.length, - configuration.site.privateIndex && - !configuration.environment.SITE_PASSWORD?.length, - ]; - if (requiredEmpty.filter((v) => v).length) { - throw new Error("Looks like you missed some required fields."); - } - - const errors = []; - for (const err of Object.values(error.environment)) { - if (err.length) errors.push(err); - } - for (const err of Object.values(error.api)) { - if (err.length) errors.push(err); - } - for (const err of Object.values(error.site)) { - if (err.length) errors.push(err); - } - - if (errors.length) { - throw new Error( - "Please fix all the errors before downloading the configuration file.", - ); - } - - function downloadBlob(blob: Blob, filename: string) { - const url = URL.createObjectURL(blob); - const anchor = document.createElement("a"); - anchor.href = url; - anchor.download = filename; - - const afterClick = () => { - setTimeout(() => { - URL.revokeObjectURL(url); - removeEventListener("click", afterClick); - }, 100); - }; - anchor.addEventListener("click", afterClick, false); - - anchor.click(); - } - - let envContent = Object.entries(configuration.environment) - .map(([key, value]) => `${key}=${value}`) - .join("\n"); - envContent += - "\n\n# Can't name it .env for download, so rename it to .env.local\n# Or you can copy the content to your deployment platform"; - - const configContent: string = `import { z } from "zod"; -import { Schema_Config } from "~/schema"; -import isDev from "~/utils/isDev"; - -const config: z.input = { - /** - * If possible, please don't change this value - * Even if you're creating a PR, just let me change it myself - */ - version: "${config.version}", - - /** - * Base path of the app, used for generating links - * - * If you're using another port for development, you can set it here - * - * @default process.env.NEXT_PUBLIC_DOMAIN - * @fallback process.env.NEXT_PUBLIC_VERCEL_URL - */ - basePath: isDev - ? "http://localhost:3000" - : \`https://\${process.env.NEXT_PUBLIC_DOMAIN || process.env.NEXT_PUBLIC_VERCEL_URL}\`, - - /** - * Allow access to the deploy guide - * Will use the \`/deploy\` route, might be overlap with file / folder name - * - * Set this to false on final deployment - * - * I'm using this to show the deploy guide on my own demo deployment - * - * @default false - */ - showDeployGuide: false, - - /** - * How long the cache will be stored in the browser - * Used for all pages and api routes - * Default is 5 minutes (300/60 = 5min) - * - * @default "max-age=0, s-maxage=60, stale-while-revalidate" - */ - cacheControl: "max-age=0, s-maxage=60, stale-while-revalidate", - - apiConfig: { - /** - * Starting point of the drive. - * Will be used for '/' route. - * - * Since service account can't access 'root' folder - * You need to create a new folder and share it with the service account - * Then, copy the folder id and paste it here - */ - rootFolder: - "${await encryptData( - configuration.api.rootFolder, - configuration.environment.ENCRYPTION_KEY, - )}", - - /** - * If your rootfolder inside a shared drive, you NEED to set this to true - * If not, you can set this to false - * - * You also need to set the shared drive ID to make it work - * Make sure you have add your service account to the shared drive since the service account can't access the shared drive by default - * - * Where to get the shared drive id? - * Go to your Shared Drive > Click on the shared drive > copy the ID from the url - * ex: https://drive.google.com/drive/u/0/folders/:shared_drive_id - * - * Then you need to encrypt it using \`/api/internal/encrypt?q=:shared_drive_id\` route - */ - isTeamDrive: ${configuration.api.isTeamDrive ? "true" : "false"}, - sharedDrive: - "${ - configuration.api.isTeamDrive && configuration.api.sharedDrive - ? await encryptData( - configuration.api.sharedDrive, - configuration.environment.ENCRYPTION_KEY, - ) - : "" - }", - - defaultQuery: [ - "trashed = false", - "(not mimeType contains 'google-apps' or mimeType contains 'folder')", - ], - defaultField: - "id, name, mimeType, thumbnailLink, fileExtension, modifiedTime, size, imageMediaMetadata, videoMediaMetadata, webContentLink, trashed", - defaultOrder: "folder, name asc, modifiedTime desc", - - itemsPerPage: 50, - searchResult: 5, - - /** - * By default, the app will use the thumbnail URL from Google Drive - * - * Sometimes, the thumbnail can't be accessed because of CORS policy - * If you're having this issue, you can set this to true - * - * This will make the api fetch the thumbnail and serve it from the server - * instead of using the Google Drive thumbnail - * - * This will increase the server load, so use it wisely - * - * Default: true - */ - proxyThumbnail: ${configuration.api.proxyThumbnail ? "true" : "false"}, - - /** - * Only show preview for files that are smaller than this size - * If the file is larger than this size, it will show "can't preview" message instead - * - * Why? - * Since the stream endpoint are counted as a bandwidth usage - * I want to limit the preview to only small files - * It also to prevent abuse from the user - * - * You can also set this to 0 to disable the limit - * - * Default: 100MB - */ - streamMaxSize: ${100 * 1024 * 1024}, - - /** - * Special file name that will be used for certain purposes - * These files will be ignored when searching for files - * and will be hidden from the files list by default - */ - specialFile: { - password: ".password", - readme: ".readme.md", - /** - * Banner will be used for opengraph image for folder - * By default, all folder will use default og image - */ - banner: ".banner", - }, - - /** - * Reason why banner has multiple extensions: - * - If I use contains query, it will also match the file or folder that contains the word. - * (e.g: File / folder with the name of "Test Password" will be matched) - * - If I use = query, it will only match the exact name, hence the multiple extensions - * - * You can add more extensions if you want - */ - hiddenFiles: [ - ".password", - ".readme.md", - ".banner", - ".banner.jpg", - ".banner.png", - ".banner.webp", - ], - - /** - * Allow user to download protected file without password. - * If this set to false, download link will have temporary token attached to it - * If this set to true, user can download the file without password as long as they have the link - * - * Default: false - */ - allowDownloadProtectedFile: ${ - configuration.api.allowDownloadProtectedFile ? "true" : "false" - }, - - /** - * Duration in hours. - * In version 2, this will be used for download link expiration. - * If you need it under 1 hour, you can use math expression. (e.g: (5 / 60) * 1 = 5 minutes) - * - * This only affect when the user download the file - * For example if you set it for example 30 minutes (0.5) - * After 30 minutes, and the user still downloading the file, the download will NOT be interrupted - * But if the user refresh the page / trying to download again, the download link will be expired - * - * Default: 6 hours - */ - temporaryTokenDuration: ${configuration.api.temporaryTokenDuration}, - - /** - * Maximum file size that can be downloaded via api routes - * If it's larger than this, it will be redirected to the file url - * - * If you're using Vercel, they have a limit of ~4 - ~4.5MB response size - * ref: https://vercel.com/docs/platform/limits#serverless-function-payload-size-limit - * If you're using another platform, you can match the limit with your platform - * Or you can set this to 0 to disable the limit - * - * Default: 4MB - */ - maxFileSize: ${configuration.api.maxFileSize}, - }, - - siteConfig: { - /** - * Site Name will be used for default metadata title - * Site Name Template will be used if the page has a title - * %s will be replaced with the page title - * - * You can set it to undefined if you don't want to use it - */ - siteName: "${configuration.site.siteName}", - siteNameTemplate: "${configuration.site.siteNameTemplate}", - siteDescription: "${configuration.site.siteDescription}", - siteIcon: "/logo.svg", - favIcon: "/favicon.png", - - siteAuthor: "${configuration.site.siteAuthor}", - twitterHandle: "${configuration.site.twitterHandle}", - - /** - * Next.js Metadata robots object - * - * ref: https://nextjs.org/docs/app/api-reference/functions/generate-metadata#robots - */ - robots: "noindex, nofollow", - - /** - * Show file extension on the file name - * Example: - * true | false - * file.txt | file - * 100KB | txt / 100KB - * - * Default: false - */ - showFileExtension: ${ - configuration.site.showFileExtension ? "true" : "false" - }, - - /** - * Footer content - * You can also set it to empty array if you don't want to use it - * - * Basic markdown is supported (bold, italic, and link) - * External link will be opened in new tab - * - * Template: - * - {{ year }} will be replaced with the current year - * - {{ repository }} will be replaced with the original repository link - * - {{ author }} will be replaced with author from siteAuthor config above (If it's not set, it will be set to mbaharip) - * - {{ version }} will be replaced with the current version - * - {{ siteName }} will be replaced with the siteName config above - * - {{ handle }} will be replaced with the twitter handle from twitterHandle config above - * - {{ creator }} will be replaced with mbaharip if you want to credit me - */ - footer: [ - "{{ siteName }} *v{{ version }}* @ {{ repository }}", - "{{ year }} - Made with ❤️ by **{{ author }}**", - isDev ? "Development Mode" : "", - ], - - /** - * DEPRECATED - * Since we're using shadcn/ui now, please refer to their theming documentation - * https://ui.shadcn.com/docs/theming - * - * Or you can use their themes, and replace the color in /src/app/globals.css - * https://ui.shadcn.com/themes - * - * Tailwind color name. - * Ref: https://tailwindcss.com/docs/customizing-colors - */ - // defaultAccentColor: "teal", - - /** - * Site wide password protection - * If this is set, all files and folders will be protected by this password - * - * The site password are set from Environment Variable (NEXT_GDRIVE_INDEX_PASSWORD) - * It's because I don't want to store sensitive data in the code - */ - privateIndex: ${configuration.site.privateIndex ? "true" : "false"}, - - /** - * Maximum breadcrumb length - * If the breadcrumb is longer than this, it will be shortened - */ - breadcrumbMax: 3, - - /** - * Toast notification configuration - * - * position: Self-explanatory - * duration: duration before the toast disappear in milliseconds - */ - toaster: { - position: "bottom-right", - duration: 3000, - }, - - /** - * This section should have autocomplete for both the object and the icon name - * - * Example item: - * { - * icon: string, // icon name from lucide icons (https://lucide.dev/icons/) - * name: string, - * href: string, - * external?: boolean - * } - */ - navbarItems: [], - - /** - * Add support / donation links on the navbar - * - * Example item: - * { - * name: string, - * currency: string, - * href: string, - * } - */ - supports: [], - }, -}; - -export default config;`; - - // downloadBlob(new Blob([envContent], { type: "text/plain" }), "env"); - // downloadBlob( - // new Blob([configContent], { type: "text/typescript" }), - // "gindex.config.ts", - // ); - - toast.success("Configuration file downloaded!", { - id: "download-config", - }); - } catch (error) { - const e = error as Error; - console.error(e); - toast.error(e.message, { - id: "download-config", - }); - } finally { - setDownloadState("idle"); - } - } - function onErrorSet< - T extends ConfigurationCategory = ConfigurationCategory, - K extends ConfigurationKeys = ConfigurationKeys, - >(category: T, key: K, value: string) { - setError((prev) => ({ - ...prev, - [category]: { - ...prev[category], - [key]: value, - }, - })); - } - - if (loading) - return ( - - - - - - ); - - return ( - - -
- - App Configuration - - v{config.version} -
- -
- - If you found any bugs or issues, please report it to the [issue tracker](https://github.com/mbahArip/next-gdrive-index/issues) -> I'll try to fix it as soon as possible`} - view='markdown' - /> - - onErrorSet("environment", key, value), - }} - onReset={onReset} - /> - onErrorSet("api", key, value), - }} - onReset={onReset} - /> - onErrorSet("site", key, value), - }} - onReset={onReset} - /> - -
- - -
-
-
- ); -} - -export function CustomizeTheme() { - const [colors, setColors] = useState({ - primary: { h: 200, s: 50, l: 50 }, - secondary: { h: 200, s: 50, l: 50 }, - }); - - return ( - - - - Customize Theme - - - - - - - - ); -} diff --git a/src/app/[...rest]/deploy/index.tsx b/src/app/[...rest]/deploy/index.tsx index f911edc..71bbdbf 100644 --- a/src/app/[...rest]/deploy/index.tsx +++ b/src/app/[...rest]/deploy/index.tsx @@ -1,64 +1,30 @@ "use client"; import { icons } from "lucide-react"; -import { useMemo, useState } from "react"; -import { z } from "zod"; -import { cn } from "~/utils"; +import { useMemo } from "react"; +import { getting_started, migration, new_user, shared_drive } from "~/data/docs"; -import Markdown from "~/app/@markdown"; -import Icon from "~/components/Icon"; +import { Icon, Markdown } from "~/components/Global"; +import { ConfigurationForm } from "~/components/Guide/Configuration"; +import { ThemeForm } from "~/components/Guide/Theme"; import { Alert, AlertDescription, AlertTitle } from "~/components/ui/alert"; -import { Button } from "~/components/ui/button"; import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card"; -import { - DropdownMenu, - DropdownMenuContent, - DropdownMenuItem, - DropdownMenuTrigger, -} from "~/components/ui/dropdown-menu"; import { Separator } from "~/components/ui/separator"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "~/components/ui/tabs"; -import useMediaQuery from "~/hooks/useMediaQuery"; +import { cn } from "~/utils/cn"; -import { - Configuration, - CustomizeTheme, - getting_started, - migration_guide, - new_user_guide, - shared_drive_guide, -} from "./docs"; - -// type Section = -// | "start" -// | "new-user" -// | "shared-drive" -// | "migrating" -// | "config" -// | "theme"; -const SchemaSection = z.enum([ - "start", - "new-user", - "shared-drive", - "migrating", - "config", - "theme", -]); -type Section = z.infer; +const Sections = ["start", "new-user", "shared-drive", "migrating", "config", "theme"] as const; +type Section = (typeof Sections)[number]; type SectionItem = { id: Section; title: string; icon: keyof typeof icons; }; + export default function DeployGuidePage() { const sectionMenu = useMemo( () => [ - // { - // id: "start", - // title: "Getting Started", - // icon: "NotebookText", - // }, { id: "new-user", title: "New User Guide", @@ -74,95 +40,27 @@ export default function DeployGuidePage() { title: "Shared Drive Guide", icon: "Database", }, - // { - // id: "config", - // title: "App Configuration", - // icon: "Settings", - // }, - // { - // id: "theme", - // title: "Theme Customization", - // icon: "PaintRoller", - // }, ], [], ); - const [sectionOpen, setSectionOpen] = useState(false); - - const isDesktop = useMediaQuery("(min-width: 768px)"); return ( -
-
- -
-
- - - - - - {sectionMenu.map((item) => ( - -
{ - const target = document.getElementById(item.id); - if (target) { - target.scrollIntoView({ behavior: "smooth" }); - } - }} - > - {item.title} - -
-
- ))} -
-
-
+
+ About this guide + +

{`If you can see this guide on your deployment. +Please set the \`showDeployGuide\` to false on the config files. Since it will take up the \`deploy\` route.`}

+
+
+
+ @@ -172,7 +70,6 @@ export default function DeployGuidePage() { @@ -191,21 +88,7 @@ export default function DeployGuidePage() { ))} - {/* - - - Deployment Guide - - - - - - - */} + @@ -214,8 +97,7 @@ export default function DeployGuidePage() { @@ -229,7 +111,7 @@ export default function DeployGuidePage() { @@ -244,8 +126,7 @@ export default function DeployGuidePage() { @@ -263,9 +144,7 @@ export default function DeployGuidePage() { />
Heads up! - - The value of the form will be reset when you switch tabs. - + The value of the form will be reset when you switch tabs.
@@ -287,11 +166,12 @@ export default function DeployGuidePage() { Theme Customization + - + - + diff --git a/src/app/[...rest]/page.tsx b/src/app/[...rest]/page.tsx index 5cfb7a3..4081c4d 100644 --- a/src/app/[...rest]/page.tsx +++ b/src/app/[...rest]/page.tsx @@ -1,35 +1,26 @@ import { Metadata, ResolvedMetadata } from "next"; import { notFound } from "next/navigation"; import { z } from "zod"; -import { Schema_File } from "~/schema"; -import { cn } from "~/utils"; +import { Actions, Explorer, FilePath, Readme } from "~/components/Explorer"; +import { Password } from "~/components/Layout"; +import { PreviewLayout } from "~/components/Preview"; import { Card, CardContent, CardHeader, CardTitle } from "~/components/ui/card"; import { Separator } from "~/components/ui/separator"; -import { decryptData } from "~/utils/encryptionHelper/hash"; +import { cn } from "~/utils/cn"; +import { decryptData } from "~/utils/encryptionHelper"; import gdrive from "~/utils/gdriveInstance"; import { getFileType } from "~/utils/previewHelper"; -import config from "~/config/gIndex.config"; +import { Schema_File } from "~/types/schema"; + +import { CheckPassword, CheckPaths, GetBanner, GetFile, GetFiles, GetReadme } from "actions"; +import config from "config"; -import FileBrowser from "../@explorer"; -import Header from "../@header"; -import HeaderButton from "../@header.button"; -import Password from "../@password"; -import FilePreviewLayout from "../@preview.layout"; -import Readme from "../@readme"; -import { - CheckPassword, - CheckPaths, - GetBanner, - GetFile, - GetFiles, - GetReadme, -} from "../actions"; import DeployGuidePage from "./deploy"; -export const revalidate = 300; +export const revalidate = 60; export const dynamic = "force-dynamic"; type Props = { @@ -38,12 +29,8 @@ type Props = { }; }; -export async function generateMetadata( - { params: { rest } }: Props, - parent: ResolvedMetadata, -): Promise { - if (rest[0] === "deploy" && config.showDeployGuide) - return { title: "Deploy Guide" }; +export async function generateMetadata({ params: { rest } }: Props, parent: ResolvedMetadata): Promise { + if (rest.length === 1 && rest[0] === "deploy" && config.showDeployGuide) return { title: "Deploy Guide" }; const paths = await CheckPaths(rest); if (!paths.success) return { title: "Not Found" }; @@ -56,17 +43,12 @@ export async function generateMetadata( return { title: data.name, - description: data.mimeType?.includes("folder") - ? `Browse ${data.name} files` - : `View ${data.name}`, + description: data.mimeType?.includes("folder") ? `Browse ${data.name} files` : `View ${data.name}`, openGraph: { images: banner ? [ { url: `/api/og/${banner}`, - // url: `/api/og/${ - // data.mimeType.startsWith("image") ? data.encryptedId : banner - // }`, width: 1200, height: 630, }, @@ -77,8 +59,7 @@ export async function generateMetadata( } export default async function RestPage({ params: { rest } }: Props) { - if (rest[0] === "deploy" && config.showDeployGuide) - return ; + if (rest.length === 1 && rest[0] === "deploy" && config.showDeployGuide) return ; const paths = await CheckPaths(rest); if (!paths.success) notFound(); @@ -86,11 +67,7 @@ export default async function RestPage({ params: { rest } }: Props) { if (!unlocked.success) { if (!unlocked.path) - throw new Error( - `No path returned from password checking${ - unlocked.message && `, ${unlocked.message}` - }`, - ); + throw new Error(`No path returned from password checking${unlocked.message && `, ${unlocked.message}`}`); return ( , string]; } else { - return values as [ - { files: z.infer[]; nextPageToken?: string }, - string, - ]; + return values as [{ files: z.infer[]; nextPageToken?: string }, string]; } }); - let fileType; - if (file.fileExtension && file.mimeType) { - fileType = getFileType(file.fileExtension, file.mimeType); - } - const isFile = !("files" in data); return (
-
({ + ({ label: decodeURIComponent(item), href: index === array.length - 1 ? undefined : `${item}`, }))} /> -
- {isFile ? ( - ) : ( <> @@ -159,40 +128,28 @@ export default async function RestPage({ params: { rest } }: Props) {
Browse files - +
- - {readme && ( - - //
- // - // - // README.md - // - // - // - // - // - // - //
- )} )} -
+ + + {readme && ( + + )}
); } diff --git a/src/app/actions.ts b/src/app/actions.ts index 90ffc18..6ea365f 100644 --- a/src/app/actions.ts +++ b/src/app/actions.ts @@ -4,14 +4,14 @@ import crypto from "crypto"; import { revalidatePath } from "next/cache"; import { cookies } from "next/headers"; import { z } from "zod"; -import { Schema_File } from "~/schema"; -import { decryptData, encryptData } from "~/utils/encryptionHelper/hash"; -import gdrive from "~/utils/gdriveInstance"; +import { decryptData, encryptData } from "~/utils/encryptionHelper"; +import gdrive, { gdriveNoCache } from "~/utils/gdriveInstance"; import { Constant } from "~/types/constant"; +import { Schema_File } from "~/types/schema"; -import config from "~/config/gIndex.config"; +import config from "config"; export async function CheckSitePassword(): Promise<{ success: boolean; @@ -36,9 +36,7 @@ export async function CheckSitePassword(): Promise<{ const password = store.get(Constant.cookies_SitePassword)?.value || ""; const decryptedPassword = await decryptData(password); if (decryptedPassword !== process.env.SITE_PASSWORD) - throw new Error( - "Saved password is incorrect, please re-enter the password", - ); + throw new Error("Saved password is incorrect, please re-enter the password"); return { success: true, @@ -156,32 +154,58 @@ export async function CheckPaths(paths: string[]): Promise< const data = await Promise.all(promises); const notFoundIndex = data.findIndex((item) => !item); - if (notFoundIndex !== -1) - throw new Error(`Path not found: ${paths[notFoundIndex]}`); + if (notFoundIndex !== -1) throw new Error(`Path not found: ${paths[notFoundIndex]}`); // Check if each path is valid let valid = true; let invalidPath: string | undefined; const decryptedRootId = await decryptData(config.apiConfig.rootFolder); - for (const [index, path] of data.entries()) { + const dataWithIndex = data.map((item, index) => { + return { + ...item, + index: index, + }; + }); + const filteredPaths: { path: string; data: { id: string; parents: string; mimeType: string }[] }[] = []; + + for (const item of dataWithIndex) { if (!valid) break; - if (index === 0) { - if ( - path?.data[0].parents === decryptedRootId || - path?.data[0].parents === decryptedSharedDrive - ) - break; - } else { - if (path?.data[0].parents === data[index - 1]?.data[0].id) break; + // Loop through data + // If the current index is 0, check if the parents is the root folder or shared drive + // If the current index is not 0, check if the parents is the previous data id from the filteredPaths + + // Use filteredPaths because it will only contain the valid path + // So if filteredPaths length is not equal to paths length, then it means there is an invalid path + for (const path of item.data || []) { + if (item.index === 0) { + if (path.parents === decryptedRootId || path.parents === decryptedSharedDrive) { + filteredPaths.push({ + path: item.path!, + data: [{ id: path.id!, parents: path.parents!, mimeType: path.mimeType! }], + }); + break; + } + } else { + if (path.parents === filteredPaths[item.index - 1]?.data?.[0].id) { + filteredPaths.push({ + path: item.path!, + data: [{ id: path.id!, parents: path.parents!, mimeType: path.mimeType! }], + }); + break; + } + } } - valid = false; - invalidPath = data[index]?.path; } + if (filteredPaths.length !== paths.length) { + valid = false; + invalidPath = dataWithIndex[filteredPaths.length]?.path; + } + if (!valid) throw new Error(`Invalid path: ${invalidPath}`); const ids: { path: string; id: string }[] = []; - for (const item of data) { + for (const item of filteredPaths) { if (item) { const encryptedId = await encryptData(item.data[0].id as string); ids.push({ @@ -203,9 +227,7 @@ export async function CheckPaths(paths: string[]): Promise< }; } } -export async function CheckPassword( - paths: { path: string; id: string }[], -): Promise< +export async function CheckPassword(paths: { path: string; id: string }[]): Promise< | { success: false; message?: string; @@ -230,7 +252,7 @@ export async function CheckPassword( `trashed = false`, `(${ids.map((id) => `'${id}' in parents`).join(" or ")})`, // Filter by paths id ]; - const { data: password } = await gdrive.files + const { data: password } = await gdriveNoCache.files .list({ q: query.join(" and "), fields: "files(id, name, mimeType, parents)", @@ -250,21 +272,15 @@ export async function CheckPassword( // To save processing time, skip if password file not found if (!password.files?.length) return { success: true }; - const protectedFolder = password.files - .filter((file) => ids.includes(file.parents?.[0] as string)) - ?.shift(); // Shift to get only the nearest folder + const protectedFolder = password.files.filter((file) => ids.includes(file.parents?.[0] as string))?.shift(); // Shift to get only the nearest folder // To save processing time, skip if all of the paths are not protected if (!protectedFolder) return { success: true }; const store = cookies(); - const folderIndex = ids.findIndex( - (item) => item === protectedFolder.parents?.[0], - ); + const folderIndex = ids.findIndex((item) => item === protectedFolder.parents?.[0]); - const cookiesValue = JSON.parse( - store.get(Constant.cookies_FolderPassword)?.value || "{}", - ); + const cookiesValue = JSON.parse(store.get(Constant.cookies_FolderPassword)?.value || "{}"); const currentFolder = paths[folderIndex]; if (!cookiesValue[currentFolder.id]) throw { @@ -321,9 +337,7 @@ export async function SetPassword( }> { try { const store = cookies(); - const cookiesValue = JSON.parse( - store.get(Constant.cookies_FolderPassword)?.value || "{}", - ); + const cookiesValue = JSON.parse(store.get(Constant.cookies_FolderPassword)?.value || "{}"); const updatedValue = { ...cookiesValue, [path]: await encryptData(password), @@ -352,13 +366,7 @@ export async function SetPassword( } } -export async function GetFiles({ - id, - pageToken, -}: { - id?: string; - pageToken?: string; -}): Promise<{ +export async function GetFiles({ id, pageToken }: { id?: string; pageToken?: string }): Promise<{ files: z.infer[]; nextPageToken?: string; }> { @@ -372,14 +380,10 @@ export async function GetFiles({ decryptedSharedDrive = await decryptData(config.apiConfig.sharedDrive); } - const filterName = config.apiConfig.hiddenFiles - .map((item) => `not name = '${item}'`) - .join(" and "); - const query: string = [ - ...config.apiConfig.defaultQuery, - `'${decryptedId}' in parents`, - `${filterName}`, - ].join(" and "); + const filterName = config.apiConfig.hiddenFiles.map((item) => `not name = '${item}'`).join(" and "); + const query: string = [...config.apiConfig.defaultQuery, `'${decryptedId}' in parents`, `${filterName}`].join( + " and ", + ); const data = await gdrive.files.list({ q: query, @@ -396,21 +400,16 @@ export async function GetFiles({ }); const encryptedData: z.infer[] = []; - if (!data.data.files?.length) - return { files: [], nextPageToken: undefined }; + if (!data.data.files?.length) return { files: [], nextPageToken: undefined }; for (const file of data.data.files) { encryptedData.push({ mimeType: file.mimeType as string, encryptedId: await encryptData(file.id as string), name: file.name as string, trashed: (file.trashed as boolean) ?? false, - modifiedTime: new Date( - file.modifiedTime as string, - ).toLocaleDateString(), + modifiedTime: new Date(file.modifiedTime as string).toLocaleDateString(), fileExtension: file.fileExtension || undefined, - encryptedWebContentLink: file.webContentLink - ? await encryptData(file.webContentLink) - : undefined, + encryptedWebContentLink: file.webContentLink ? await encryptData(file.webContentLink) : undefined, size: file.size ? Number(file.size) : undefined, thumbnailLink: file.thumbnailLink || undefined, imageMediaMetadata: file.imageMediaMetadata @@ -441,9 +440,7 @@ export async function GetFiles({ throw new Error(e.message); } } -export async function GetFile( - encryptedId: string, -): Promise> { +export async function GetFile(encryptedId: string): Promise> { try { const decryptedId = await decryptData(encryptedId); const { data: file } = await gdrive.files.get({ @@ -459,9 +456,7 @@ export async function GetFile( trashed: (file.trashed as boolean) ?? false, modifiedTime: new Date(file.modifiedTime as string).toLocaleDateString(), fileExtension: file.fileExtension || undefined, - encryptedWebContentLink: file.webContentLink - ? await encryptData(file.webContentLink) - : undefined, + encryptedWebContentLink: file.webContentLink ? await encryptData(file.webContentLink) : undefined, size: file.size ? Number(file.size) : undefined, thumbnailLink: file.thumbnailLink || undefined, imageMediaMetadata: file.imageMediaMetadata @@ -504,9 +499,7 @@ export async function SearchFile( const query: string[] = [ ...config.apiConfig.defaultQuery, `name contains '${keyword}'`, - config.apiConfig.hiddenFiles - .map((item) => `not name = '${item}'`) - .join(" and "), + config.apiConfig.hiddenFiles.map((item) => `not name = '${item}'`).join(" and "), ]; const data = await gdrive.files.list({ q: query.join(" and "), @@ -522,21 +515,16 @@ export async function SearchFile( }), }); const encryptedData: z.infer[] = []; - if (!data.data.files?.length) - return { files: [], nextPageToken: undefined }; + if (!data.data.files?.length) return { files: [], nextPageToken: undefined }; for (const file of data.data.files) { encryptedData.push({ mimeType: file.mimeType as string, encryptedId: await encryptData(file.id as string), name: file.name as string, trashed: (file.trashed as boolean) ?? false, - modifiedTime: new Date( - file.modifiedTime as string, - ).toLocaleDateString(), + modifiedTime: new Date(file.modifiedTime as string).toLocaleDateString(), fileExtension: file.fileExtension || undefined, - encryptedWebContentLink: file.webContentLink - ? await encryptData(file.webContentLink) - : undefined, + encryptedWebContentLink: file.webContentLink ? await encryptData(file.webContentLink) : undefined, size: file.size ? Number(file.size) : undefined, thumbnailLink: file.thumbnailLink || undefined, imageMediaMetadata: file.imageMediaMetadata @@ -611,8 +599,7 @@ export async function GetContent(encryptedId: string): Promise { }, ); - if (typeof file !== "string") - throw new Error("It seems the file is not a text file"); + if (typeof file !== "string") throw new Error("It seems the file is not a text file"); return file as string; } catch (error) { @@ -621,9 +608,7 @@ export async function GetContent(encryptedId: string): Promise { throw new Error(e.message); } } -export async function GetReadme( - encryptedId: string | undefined, -): Promise { +export async function GetReadme(encryptedId: string | undefined): Promise { try { let decryptedId; if (encryptedId) decryptedId = await decryptData(encryptedId); @@ -635,7 +620,8 @@ export async function GetReadme( } const query: string[] = [ - ...config.apiConfig.defaultQuery, + "trashed = false", + "(not mimeType contains 'folder')", `name = '${config.apiConfig.specialFile.readme}'`, `'${decryptedId}' in parents`, ]; @@ -652,11 +638,57 @@ export async function GetReadme( corpora: "drive", }), }); + if (!data.files?.length) return null; + let file; + + if (data.files.length === 1) { + file = data.files[0]; + } else { + // Check by mimetype, use google-apps.shortcut last + file = data.files.find((item) => item.mimeType === "text/markdown"); + if (!file) { + file = data.files.find((item) => item.mimeType === "application/vnd.google-apps.shortcut"); + } + } + + if (!file) return null; + if ( + file.mimeType !== "text/markdown" && + file.mimeType !== "application/vnd.google-apps.shortcut" && + file.mimeType !== "text/plain" + ) + return null; + + if (file.mimeType === "application/vnd.google-apps.shortcut") { + const { data: shortcutData } = (await gdrive.files.get({ + fileId: file.id as string, + fields: "shortcutDetails", + supportsAllDrives: config.apiConfig.isTeamDrive, + })) as { + data: { shortcutDetails: { targetId: string; targetMimeType: string } }; + }; + if (!shortcutData.shortcutDetails.targetId) return null; + if (shortcutData.shortcutDetails.targetMimeType !== "text/markdown") return null; + + const { data: content } = await gdrive.files.get( + { + fileId: shortcutData.shortcutDetails.targetId, + alt: "media", + supportsAllDrives: config.apiConfig.isTeamDrive, + }, + { + responseType: "text", + }, + ); + + return content as string; + } + const { data: content } = await gdrive.files.get( { - fileId: data.files[0].id as string, + fileId: file.id as string, alt: "media", supportsAllDrives: config.apiConfig.isTeamDrive, }, @@ -672,9 +704,7 @@ export async function GetReadme( throw new Error(e.message); } } -export async function GetBanner( - encryptedId: string | undefined, -): Promise { +export async function GetBanner(encryptedId: string | undefined): Promise { try { let decryptedId; if (encryptedId) decryptedId = await decryptData(encryptedId); @@ -722,14 +752,10 @@ export async function GetWebContent(encrypted: string): Promise { throw new Error(e.message); } } -export async function CreateDownloadToken( - duration: number = config.apiConfig.temporaryTokenDuration, -): Promise { +export async function CreateDownloadToken(duration: number = config.apiConfig.temporaryTokenDuration): Promise { try { const data = { - expiredAt: - Date.now() + - duration * 60 * 60 * 1000 * config.apiConfig.temporaryTokenDuration, + expiredAt: Date.now() + duration * 60 * 60 * 1000 * config.apiConfig.temporaryTokenDuration, }; const token = await encryptData(JSON.stringify(data)); return token; @@ -748,8 +774,7 @@ export async function CheckDownloadToken(token: string): Promise<{ if (decryptToken.expiredAt < Date.now()) { return { success: false, - message: - "Download token expired, please click the download button again to get a new token", + message: "Download token expired, please click the download button again to get a new token", }; } @@ -776,10 +801,7 @@ export async function GenerateAESKey(): Promise { throw new Error(e.message); } } -export async function VerifyAESKey( - data: string, - key: string, -): Promise { +export async function VerifyAESKey(data: string, key: string): Promise { try { let paddedKey; if (key.length < 16) { diff --git a/src/app/api/download/[encryptedId]/route.ts b/src/app/api/download/[encryptedId]/route.ts index 15cb631..39956d5 100644 --- a/src/app/api/download/[encryptedId]/route.ts +++ b/src/app/api/download/[encryptedId]/route.ts @@ -1,17 +1,10 @@ import { NextRequest, NextResponse } from "next/server"; -import { - CheckDownloadToken, - CheckPassword, - CheckPaths, - CheckSitePassword, - RedirectSearchFile, -} from "~/app/actions"; - -import { decryptData } from "~/utils/encryptionHelper/hash"; +import { decryptData } from "~/utils/encryptionHelper"; import { gdriveNoCache as gdrive } from "~/utils/gdriveInstance"; -import config from "~/config/gIndex.config"; +import { CheckDownloadToken, CheckPassword, CheckPaths, CheckSitePassword, RedirectSearchFile } from "actions"; +import config from "config"; export const dynamic = "force-dynamic"; @@ -33,10 +26,7 @@ export async function GET( const tokenValidity = await CheckDownloadToken(token); if (!tokenValidity.success) throw new Error(tokenValidity.message); - if ( - config.siteConfig.privateIndex && - !config.apiConfig.allowDownloadProtectedFile - ) { + if (config.siteConfig.privateIndex && !config.apiConfig.allowDownloadProtectedFile) { const unlocked = await CheckSitePassword(); if (!unlocked.success) { return new NextResponse( @@ -65,12 +55,9 @@ If you've already entered the password, please make sure your browser is not blo if (!checkPath.success) throw new Error("File not found"); const unlocked = await CheckPassword(checkPath.data); if (!unlocked.success) { - if (!unlocked.path) - throw new Error("No path returned from password checking"); + if (!unlocked.path) throw new Error("No path returned from password checking"); - const lockedIndex = checkPath.data.findIndex( - (path) => path.id === unlocked.path, - ); + const lockedIndex = checkPath.data.findIndex((path) => path.id === unlocked.path); // Get all path until the locked index, then join them const path = checkPath.data .slice(0, lockedIndex + 1) @@ -91,13 +78,9 @@ If you've already entered the password, please make sure your browser is not blo } const fileSize = Number(fileMeta.data.size || 0); - if (!fileMeta.data.webContentLink) - throw new Error("No download link found"); + if (!fileMeta.data.webContentLink) throw new Error("No download link found"); - if ( - config.apiConfig.maxFileSize && - fileSize > config.apiConfig.maxFileSize - ) { + if (config.apiConfig.maxFileSize && fileSize > config.apiConfig.maxFileSize) { const contentUrl = new URL(fileMeta.data.webContentLink); contentUrl.searchParams.set("confirm", "1"); return NextResponse.redirect(contentUrl, { diff --git a/src/app/api/internal/encrypt/route.ts b/src/app/api/internal/encrypt/route.ts index c62f22e..7fdbe39 100644 --- a/src/app/api/internal/encrypt/route.ts +++ b/src/app/api/internal/encrypt/route.ts @@ -1,6 +1,6 @@ import { NextRequest, NextResponse } from "next/server"; -import { encryptData } from "~/utils/encryptionHelper/hash"; +import { encryptData } from "~/utils/encryptionHelper"; export const dynamic = "force-dynamic"; @@ -8,11 +8,7 @@ export async function GET(request: NextRequest) { try { const sp = new URL(request.nextUrl).searchParams; const query = sp.get("q"); - if (!query) - return new NextResponse( - "Add query parameter 'q' with the value to encrypt", - { status: 400 }, - ); + if (!query) return new NextResponse("Add query parameter 'q' with the value to encrypt", { status: 400 }); const encrypted = await encryptData(query); diff --git a/src/app/api/og/[encryptedId]/route.ts b/src/app/api/og/[encryptedId]/route.ts index a569935..61f5ddf 100644 --- a/src/app/api/og/[encryptedId]/route.ts +++ b/src/app/api/og/[encryptedId]/route.ts @@ -1,9 +1,9 @@ import { NextRequest, NextResponse } from "next/server"; -import { decryptData } from "~/utils/encryptionHelper/hash"; +import { decryptData } from "~/utils/encryptionHelper"; import gdrive from "~/utils/gdriveInstance"; -import config from "~/config/gIndex.config"; +import config from "config"; type Props = { params: { @@ -11,10 +11,7 @@ type Props = { }; }; -export async function GET( - request: NextRequest, - { params: { encryptedId } }: Props, -) { +export async function GET(request: NextRequest, { params: { encryptedId } }: Props) { try { const decryptedId = await decryptData(encryptedId); const { data } = await gdrive.files.get({ diff --git a/src/app/api/raw/[...rest]/route.ts b/src/app/api/raw/[...rest]/route.ts index 832c865..2481ddb 100644 --- a/src/app/api/raw/[...rest]/route.ts +++ b/src/app/api/raw/[...rest]/route.ts @@ -1,16 +1,13 @@ import { NextRequest, NextResponse } from "next/server"; -import { CheckPassword, CheckPaths, GetFile } from "~/app/actions"; -import { decryptData } from "~/utils/encryptionHelper/hash"; +import { decryptData } from "~/utils/encryptionHelper"; -import config from "~/config/gIndex.config"; +import { CheckPassword, CheckPaths, GetFile } from "actions"; +import config from "config"; export const dynamic = "force-dynamic"; -export async function GET( - request: NextRequest, - { params: { rest } }: { params: { rest: string[] } }, -) { +export async function GET(request: NextRequest, { params: { rest } }: { params: { rest: string[] } }) { try { const sp = new URL(request.nextUrl).searchParams; const token = sp.get("token"); @@ -22,31 +19,18 @@ export async function GET( if (!config.apiConfig.allowDownloadProtectedFile) { const unlocked = await CheckPassword(paths.data); if (!unlocked.success) - throw new Error( - unlocked.path - ? unlocked.message - : "No path returned from password checking", - ); + throw new Error(unlocked.path ? unlocked.message : "No path returned from password checking"); } const encryptedId = paths.data.pop()?.id; - if (!encryptedId) - throw new Error("Failed to get encrypted ID, try to refresh the page."); + if (!encryptedId) throw new Error("Failed to get encrypted ID, try to refresh the page."); if (token !== encryptedId) throw new Error("Invalid token"); const data = await GetFile(encryptedId); - if (data.mimeType?.includes("folder")) - throw new Error("Can't download folder"); - if ( - !data.mimeType.includes("video") && - !data.mimeType.includes("image") && - !data.mimeType.includes("audio") - ) - throw new Error( - "Raw link only available for video, image, and audio files", - ); - if (!data.encryptedWebContentLink) - throw new Error("No download link found"); + if (data.mimeType?.includes("folder")) throw new Error("Can't download folder"); + if (!data.mimeType.includes("video") && !data.mimeType.includes("image") && !data.mimeType.includes("audio")) + throw new Error("Raw link only available for video, image, and audio files"); + if (!data.encryptedWebContentLink) throw new Error("No download link found"); const decryptedWebContent = await decryptData(data.encryptedWebContentLink); return new NextResponse(null, { diff --git a/src/app/api/stream/[encryptedId]/helper.ts b/src/app/api/stream/[encryptedId]/helper.ts deleted file mode 100644 index d12e947..0000000 --- a/src/app/api/stream/[encryptedId]/helper.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Readable } from "stream"; - -async function* nodeStreamToIterator(stream: any) { - for await (const chunk of stream) { - yield chunk; - } -} - -function iteratorToStream(iterator: AsyncGenerator) { - return new ReadableStream({ - async pull(controller) { - const { done, value } = await iterator.next(); - if (done) { - controller.close(); - } else { - controller.enqueue(value); - } - }, - }); -} -export function streamFile(body: Readable): ReadableStream { - const data: ReadableStream = iteratorToStream(nodeStreamToIterator(body)); - return data; -} diff --git a/src/app/api/stream/[encryptedId]/route.ts b/src/app/api/stream/[encryptedId]/route.ts index e6285fc..46c85e6 100644 --- a/src/app/api/stream/[encryptedId]/route.ts +++ b/src/app/api/stream/[encryptedId]/route.ts @@ -1,17 +1,11 @@ import { NextRequest, NextResponse } from "next/server"; -import { - CheckDownloadToken, - CheckPassword, - CheckPaths, - RedirectSearchFile, -} from "~/app/actions"; - -import { decryptData } from "~/utils/encryptionHelper/hash"; +import { decryptData } from "~/utils/encryptionHelper"; import { gdriveNoCache as gdrive } from "~/utils/gdriveInstance"; -import isDev from "~/utils/isDev"; +import { isDev } from "~/utils/isDev"; -import config from "~/config/gIndex.config"; +import { CheckDownloadToken, CheckPassword, CheckPaths, RedirectSearchFile } from "actions"; +import config from "config"; export const dynamic = "force-dynamic"; @@ -57,18 +51,12 @@ export async function GET( const [filePaths, fileMeta] = await Promise.all([_filePaths, _fileMeta]); - const isFull = - Number(request.headers.get("Range")?.split("-")[1] || 0) === - Number(fileMeta.data.size || "1") - 1; + const isFull = Number(request.headers.get("Range")?.split("-")[1] || 0) === Number(fileMeta.data.size || "1") - 1; const fileSize = Number(fileMeta.data.size || 0); - if (!fileMeta.data.webContentLink) - throw new Error("No download link found"); + if (!fileMeta.data.webContentLink) throw new Error("No download link found"); - if ( - config.apiConfig.streamMaxSize && - fileSize > config.apiConfig.streamMaxSize - ) { + if (config.apiConfig.streamMaxSize && fileSize > config.apiConfig.streamMaxSize) { throw new Error("File is too large to stream"); } @@ -77,12 +65,9 @@ export async function GET( if (!checkPath.success) throw new Error("File not found"); const unlocked = await CheckPassword(checkPath.data); if (!unlocked.success) { - if (!unlocked.path) - throw new Error("No path returned from password checking"); + if (!unlocked.path) throw new Error("No path returned from password checking"); - const lockedIndex = checkPath.data.findIndex( - (path) => path.id === unlocked.path, - ); + const lockedIndex = checkPath.data.findIndex((path) => path.id === unlocked.path); // Get all path until the locked index, then join them const path = checkPath.data .slice(0, lockedIndex + 1) diff --git a/src/app/api/thumb/[encryptedId]/route.ts b/src/app/api/thumb/[encryptedId]/route.ts index eb7f431..0255c3d 100644 --- a/src/app/api/thumb/[encryptedId]/route.ts +++ b/src/app/api/thumb/[encryptedId]/route.ts @@ -1,10 +1,10 @@ import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; -import { decryptData } from "~/utils/encryptionHelper/hash"; -import isDev from "~/utils/isDev"; +import { decryptData } from "~/utils/encryptionHelper"; +import { isDev } from "~/utils/isDev"; -import config from "~/config/gIndex.config"; +import config from "config"; type Props = { params: { @@ -12,10 +12,7 @@ type Props = { }; }; -export async function GET( - request: NextRequest, - { params: { encryptedId } }: Props, -) { +export async function GET(request: NextRequest, { params: { encryptedId } }: Props) { try { const searchParams = new URL(request.nextUrl).searchParams; const size = searchParams.get("size") || "512"; @@ -30,12 +27,9 @@ export async function GET( throw new Error("Invalid size"); } - const defaultImage = NextResponse.redirect( - new URL("/og.png", config.basePath), - { - status: 302, - }, - ); + const defaultImage = NextResponse.redirect(new URL("/og.png", config.basePath), { + status: 302, + }); const decryptedId = await decryptData(encryptedId); const url = `https://drive.google.com/thumbnail?id=${decryptedId}&sz=w${size}`; diff --git a/src/app/error.tsx b/src/app/error.tsx index f35a1dc..8ba565e 100644 --- a/src/app/error.tsx +++ b/src/app/error.tsx @@ -2,42 +2,28 @@ import { useRouter } from "next/navigation"; import { useEffect } from "react"; -import { cn } from "~/utils"; -import Icon from "~/components/Icon"; +import { Icon } from "~/components/Global"; import { Button } from "~/components/ui/button"; -export default function Error({ - error, - reset, -}: { - error: Error & { digest?: string }; - reset: () => void; -}) { +import { cn } from "~/utils/cn"; + +export default function Error({ error, reset }: { error: Error & { digest?: string }; reset: () => void }) { const router = useRouter(); useEffect(() => { console.error(error); }, [error]); return ( -
+
- - Something went wrong - - - More details can be found in the console - + Something went wrong + More details can be found in the console
{error.message} diff --git a/src/app/globals.css b/src/app/globals.css index cbb219c..75f52f7 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1,3 +1,4 @@ +/* Version: ${pkg.version} */ @tailwind base; @tailwind components; @tailwind utilities; @@ -50,6 +51,10 @@ --ring: 0 0% 14.9%; /* --ring: 0 0% 83.1%; */ } + + div.preview * { + @apply !transition-none; + } } html, @@ -75,7 +80,7 @@ body { @apply h-1.5 w-1.5; } ::-webkit-scrollbar-track { - @apply bg-background; + @apply bg-primary/5; } ::-webkit-scrollbar-thumb { @apply rounded-full bg-primary/25 hover:bg-primary/50; diff --git a/src/app/highlight.css b/src/app/highlight.css index cf8359e..54e65c1 100644 --- a/src/app/highlight.css +++ b/src/app/highlight.css @@ -204,10 +204,7 @@ pre { color: var(--hue-3); } -.language-javascript - .token.template-string - > .token.interpolation - > .token.interpolation-punctuation.punctuation { +.language-javascript .token.template-string > .token.interpolation > .token.interpolation-punctuation.punctuation { color: var(--hue-5-2); } @@ -335,9 +332,7 @@ div.code-toolbar > .toolbar.toolbar > .toolbar-item > span:focus { /* Hovering over a linkable line number (in the gutter area) */ /* Requires Line Numbers plugin as well */ -pre[id].linkable-line-numbers.linkable-line-numbers - span.line-numbers-rows - > span:hover:before { +pre[id].linkable-line-numbers.linkable-line-numbers span.line-numbers-rows > span:hover:before { background-color: var(--syntax-cursor-line); } diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 8050acd..deebe88 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -1,19 +1,18 @@ import { Metadata } from "next"; import { JetBrains_Mono, Outfit, Source_Sans_3 } from "next/font/google"; import "plyr-react/plyr.css"; -import { cn } from "~/utils"; +import { Footer, Navbar, Password, ThemeProvider } from "~/components/Layout"; +import ToTop from "~/components/Layout/ToTop"; + +import { cn } from "~/utils/cn"; import { formatFooter } from "~/utils/footerFormatter"; -import config from "~/config/gIndex.config"; +import { CheckSitePassword } from "actions"; +import config from "config"; -import Footer from "./@footer"; -import Navbar from "./@navbar"; -import Password from "./@password"; -import { CheckSitePassword } from "./actions"; import "./globals.css"; import "./markdown.css"; -import ThemeProvider from "./theme-provider"; const sourceSans3 = Source_Sans_3({ weight: ["300", "400", "600", "700"], @@ -41,7 +40,7 @@ export const metadata: Metadata = { metadataBase: new URL(config.basePath), title: { default: config.siteConfig.siteName, - template: config.siteConfig.siteNameTemplate || "%s", + template: config.siteConfig.siteNameTemplate?.replace("%t", config.siteConfig.siteName) || "%s", }, description: config.siteConfig.siteDescription, authors: config.siteConfig.siteAuthor @@ -74,10 +73,14 @@ export const metadata: Metadata = { robots: config.siteConfig.robots, }; -export default async function RootLayout({ - children, -}: Readonly<{ children: React.ReactNode }>) { - const unlocked = await CheckSitePassword(); +export default async function RootLayout({ children }: Readonly<{ children: React.ReactNode }>) { + let unlocked: Awaited> = { + success: true, + message: "", + }; + if (config.siteConfig.privateIndex) { + unlocked = await CheckSitePassword(); + } return ( @@ -114,9 +117,8 @@ export default async function RootLayout({ <>{children} )} - {config.siteConfig.footer && ( -