commit b73e4173a3c1e69e02ad6b4e3b43e425e57a5be9 Author: MHSanaei Date: Thu Feb 9 22:48:06 2023 +0330 3x-ui diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 00000000..6e4fd399 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,10 @@ +version: 2 +updates: + - package-ecosystem: "gomod" # See documentation for possible values + directory: "/" # Location of package manifests + schedule: + interval: "daily" + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 00000000..db2c6cbc --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,146 @@ +name: Release 3X-ui +on: + push: + tags: + - "*" + workflow_dispatch: +jobs: + release: + runs-on: ubuntu-20.04 + outputs: + upload_url: ${{ steps.create_release.outputs.upload_url }} + steps: + - name: Create Release + id: create_release + uses: actions/create-release@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + tag_name: ${{ github.ref }} + release_name: ${{ github.ref }} + draft: true + prerelease: true + linuxamd64build: + name: build x-ui amd64 version + needs: release + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v3 + - name: Set up Go + uses: actions/setup-go@v3 + with: + go-version: 1.19 + - name: build linux amd64 version + run: | + CGO_ENABLED=1 GOOS=linux GOARCH=amd64 go build -o xui-release -v main.go + mkdir x-ui + cp xui-release x-ui/xui-release + cp x-ui.service x-ui/x-ui.service + cp x-ui.sh x-ui/x-ui.sh + cd x-ui + mv xui-release x-ui + mkdir bin + cd bin + wget https://github.com/XTLS/Xray-core/releases/latest/download/Xray-linux-64.zip + unzip Xray-linux-64.zip + rm -f Xray-linux-64.zip geoip.dat geosite.dat + wget https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat + wget https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat + mv xray xray-linux-amd64 + cd .. + cd .. + - name: package + run: tar -zcvf x-ui-linux-amd64.tar.gz x-ui + - name: upload + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ needs.release.outputs.upload_url }} + asset_path: x-ui-linux-amd64.tar.gz + asset_name: x-ui-linux-amd64.tar.gz + asset_content_type: application/gzip + linuxarm64build: + name: build x-ui arm64 version + needs: release + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v3 + - name: Set up Go + uses: actions/setup-go@v3 + with: + go-version: 1.19 + - name: build linux arm64 version + run: | + sudo apt-get update + sudo apt install gcc-aarch64-linux-gnu + CGO_ENABLED=1 GOOS=linux GOARCH=arm64 CC=aarch64-linux-gnu-gcc go build -o xui-release -v main.go + mkdir x-ui + cp xui-release x-ui/xui-release + cp x-ui.service x-ui/x-ui.service + cp x-ui.sh x-ui/x-ui.sh + cd x-ui + mv xui-release x-ui + mkdir bin + cd bin + wget https://github.com/XTLS/Xray-core/releases/latest/download/Xray-linux-arm64-v8a.zip + unzip Xray-linux-arm64-v8a.zip + rm -f Xray-linux-arm64-v8a.zip geoip.dat geosite.dat + wget https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat + wget https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat + mv xray xray-linux-arm64 + cd .. + cd .. + - name: package + run: tar -zcvf x-ui-linux-arm64.tar.gz x-ui + - name: upload + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ needs.release.outputs.upload_url }} + asset_path: x-ui-linux-arm64.tar.gz + asset_name: x-ui-linux-arm64.tar.gz + asset_content_type: application/gzip + linuxs390xbuild: + name: build x-ui s390x version + needs: release + runs-on: ubuntu-20.04 + steps: + - uses: actions/checkout@v3 + - name: Set up Go + uses: actions/setup-go@v3 + with: + go-version: 1.19 + - name: build linux s390x version + run: | + sudo apt-get update + sudo apt install gcc-s390x-linux-gnu -y + CGO_ENABLED=1 GOOS=linux GOARCH=s390x CC=s390x-linux-gnu-gcc go build -o xui-release -v main.go + mkdir x-ui + cp xui-release x-ui/xui-release + cp x-ui.service x-ui/x-ui.service + cp x-ui.sh x-ui/x-ui.sh + cd x-ui + mv xui-release x-ui + mkdir bin + cd bin + wget https://github.com/XTLS/Xray-core/releases/latest/download/Xray-linux-s390x.zip + unzip Xray-linux-s390x.zip + rm -f Xray-linux-s390x.zip geoip.dat geosite.dat + wget https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geoip.dat + wget https://github.com/Loyalsoldier/v2ray-rules-dat/releases/latest/download/geosite.dat + mv xray xray-linux-s390x + cd .. + cd .. + - name: package + run: tar -zcvf x-ui-linux-s390x.tar.gz x-ui + - name: upload + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ needs.release.outputs.upload_url }} + asset_path: x-ui-linux-s390x.tar.gz + asset_name: x-ui-linux-s390x.tar.gz + asset_content_type: application/gzip diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..63ca6b69 --- /dev/null +++ b/.gitignore @@ -0,0 +1,13 @@ +.idea +tmp +bin/xray-darwin-arm64 +bin/config.json +dist/ +x-ui-*.tar.gz +/x-ui +/release.sh +.sync* +main +release/ +access.log +.cache diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 00000000..46bad8e4 --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# 3x-ui +> **Disclaimer: This project is only for personal learning and communication, please do not use it for illegal purposes, please do not use it in a production environment** + +# Install & Upgrade + +``` +bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh) +``` + +# SSL +``` +apt-get install certbot -y +certbot certonly --standalone --agree-tos --register-unsafely-without-email -d yourdomain.com +certbot renew --dry-run +``` + +# Default settings + +- Port: 2053 +- user: admin +- password: admin +- database path: /etc/x-ui/x-ui.db + +- before you set ssl on settings +- http:// ip or domain:2053/xui + +- After you set ssl on settings +- https://yourdomain:2053/xui + +# suggestion system +- Ubuntu 20.04+ + +# pic + +![1](https://raw.githubusercontent.com/MHSanaei/3x-ui/main/media/1.png) +![2](https://raw.githubusercontent.com/MHSanaei/3x-ui/main/media/2.png) +![3](https://raw.githubusercontent.com/MHSanaei/3x-ui/main/media/3.png) +![4](https://raw.githubusercontent.com/MHSanaei/3x-ui/main/media/4.png) + + + diff --git a/config/config.go b/config/config.go new file mode 100644 index 00000000..e1c7f911 --- /dev/null +++ b/config/config.go @@ -0,0 +1,50 @@ +package config + +import ( + _ "embed" + "fmt" + "os" + "strings" +) + +//go:embed version +var version string + +//go:embed name +var name string + +type LogLevel string + +const ( + Debug LogLevel = "debug" + Info LogLevel = "info" + Warn LogLevel = "warn" + Error LogLevel = "error" +) + +func GetVersion() string { + return strings.TrimSpace(version) +} + +func GetName() string { + return strings.TrimSpace(name) +} + +func GetLogLevel() LogLevel { + if IsDebug() { + return Debug + } + logLevel := os.Getenv("XUI_LOG_LEVEL") + if logLevel == "" { + return Info + } + return LogLevel(logLevel) +} + +func IsDebug() bool { + return os.Getenv("XUI_DEBUG") == "true" +} + +func GetDBPath() string { + return fmt.Sprintf("/etc/%s/%s.db", GetName(), GetName()) +} diff --git a/config/name b/config/name new file mode 100644 index 00000000..491114af --- /dev/null +++ b/config/name @@ -0,0 +1 @@ +x-ui \ No newline at end of file diff --git a/config/version b/config/version new file mode 100644 index 00000000..be14282b --- /dev/null +++ b/config/version @@ -0,0 +1 @@ +0.5.3 diff --git a/database/db.go b/database/db.go new file mode 100644 index 00000000..92fca27a --- /dev/null +++ b/database/db.go @@ -0,0 +1,104 @@ +package database + +import ( + "gorm.io/driver/sqlite" + "gorm.io/gorm" + "gorm.io/gorm/logger" + "io/fs" + "os" + "path" + "x-ui/config" + "x-ui/xray" + "x-ui/database/model" +) + +var db *gorm.DB + +func initUser() error { + err := db.AutoMigrate(&model.User{}) + if err != nil { + return err + } + var count int64 + err = db.Model(&model.User{}).Count(&count).Error + if err != nil { + return err + } + if count == 0 { + user := &model.User{ + Username: "admin", + Password: "admin", + } + return db.Create(user).Error + } + return nil +} + +func initInbound() error { + return db.AutoMigrate(&model.Inbound{}) +} + +func initSetting() error { + return db.AutoMigrate(&model.Setting{}) +} +func initInboundClientIps() error { + return db.AutoMigrate(&model.InboundClientIps{}) +} +func initClientTraffic() error { + return db.AutoMigrate(&xray.ClientTraffic{}) +} + +func InitDB(dbPath string) error { + dir := path.Dir(dbPath) + err := os.MkdirAll(dir, fs.ModeDir) + if err != nil { + return err + } + + var gormLogger logger.Interface + + if config.IsDebug() { + gormLogger = logger.Default + } else { + gormLogger = logger.Discard + } + + c := &gorm.Config{ + Logger: gormLogger, + } + db, err = gorm.Open(sqlite.Open(dbPath), c) + if err != nil { + return err + } + + err = initUser() + if err != nil { + return err + } + err = initInbound() + if err != nil { + return err + } + err = initSetting() + if err != nil { + return err + } + err = initInboundClientIps() + if err != nil { + return err + } + err = initClientTraffic() + if err != nil { + return err + } + + return nil +} + +func GetDB() *gorm.DB { + return db +} + +func IsNotFound(err error) bool { + return err == gorm.ErrRecordNotFound +} diff --git a/database/model/model.go b/database/model/model.go new file mode 100644 index 00000000..30e348be --- /dev/null +++ b/database/model/model.go @@ -0,0 +1,81 @@ +package model + +import ( + "fmt" + "x-ui/util/json_util" + "x-ui/xray" +) + +type Protocol string + +const ( + VMess Protocol = "vmess" + VLESS Protocol = "vless" + Dokodemo Protocol = "Dokodemo-door" + Http Protocol = "http" + Trojan Protocol = "trojan" + Shadowsocks Protocol = "shadowsocks" +) + +type User struct { + Id int `json:"id" gorm:"primaryKey;autoIncrement"` + Username string `json:"username"` + Password string `json:"password"` +} + +type Inbound struct { + Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"` + UserId int `json:"-"` + Up int64 `json:"up" form:"up"` + Down int64 `json:"down" form:"down"` + Total int64 `json:"total" form:"total"` + Remark string `json:"remark" form:"remark"` + Enable bool `json:"enable" form:"enable"` + ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` + ClientStats []xray.ClientTraffic `gorm:"foreignKey:InboundId;references:Id" json:"clientStats" form:"clientStats"` + + // config part + Listen string `json:"listen" form:"listen"` + Port int `json:"port" form:"port" gorm:"unique"` + Protocol Protocol `json:"protocol" form:"protocol"` + Settings string `json:"settings" form:"settings"` + StreamSettings string `json:"streamSettings" form:"streamSettings"` + Tag string `json:"tag" form:"tag" gorm:"unique"` + Sniffing string `json:"sniffing" form:"sniffing"` +} +type InboundClientIps struct { + Id int `json:"id" gorm:"primaryKey;autoIncrement"` + ClientEmail string `json:"clientEmail" form:"clientEmail" gorm:"unique"` + Ips string `json:"ips" form:"ips"` +} + +func (i *Inbound) GenXrayInboundConfig() *xray.InboundConfig { + listen := i.Listen + if listen != "" { + listen = fmt.Sprintf("\"%v\"", listen) + } + return &xray.InboundConfig{ + Listen: json_util.RawMessage(listen), + Port: i.Port, + Protocol: string(i.Protocol), + Settings: json_util.RawMessage(i.Settings), + StreamSettings: json_util.RawMessage(i.StreamSettings), + Tag: i.Tag, + Sniffing: json_util.RawMessage(i.Sniffing), + } +} + +type Setting struct { + Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"` + Key string `json:"key" form:"key"` + Value string `json:"value" form:"value"` +} +type Client struct { + ID string `json:"id"` + AlterIds uint16 `json:"alterId"` + Email string `json:"email"` + LimitIP int `json:"limitIp"` + Security string `json:"security"` + TotalGB int64 `json:"totalGB" form:"totalGB"` + ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` +} \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 00000000..4c196ede --- /dev/null +++ b/go.mod @@ -0,0 +1,55 @@ +module x-ui + +go 1.19 + +require ( + github.com/BurntSushi/toml v1.2.0 + github.com/Workiva/go-datastructures v1.0.53 + github.com/gin-contrib/sessions v0.0.5 + github.com/gin-gonic/gin v1.8.1 + github.com/go-cmd/cmd v1.4.1 + github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 + github.com/nicksnyder/go-i18n/v2 v2.2.0 + github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 + github.com/robfig/cron/v3 v3.0.1 + github.com/shirou/gopsutil v3.21.11+incompatible + github.com/xtls/xray-core v1.7.5 + go.uber.org/atomic v1.10.0 + golang.org/x/text v0.6.0 + google.golang.org/grpc v1.53.0 + gorm.io/driver/sqlite v1.3.6 + gorm.io/gorm v1.23.8 +) + +require ( + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/go-ole/go-ole v1.2.6 // indirect + github.com/go-playground/locales v0.14.0 // indirect + github.com/go-playground/universal-translator v0.18.0 // indirect + github.com/go-playground/validator/v10 v10.10.0 // indirect + github.com/goccy/go-json v0.10.0 // indirect + github.com/golang/protobuf v1.5.2 // indirect + github.com/gorilla/context v1.1.1 // indirect + github.com/gorilla/securecookie v1.1.1 // indirect + github.com/gorilla/sessions v1.2.1 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/leodido/go-urn v1.2.1 // indirect + github.com/mattn/go-isatty v0.0.14 // indirect + github.com/mattn/go-sqlite3 v2.0.3+incompatible // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.0.1 // indirect + github.com/pires/go-proxyproto v0.6.2 // indirect + github.com/tklauser/go-sysconf v0.3.5 // indirect + github.com/tklauser/numcpus v0.2.2 // indirect + github.com/ugorji/go/codec v1.2.7 // indirect + github.com/yusufpapurcu/wmi v1.2.2 // indirect + golang.org/x/crypto v0.5.0 // indirect + golang.org/x/net v0.5.0 // indirect + golang.org/x/sys v0.5.0 // indirect + google.golang.org/genproto v0.0.0-20230202175211-008b39050e57 // indirect + google.golang.org/protobuf v1.28.1 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 00000000..55241836 --- /dev/null +++ b/go.sum @@ -0,0 +1,206 @@ +github.com/BurntSushi/toml v1.0.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/BurntSushi/toml v1.2.0 h1:Rt8g24XnyGTyglgET/PRUNlrUeu9F5L+7FilkXfZgs0= +github.com/BurntSushi/toml v1.2.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= +github.com/Workiva/go-datastructures v1.0.53 h1:J6Y/52yX10Xc5JjXmGtWoSSxs3mZnGSaq37xZZh7Yig= +github.com/Workiva/go-datastructures v1.0.53/go.mod h1:1yZL+zfsztete+ePzZz/Zb1/t5BnDuE2Ya2MMGhzP6A= +github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-metro v0.0.0-20211217172704-adc40b04c140 h1:y7y0Oa6UawqTFPCDw9JG6pdKt4F9pAhHv0B7FMGaGD0= +github.com/francoispqt/gojay v1.2.13 h1:d2m3sFjloqoIUQU3TsHBgj6qg/BVGlTBeHDUmyJnXKk= +github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344 h1:Arcl6UOIS/kgO2nW3A65HN+7CMjSDP/gofXL4CZt1V4= +github.com/gin-contrib/sessions v0.0.5 h1:CATtfHmLMQrMNpJRgzjWXD7worTh7g7ritsQfmF+0jE= +github.com/gin-contrib/sessions v0.0.5/go.mod h1:vYAuaUPqie3WUSsft6HUlCjlwwoJQs97miaG2+7neKY= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.8.1 h1:4+fr/el88TOO3ewCmQr8cx/CtZ/umlIRIs5M4NTNjf8= +github.com/gin-gonic/gin v1.8.1/go.mod h1:ji8BvRH1azfM+SYow9zQ6SZMvR8qOMZHmsCuWR9tTTk= +github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= +github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= +github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU= +github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs= +github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho= +github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA= +github.com/go-playground/validator/v10 v10.10.0 h1:I7mrTYv78z8k8VXa/qJlOlEXn/nBh+BF8dHX5nt/dr0= +github.com/go-playground/validator/v10 v10.10.0/go.mod h1:74x4gJWsvQexRdW8Pn3dXSGrTK4nAUsbPlLADvpJkos= +github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0 h1:p104kn46Q8WdvHunIJ9dAyjPVtrBPhSr3KT2yUst43I= +github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1 h1:wG8n/XJQ07TmjbITcGiUaOtXxdrINDz1b0J1w0SzqDc= +github.com/go-telegram-bot-api/telegram-bot-api/v5 v5.5.1/go.mod h1:A2S0CWkNylc2phvKXWBBdD3K0iGnDBGbzRpISP2zBl8= +github.com/goccy/go-json v0.10.0 h1:mXKd9Qw4NuzShiRlOXKews24ufknHO7gx30lsDyokKA= +github.com/goccy/go-json v0.10.0/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/google/btree v1.1.2 h1:xf4v41cLI2Z6FxbKm+8Bu+m8ifhj15JuZ9sa0jZCMUU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.9 h1:O2Tfq5qg4qc4AmwVlvv0oLiVAGB7enBSJ2x2DqQFi38= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20230207041349-798e818bf904 h1:4/hN5RUoecvl+RmJRE2YxKWtnnQls6rQjjW5oV7qg2U= +github.com/gorilla/context v1.1.1 h1:AWwleXJkX/nhcU9bZSnZoi3h/qGYqQAGhq6zZe/aQW8= +github.com/gorilla/context v1.1.1/go.mod h1:kBGZzfjB9CEq2AlWe17Uuf7NDRt0dE0s8S51q0aT7Yg= +github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ= +github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4= +github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI= +github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM= +github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/compress v1.15.15 h1:EF27CXIuDsYJ6mmvtBRlEuB2UVOqHG1tAXgZ7yIO+lw= +github.com/klauspost/cpuid/v2 v2.2.3 h1:sxCkb+qR91z4vsqw4vGGZlDgPz3G7gjaLyK3V8y70BU= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= +github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= +github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= +github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/mattn/go-sqlite3 v1.14.12/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU= +github.com/mattn/go-sqlite3 v2.0.3+incompatible h1:gXHsfypPkaMZrKbD5209QV9jbUTJKjyR5WD3HYQSd+U= +github.com/mattn/go-sqlite3 v2.0.3+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/nicksnyder/go-i18n/v2 v2.2.0 h1:MNXbyPvd141JJqlU6gJKrczThxJy+kdCNivxZpBQFkw= +github.com/nicksnyder/go-i18n/v2 v2.2.0/go.mod h1:4OtLfzqyAxsscyCb//3gfqSvBc81gImX91LrZzczN1o= +github.com/onsi/ginkgo/v2 v2.8.0 h1:pAM+oBNPrpXRs+E/8spkeGx9QgekbRVyr74EUvRVOUI= +github.com/op/go-logging v0.0.0-20160315200505-970db520ece7 h1:lDH9UUVJtmYCjyT0CI4q8xvlXPxeZ0gYCVvWbmPlp88= +github.com/op/go-logging v0.0.0-20160315200505-970db520ece7/go.mod h1:HzydrMdWErDVzsI23lYNej1Htcns9BCg93Dk0bBINWk= +github.com/pelletier/go-toml v1.9.5 h1:4yBQzkHv+7BHq2PQUZF3Mx0IYxG7LsP222s7Agd3ve8= +github.com/pelletier/go-toml/v2 v2.0.1 h1:8e3L2cCQzLFi2CR4g7vGFuFxX7Jl1kKX8gW+iV0GUKU= +github.com/pelletier/go-toml/v2 v2.0.1/go.mod h1:r9LEWfGN8R5k0VXJ+0BkIe7MYkRdwZOjgMj2KwnJFUo= +github.com/philhofer/fwd v1.1.1/go.mod h1:gk3iGcWd9+svBvR0sR+KPcfE+RNWozjowpeBVG3ZVNU= +github.com/pires/go-proxyproto v0.6.2 h1:KAZ7UteSOt6urjme6ZldyFm4wDe/z0ZUP0Yv0Dos0d8= +github.com/pires/go-proxyproto v0.6.2/go.mod h1:Odh9VFOZJCf9G8cLW5o435Xf1J95Jw9Gw5rnCjcwzAY= +github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/quic-go/qtls-go1-18 v0.2.0 h1:5ViXqBZ90wpUcZS0ge79rf029yx0dYB0McyPJwqqj7U= +github.com/quic-go/qtls-go1-19 v0.2.0 h1:Cvn2WdhyViFUHoOqK52i51k4nDX8EwIh5VJiVM4nttk= +github.com/quic-go/qtls-go1-20 v0.1.0 h1:d1PK3ErFy9t7zxKsG3NXBJXZjp/kMLoIb3y/kV54oAI= +github.com/quic-go/quic-go v0.32.0 h1:lY02md31s1JgPiiyfqJijpu/UX/Iun304FI3yUqX7tA= +github.com/refraction-networking/utls v1.2.2-0.20230207151345-a75a4b484849 h1:vNEcNapWFwnYJTBcVkHJa8VrdL40PNDLDbSGVY+ZV7I= +github.com/riobard/go-bloom v0.0.0-20200614022211-cdc8013cb5b3 h1:f/FNXud6gA3MNr8meMVVGxhp+QBTqY91tM8HjEuMjGg= +github.com/robfig/cron/v3 v3.0.1 h1:WdRxkvbJztn8LMz/QEvLN5sBU+xKpSqwwUO1Pjr4qDs= +github.com/robfig/cron/v3 v3.0.1/go.mod h1:eQICP3HwyT7UooqI/z+Ov+PtYAWygg1TEWWzGIFLtro= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= +github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= +github.com/sagernet/sing v0.1.6 h1:Qy63OUfKpcqKjfd5rPmUlj0RGjHZSK/PJn0duyCCsRg= +github.com/sagernet/sing-shadowsocks v0.1.1-0.20230202035033-e3123545f2f7 h1:Plup6oEiyLzY3HDqQ+QsUBzgBGdVmcsgf3t8h940z9U= +github.com/sagernet/wireguard-go v0.0.0-20221116151939-c99467f53f2c h1:vK2wyt9aWYHHvNLWniwijBu/n4pySypiKRhN32u/JGo= +github.com/seiflotfy/cuckoofilter v0.0.0-20220411075957-e3b120b3f5fb h1:XfLJSPIOUX+osiMraVgIrMR27uMXnRJWGm1+GL8/63U= +github.com/shirou/gopsutil v3.21.11+incompatible h1:+1+c1VGhc88SSonWP6foOcLhvnKlUeu/erjjvaPEYiI= +github.com/shirou/gopsutil v3.21.11+incompatible/go.mod h1:5b4v6he4MtMOwMlS0TUMTu2PcXUg8+E1lC7eC3UO/RA= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/tinylib/msgp v1.1.5/go.mod h1:eQsjooMTnV42mHu917E26IogZ2930nFyBQdofk10Udg= +github.com/tklauser/go-sysconf v0.3.5 h1:uu3Xl4nkLzQfXNsWn15rPc/HQCJKObbt1dKJeWp3vU4= +github.com/tklauser/go-sysconf v0.3.5/go.mod h1:MkWzOF4RMCshBAMXuhXJs64Rte09mITnppBXY/rYEFI= +github.com/tklauser/numcpus v0.2.2 h1:oyhllyrScuYI6g+h/zUvNXNp1wy7x8qQy3t/piefldA= +github.com/tklauser/numcpus v0.2.2/go.mod h1:x3qojaO3uyYt0i56EW/VUYs7uBvdl2fkfZFu0T9wgjM= +github.com/ttacon/chalk v0.0.0-20160626202418-22c06c80ed31/go.mod h1:onvgF043R+lC5RZ8IT9rBXDaEDnpnw/Cl+HFiw+v/7Q= +github.com/ugorji/go v1.2.7/go.mod h1:nF9osbDWLy6bDVv/Rtoh6QgnvNDpmCalQV5urGCCS6M= +github.com/ugorji/go/codec v1.2.7 h1:YPXUKf7fYbp/y8xloBqZOw2qaVggbfwMlI8WM3wZUJ0= +github.com/ugorji/go/codec v1.2.7/go.mod h1:WGN1fab3R1fzQlVQTkfxVtIBhWDRqOviHU95kRgeqEY= +github.com/v2fly/ss-bloomring v0.0.0-20210312155135-28617310f63e h1:5QefA066A1tF8gHIiADmOVOV5LS43gt3ONnlEl3xkwI= +github.com/xtls/go v0.0.0-20230107031059-4610f88d00f3 h1:a3Y4WVjCxwoyO4E2xdNvq577tW8lkSBgyrA8E9+2NtM= +github.com/xtls/xray-core v1.7.5 h1:Ukr3hXnOG2ciViQL7kfYRl9S3GVej2dkV7DzabmoLL4= +github.com/xtls/xray-core v1.7.5/go.mod h1:Mx1QzIDvSk4eZ8hKa3AYsSPfyZJNQXWVXTJxJRJ98wI= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yusufpapurcu/wmi v1.2.2 h1:KBNDSne4vP5mbSWnJbO+51IMOXJB67QiYCSBrubbPRg= +github.com/yusufpapurcu/wmi v1.2.2/go.mod h1:SBZ9tNy3G9/m5Oi98Zks0QjeHVDvuK0qfxQmPyzfmi0= +go.starlark.net v0.0.0-20230128213706-3f75dec8e403 h1:jPeC7Exc+m8OBJUlWbBLh0O5UZPM7yU5W4adnhhbG4U= +go.uber.org/atomic v1.10.0 h1:9qC72Qh0+3MqyJbAn8YU5xVq1frD8bn3JtD2oXtafVQ= +go.uber.org/atomic v1.10.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE= +golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU= +golang.org/x/exp v0.0.0-20230206171751-46f607a40771 h1:xP7rWLUr1e1n2xkK5YB4LI0hPEy3LJC6Wk+D4pGlOJg= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.7.0 h1:LapD9S96VoQRhi/GrNTqeBJFrUjs5UHCAtTlgwA5oZA= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.5.0 h1:GyT4nK/YDHSqa1c4753ouYCDajOYKTja9Xb/OHtgvSw= +golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210316164454-77fc1eacc6aa/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.6.0 h1:3XmdazWV+ubf7QgHSTWeykHOci5oeekaGJBLkrkaw4k= +golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20201022035929-9cf592e881e9/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.5.0 h1:+bSpV5HIeWkuvgaMfI3UmKRThoTA5ODJTUd8T17NO+4= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/genproto v0.0.0-20230202175211-008b39050e57 h1:vArvWooPH749rNHpBGgVl+U9B9dATjiEhJzcWGlovNs= +google.golang.org/genproto v0.0.0-20230202175211-008b39050e57/go.mod h1:RGgjbofJ8xD9Sq1VVhDM1Vok1vRONV+rg+CjzG4SZKM= +google.golang.org/grpc v1.53.0 h1:LAv2ds7cmFV/XTS3XG1NneeENYrXGmorPxsBbptIjNc= +google.golang.org/grpc v1.53.0/go.mod h1:OnIrk0ipVdj4N5d9IUoFUx72/VlD7+jUsHwZgwSMQpw= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= +google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gorm.io/driver/sqlite v1.3.6 h1:Fi8xNYCUplOqWiPa3/GuCeowRNBRGTf62DEmhMDHeQQ= +gorm.io/driver/sqlite v1.3.6/go.mod h1:Sg1/pvnKtbQ7jLXxfZa+jSHvoX8hoZA8cn4xllOMTgE= +gorm.io/gorm v1.23.4/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk= +gorm.io/gorm v1.23.8 h1:h8sGJ+biDgBA1AD1Ha9gFCx7h8npU7AsLdlkX0n2TpE= +gorm.io/gorm v1.23.8/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk= +gvisor.dev/gvisor v0.0.0-20220901235040-6ca97ef2ce1c h1:m5lcgWnL3OElQNVyp3qcncItJ2c0sQlSGjYK2+nJTA4= +lukechampine.com/blake3 v1.1.7 h1:GgRMhmdsuK8+ii6UZFDL8Nb+VyMwadAgcJyfYHxG6n0= diff --git a/install.sh b/install.sh new file mode 100644 index 00000000..4b14e3c4 --- /dev/null +++ b/install.sh @@ -0,0 +1,175 @@ +#!/bin/bash + +red='\033[0;31m' +green='\033[0;32m' +yellow='\033[0;33m' +plain='\033[0m' + +cur_dir=$(pwd) + +# check root +[[ $EUID -ne 0 ]] && echo -e "${red}Fatal error:${plain} Please run this script with root privilege \n " && exit 1 + +# check os +if [[ -f /etc/redhat-release ]]; then + release="centos" +elif cat /etc/issue | grep -Eqi "debian"; then + release="debian" +elif cat /etc/issue | grep -Eqi "ubuntu"; then + release="ubuntu" +elif cat /etc/issue | grep -Eqi "centos|red hat|redhat"; then + release="centos" +elif cat /proc/version | grep -Eqi "debian"; then + release="debian" +elif cat /proc/version | grep -Eqi "ubuntu"; then + release="ubuntu" +elif cat /proc/version | grep -Eqi "centos|red hat|redhat"; then + release="centos" +else + echo -e "${red} Check system OS failed, please contact the author! ${plain}\n" && exit 1 +fi + +arch=$(arch) + +if [[ $arch == "x86_64" || $arch == "x64" || $arch == "amd64" ]]; then + arch="amd64" +elif [[ $arch == "aarch64" || $arch == "arm64" ]]; then + arch="arm64" +elif [[ $arch == "s390x" ]]; then + arch="s390x" +else + arch="amd64" + echo -e "${red} Failed to check system arch, will use default arch: ${arch}${plain}" +fi + +echo "arch: ${arch}" + +if [ $(getconf WORD_BIT) != '32' ] && [ $(getconf LONG_BIT) != '64' ]; then + echo "x-ui dosen't support 32-bit(x86) system, please use 64 bit operating system(x86_64) instead, if there is something wrong, please get in touch with me!" + exit -1 +fi + +os_version="" + +# os version +if [[ -f /etc/os-release ]]; then + os_version=$(awk -F'[= ."]' '/VERSION_ID/{print $3}' /etc/os-release) +fi +if [[ -z "$os_version" && -f /etc/lsb-release ]]; then + os_version=$(awk -F'[= ."]+' '/DISTRIB_RELEASE/{print $2}' /etc/lsb-release) +fi + +if [[ x"${release}" == x"centos" ]]; then + if [[ ${os_version} -le 6 ]]; then + echo -e "${red} Please use CentOS 7 or higher ${plain}\n" && exit 1 + fi +elif [[ x"${release}" == x"ubuntu" ]]; then + if [[ ${os_version} -lt 16 ]]; then + echo -e "${red} Please use Ubuntu 16 or higher ${plain}\n" && exit 1 + fi +elif [[ x"${release}" == x"debian" ]]; then + if [[ ${os_version} -lt 8 ]]; then + echo -e "${red} Please use Debian 8 or higher ${plain}\n" && exit 1 + fi +fi + +install_base() { + if [[ x"${release}" == x"centos" ]]; then + yum install wget curl tar -y + else + apt install wget curl tar -y + fi +} + +#This function will be called when user installed x-ui out of sercurity +config_after_install() { + echo -e "${yellow}Install/update finished! For security it's recommended to modify panel settings ${plain}" + read -p "Do you want to continue with the modification [y/n]? ": config_confirm + if [[ x"${config_confirm}" == x"y" || x"${config_confirm}" == x"Y" ]]; then + read -p "Please set up your username:" config_account + echo -e "${yellow}Your username will be:${config_account}${plain}" + read -p "Please set up your password:" config_password + echo -e "${yellow}Your password will be:${config_password}${plain}" + read -p "Please set up the panel port:" config_port + echo -e "${yellow}Your panel port is:${config_port}${plain}" + echo -e "${yellow}Initializing, please wait...${plain}" + /usr/local/x-ui/x-ui setting -username ${config_account} -password ${config_password} + echo -e "${yellow}Account name and password set successfully!${plain}" + /usr/local/x-ui/x-ui setting -port ${config_port} + echo -e "${yellow}Panel port set successfully!${plain}" + else + echo -e "${red}Canceled, will use the default settings.${plain}" + fi +} + +install_x-ui() { + systemctl stop x-ui + cd /usr/local/ + + if [ $# == 0 ]; then + last_version=$(curl -Ls "https://api.github.com/repos/mhsanaei/3x-ui/releases/latest" | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/') + if [[ ! -n "$last_version" ]]; then + echo -e "${red}Failed to fetch x-ui version, it maybe due to Github API restrictions, please try it later${plain}" + exit 1 + fi + echo -e "Got x-ui latest version: ${last_version}, beginning the installation..." + wget -N --no-check-certificate -O /usr/local/x-ui-linux-${arch}.tar.gz https://github.com/mhsanaei/3x-ui/releases/download/${last_version}/x-ui-linux-${arch}.tar.gz + if [[ $? -ne 0 ]]; then + echo -e "${red}Downloading x-ui failed, please be sure that your server can access Github ${plain}" + exit 1 + fi + else + last_version=$1 + url="https://github.com/mhsanaei/3x-ui/releases/download/${last_version}/x-ui-linux-${arch}.tar.gz" + echo -e "Begining to install x-ui $1" + wget -N --no-check-certificate -O /usr/local/x-ui-linux-${arch}.tar.gz ${url} + if [[ $? -ne 0 ]]; then + echo -e "${red}Download x-ui $1 failed,please check the version exists${plain}" + exit 1 + fi + fi + + if [[ -e /usr/local/x-ui/ ]]; then + rm /usr/local/x-ui/ -rf + fi + + tar zxvf x-ui-linux-${arch}.tar.gz + rm x-ui-linux-${arch}.tar.gz -f + cd x-ui + chmod +x x-ui bin/xray-linux-${arch} + cp -f x-ui.service /etc/systemd/system/ + wget --no-check-certificate -O /usr/bin/x-ui https://raw.githubusercontent.com/mhsanaei/3x-ui/main/x-ui.sh + chmod +x /usr/local/x-ui/x-ui.sh + chmod +x /usr/bin/x-ui + config_after_install + #echo -e "If it is a new installation, the default web port is ${green}2053${plain}, The username and password are ${green}admin${plain} by default" + #echo -e "Please make sure that this port is not occupied by other procedures,${yellow} And make sure that port 2053 has been released${plain}" + # echo -e "If you want to modify the 2053 to other ports and enter the x-ui command to modify it, you must also ensure that the port you modify is also released" + #echo -e "" + #echo -e "If it is updated panel, access the panel in your previous way" + #echo -e "" + systemctl daemon-reload + systemctl enable x-ui + systemctl start x-ui + echo -e "${green}x-ui ${last_version}${plain} installation finished, it is running now..." + echo -e "" + echo -e "x-ui control menu usages: " + echo -e "----------------------------------------------" + echo -e "x-ui - Enter Admin menu" + echo -e "x-ui start - Start x-ui" + echo -e "x-ui stop - Stop x-ui" + echo -e "x-ui restart - Restart x-ui" + echo -e "x-ui status - Show x-ui status" + echo -e "x-ui enable - Enable x-ui on system startup" + echo -e "x-ui disable - Disable x-ui on system startup" + echo -e "x-ui log - Check x-ui logs" + echo -e "x-ui v2-ui - Migrate v2-ui Account data to x-ui" + echo -e "x-ui update - Update x-ui" + echo -e "x-ui install - Install x-ui" + echo -e "x-ui uninstall - Uninstall x-ui" + echo -e "----------------------------------------------" +} + +echo -e "${green}Running...${plain}" +install_base +install_x-ui $1 diff --git a/logger/logger.go b/logger/logger.go new file mode 100644 index 00000000..cb5e8360 --- /dev/null +++ b/logger/logger.go @@ -0,0 +1,58 @@ +package logger + +import ( + "github.com/op/go-logging" + "os" +) + +var logger *logging.Logger + +func init() { + InitLogger(logging.INFO) +} + +func InitLogger(level logging.Level) { + format := logging.MustStringFormatter( + `%{time:2006/01/02 15:04:05} %{level} - %{message}`, + ) + newLogger := logging.MustGetLogger("x-ui") + backend := logging.NewLogBackend(os.Stderr, "", 0) + backendFormatter := logging.NewBackendFormatter(backend, format) + backendLeveled := logging.AddModuleLevel(backendFormatter) + backendLeveled.SetLevel(level, "") + newLogger.SetBackend(backendLeveled) + + logger = newLogger +} + +func Debug(args ...interface{}) { + logger.Debug(args...) +} + +func Debugf(format string, args ...interface{}) { + logger.Debugf(format, args...) +} + +func Info(args ...interface{}) { + logger.Info(args...) +} + +func Infof(format string, args ...interface{}) { + logger.Infof(format, args...) +} + +func Warning(args ...interface{}) { + logger.Warning(args...) +} + +func Warningf(format string, args ...interface{}) { + logger.Warningf(format, args...) +} + +func Error(args ...interface{}) { + logger.Error(args...) +} + +func Errorf(format string, args ...interface{}) { + logger.Errorf(format, args...) +} diff --git a/main.go b/main.go new file mode 100644 index 00000000..f5da0704 --- /dev/null +++ b/main.go @@ -0,0 +1,302 @@ +package main + +import ( + "flag" + "fmt" + "log" + "os" + "os/signal" + "syscall" + _ "unsafe" + "x-ui/config" + "x-ui/database" + "x-ui/logger" + "x-ui/v2ui" + "x-ui/web" + "x-ui/web/global" + "x-ui/web/service" + + "github.com/op/go-logging" +) + +func runWebServer() { + log.Printf("%v %v", config.GetName(), config.GetVersion()) + + switch config.GetLogLevel() { + case config.Debug: + logger.InitLogger(logging.DEBUG) + case config.Info: + logger.InitLogger(logging.INFO) + case config.Warn: + logger.InitLogger(logging.WARNING) + case config.Error: + logger.InitLogger(logging.ERROR) + default: + log.Fatal("unknown log level:", config.GetLogLevel()) + } + + err := database.InitDB(config.GetDBPath()) + if err != nil { + log.Fatal(err) + } + + var server *web.Server + + server = web.NewServer() + global.SetWebServer(server) + err = server.Start() + if err != nil { + log.Println(err) + return + } + + sigCh := make(chan os.Signal, 1) + //信号量捕获处理 + signal.Notify(sigCh, syscall.SIGHUP, syscall.SIGTERM, syscall.SIGKILL) + for { + sig := <-sigCh + + switch sig { + case syscall.SIGHUP: + err := server.Stop() + if err != nil { + logger.Warning("stop server err:", err) + } + server = web.NewServer() + global.SetWebServer(server) + err = server.Start() + if err != nil { + log.Println(err) + return + } + default: + server.Stop() + return + } + } +} + +func resetSetting() { + err := database.InitDB(config.GetDBPath()) + if err != nil { + fmt.Println(err) + return + } + + settingService := service.SettingService{} + err = settingService.ResetSettings() + if err != nil { + fmt.Println("reset setting failed:", err) + } else { + fmt.Println("reset setting success") + } +} + +func showSetting(show bool) { + if show { + settingService := service.SettingService{} + port, err := settingService.GetPort() + if err != nil { + fmt.Println("get current port fialed,error info:", err) + } + userService := service.UserService{} + userModel, err := userService.GetFirstUser() + if err != nil { + fmt.Println("get current user info failed,error info:", err) + } + username := userModel.Username + userpasswd := userModel.Password + if (username == "") || (userpasswd == "") { + fmt.Println("current username or password is empty") + } + fmt.Println("current pannel settings as follows:") + fmt.Println("username:", username) + fmt.Println("userpasswd:", userpasswd) + fmt.Println("port:", port) + } +} + +func updateTgbotEnableSts(status bool) { + settingService := service.SettingService{} + currentTgSts, err := settingService.GetTgbotenabled() + if err != nil { + fmt.Println(err) + return + } + logger.Infof("current enabletgbot status[%v],need update to status[%v]", currentTgSts, status) + if currentTgSts != status { + err := settingService.SetTgbotenabled(status) + if err != nil { + fmt.Println(err) + return + } else { + logger.Infof("SetTgbotenabled[%v] success", status) + } + } + return +} + +func updateTgbotSetting(tgBotToken string, tgBotChatid int, tgBotRuntime string) { + err := database.InitDB(config.GetDBPath()) + if err != nil { + fmt.Println(err) + return + } + + settingService := service.SettingService{} + + if tgBotToken != "" { + err := settingService.SetTgBotToken(tgBotToken) + if err != nil { + fmt.Println(err) + return + } else { + logger.Info("updateTgbotSetting tgBotToken success") + } + } + + if tgBotRuntime != "" { + err := settingService.SetTgbotRuntime(tgBotRuntime) + if err != nil { + fmt.Println(err) + return + } else { + logger.Infof("updateTgbotSetting tgBotRuntime[%s] success", tgBotRuntime) + } + } + + if tgBotChatid != 0 { + err := settingService.SetTgBotChatId(tgBotChatid) + if err != nil { + fmt.Println(err) + return + } else { + logger.Info("updateTgbotSetting tgBotChatid success") + } + } +} + +func updateSetting(port int, username string, password string) { + err := database.InitDB(config.GetDBPath()) + if err != nil { + fmt.Println(err) + return + } + + settingService := service.SettingService{} + + if port > 0 { + err := settingService.SetPort(port) + if err != nil { + fmt.Println("set port failed:", err) + } else { + fmt.Printf("set port %v success", port) + } + } + if username != "" || password != "" { + userService := service.UserService{} + err := userService.UpdateFirstUser(username, password) + if err != nil { + fmt.Println("set username and password failed:", err) + } else { + fmt.Println("set username and password success") + } + } +} + +func main() { + if len(os.Args) < 2 { + runWebServer() + return + } + + var showVersion bool + flag.BoolVar(&showVersion, "v", false, "show version") + + runCmd := flag.NewFlagSet("run", flag.ExitOnError) + + v2uiCmd := flag.NewFlagSet("v2-ui", flag.ExitOnError) + var dbPath string + v2uiCmd.StringVar(&dbPath, "db", "/etc/v2-ui/v2-ui.db", "set v2-ui db file path") + + settingCmd := flag.NewFlagSet("setting", flag.ExitOnError) + var port int + var username string + var password string + var tgbottoken string + var tgbotchatid int + var enabletgbot bool + var tgbotRuntime string + var reset bool + var show bool + settingCmd.BoolVar(&reset, "reset", false, "reset all settings") + settingCmd.BoolVar(&show, "show", false, "show current settings") + settingCmd.IntVar(&port, "port", 0, "set panel port") + settingCmd.StringVar(&username, "username", "", "set login username") + settingCmd.StringVar(&password, "password", "", "set login password") + settingCmd.StringVar(&tgbottoken, "tgbottoken", "", "set telegrame bot token") + settingCmd.StringVar(&tgbotRuntime, "tgbotRuntime", "", "set telegrame bot cron time") + settingCmd.IntVar(&tgbotchatid, "tgbotchatid", 0, "set telegrame bot chat id") + settingCmd.BoolVar(&enabletgbot, "enabletgbot", false, "enable telegram bot notify") + + oldUsage := flag.Usage + flag.Usage = func() { + oldUsage() + fmt.Println() + fmt.Println("Commands:") + fmt.Println(" run run web panel") + fmt.Println(" v2-ui migrate form v2-ui") + fmt.Println(" setting set settings") + } + + flag.Parse() + if showVersion { + fmt.Println(config.GetVersion()) + return + } + + switch os.Args[1] { + case "run": + err := runCmd.Parse(os.Args[2:]) + if err != nil { + fmt.Println(err) + return + } + runWebServer() + case "v2-ui": + err := v2uiCmd.Parse(os.Args[2:]) + if err != nil { + fmt.Println(err) + return + } + err = v2ui.MigrateFromV2UI(dbPath) + if err != nil { + fmt.Println("migrate from v2-ui failed:", err) + } + case "setting": + err := settingCmd.Parse(os.Args[2:]) + if err != nil { + fmt.Println(err) + return + } + if reset { + resetSetting() + } else { + updateSetting(port, username, password) + } + if show { + showSetting(show) + } + if (tgbottoken != "") || (tgbotchatid != 0) || (tgbotRuntime != "") { + updateTgbotSetting(tgbottoken, tgbotchatid, tgbotRuntime) + } + default: + fmt.Println("except 'run' or 'v2-ui' or 'setting' subcommands") + fmt.Println() + runCmd.Usage() + fmt.Println() + v2uiCmd.Usage() + fmt.Println() + settingCmd.Usage() + } +} diff --git a/media/1.png b/media/1.png new file mode 100644 index 00000000..4785612c Binary files /dev/null and b/media/1.png differ diff --git a/media/2.png b/media/2.png new file mode 100644 index 00000000..4606f4f6 Binary files /dev/null and b/media/2.png differ diff --git a/media/3.png b/media/3.png new file mode 100644 index 00000000..a3cb3754 Binary files /dev/null and b/media/3.png differ diff --git a/media/4.png b/media/4.png new file mode 100644 index 00000000..05c281ed Binary files /dev/null and b/media/4.png differ diff --git a/util/common/err.go b/util/common/err.go new file mode 100644 index 00000000..c0ecbbb8 --- /dev/null +++ b/util/common/err.go @@ -0,0 +1,29 @@ +package common + +import ( + "errors" + "fmt" + "x-ui/logger" +) + +var CtxDone = errors.New("context done") + +func NewErrorf(format string, a ...interface{}) error { + msg := fmt.Sprintf(format, a...) + return errors.New(msg) +} + +func NewError(a ...interface{}) error { + msg := fmt.Sprintln(a...) + return errors.New(msg) +} + +func Recover(msg string) interface{} { + panicErr := recover() + if panicErr != nil { + if msg != "" { + logger.Error(msg, "panic:", panicErr) + } + } + return panicErr +} diff --git a/util/common/format.go b/util/common/format.go new file mode 100644 index 00000000..1ea10877 --- /dev/null +++ b/util/common/format.go @@ -0,0 +1,21 @@ +package common + +import ( + "fmt" +) + +func FormatTraffic(trafficBytes int64) (size string) { + if trafficBytes < 1024 { + return fmt.Sprintf("%.2fB", float64(trafficBytes)/float64(1)) + } else if trafficBytes < (1024 * 1024) { + return fmt.Sprintf("%.2fKB", float64(trafficBytes)/float64(1024)) + } else if trafficBytes < (1024 * 1024 * 1024) { + return fmt.Sprintf("%.2fMB", float64(trafficBytes)/float64(1024*1024)) + } else if trafficBytes < (1024 * 1024 * 1024 * 1024) { + return fmt.Sprintf("%.2fGB", float64(trafficBytes)/float64(1024*1024*1024)) + } else if trafficBytes < (1024 * 1024 * 1024 * 1024 * 1024) { + return fmt.Sprintf("%.2fTB", float64(trafficBytes)/float64(1024*1024*1024*1024)) + } else { + return fmt.Sprintf("%.2fEB", float64(trafficBytes)/float64(1024*1024*1024*1024*1024)) + } +} diff --git a/util/common/multi_error.go b/util/common/multi_error.go new file mode 100644 index 00000000..ff9ff628 --- /dev/null +++ b/util/common/multi_error.go @@ -0,0 +1,30 @@ +package common + +import ( + "strings" +) + +type multiError []error + +func (e multiError) Error() string { + var r strings.Builder + r.WriteString("multierr: ") + for _, err := range e { + r.WriteString(err.Error()) + r.WriteString(" | ") + } + return r.String() +} + +func Combine(maybeError ...error) error { + var errs multiError + for _, err := range maybeError { + if err != nil { + errs = append(errs, err) + } + } + if len(errs) == 0 { + return nil + } + return errs +} diff --git a/util/common/stringUtil.go b/util/common/stringUtil.go new file mode 100644 index 00000000..5f1f93fd --- /dev/null +++ b/util/common/stringUtil.go @@ -0,0 +1,9 @@ +package common + +import "sort" + +func IsSubString(target string, str_array []string) bool { + sort.Strings(str_array) + index := sort.SearchStrings(str_array, target) + return index < len(str_array) && str_array[index] == target +} diff --git a/util/context.go b/util/context.go new file mode 100644 index 00000000..b768f05c --- /dev/null +++ b/util/context.go @@ -0,0 +1,12 @@ +package util + +import "context" + +func IsDone(ctx context.Context) bool { + select { + case <-ctx.Done(): + return true + default: + return false + } +} diff --git a/util/json_util/json.go b/util/json_util/json.go new file mode 100644 index 00000000..65ad789e --- /dev/null +++ b/util/json_util/json.go @@ -0,0 +1,24 @@ +package json_util + +import ( + "errors" +) + +type RawMessage []byte + +// MarshalJSON 自定义 json.RawMessage 默认行为 +func (m RawMessage) MarshalJSON() ([]byte, error) { + if len(m) == 0 { + return []byte("null"), nil + } + return m, nil +} + +// UnmarshalJSON sets *m to a copy of data. +func (m *RawMessage) UnmarshalJSON(data []byte) error { + if m == nil { + return errors.New("json.RawMessage: UnmarshalJSON on nil pointer") + } + *m = append((*m)[0:0], data...) + return nil +} diff --git a/util/random/random.go b/util/random/random.go new file mode 100644 index 00000000..b1dd2e09 --- /dev/null +++ b/util/random/random.go @@ -0,0 +1,43 @@ +package random + +import ( + "math/rand" + "time" +) + +var numSeq [10]rune +var lowerSeq [26]rune +var upperSeq [26]rune +var numLowerSeq [36]rune +var numUpperSeq [36]rune +var allSeq [62]rune + +func init() { + rand.Seed(time.Now().UnixNano()) + + for i := 0; i < 10; i++ { + numSeq[i] = rune('0' + i) + } + for i := 0; i < 26; i++ { + lowerSeq[i] = rune('a' + i) + upperSeq[i] = rune('A' + i) + } + + copy(numLowerSeq[:], numSeq[:]) + copy(numLowerSeq[len(numSeq):], lowerSeq[:]) + + copy(numUpperSeq[:], numSeq[:]) + copy(numUpperSeq[len(numSeq):], upperSeq[:]) + + copy(allSeq[:], numSeq[:]) + copy(allSeq[len(numSeq):], lowerSeq[:]) + copy(allSeq[len(numSeq)+len(lowerSeq):], upperSeq[:]) +} + +func Seq(n int) string { + runes := make([]rune, n) + for i := 0; i < n; i++ { + runes[i] = allSeq[rand.Intn(len(allSeq))] + } + return string(runes) +} diff --git a/util/reflect_util/reflect.go b/util/reflect_util/reflect.go new file mode 100644 index 00000000..1fdaec50 --- /dev/null +++ b/util/reflect_util/reflect.go @@ -0,0 +1,21 @@ +package reflect_util + +import "reflect" + +func GetFields(t reflect.Type) []reflect.StructField { + num := t.NumField() + fields := make([]reflect.StructField, 0, num) + for i := 0; i < num; i++ { + fields = append(fields, t.Field(i)) + } + return fields +} + +func GetFieldValues(v reflect.Value) []reflect.Value { + num := v.NumField() + fields := make([]reflect.Value, 0, num) + for i := 0; i < num; i++ { + fields = append(fields, v.Field(i)) + } + return fields +} diff --git a/util/sys/a.s b/util/sys/a.s new file mode 100644 index 00000000..e69de29b diff --git a/util/sys/psutil.go b/util/sys/psutil.go new file mode 100644 index 00000000..645f839a --- /dev/null +++ b/util/sys/psutil.go @@ -0,0 +1,8 @@ +package sys + +import ( + _ "unsafe" +) + +//go:linkname HostProc github.com/shirou/gopsutil/internal/common.HostProc +func HostProc(combineWith ...string) string diff --git a/util/sys/sys_darwin.go b/util/sys/sys_darwin.go new file mode 100644 index 00000000..d61a38a2 --- /dev/null +++ b/util/sys/sys_darwin.go @@ -0,0 +1,23 @@ +// +build darwin + +package sys + +import ( + "github.com/shirou/gopsutil/net" +) + +func GetTCPCount() (int, error) { + stats, err := net.Connections("tcp") + if err != nil { + return 0, err + } + return len(stats), nil +} + +func GetUDPCount() (int, error) { + stats, err := net.Connections("udp") + if err != nil { + return 0, err + } + return len(stats), nil +} diff --git a/util/sys/sys_linux.go b/util/sys/sys_linux.go new file mode 100644 index 00000000..843d9b00 --- /dev/null +++ b/util/sys/sys_linux.go @@ -0,0 +1,70 @@ +// +build linux + +package sys + +import ( + "bytes" + "fmt" + "io" + "os" +) + +func getLinesNum(filename string) (int, error) { + file, err := os.Open(filename) + if err != nil { + return 0, err + } + defer file.Close() + + sum := 0 + buf := make([]byte, 8192) + for { + n, err := file.Read(buf) + + var buffPosition int + for { + i := bytes.IndexByte(buf[buffPosition:], '\n') + if i < 0 || n == buffPosition { + break + } + buffPosition += i + 1 + sum++ + } + + if err == io.EOF { + return sum, nil + } else if err != nil { + return sum, err + } + } +} + +func GetTCPCount() (int, error) { + root := HostProc() + + tcp4, err := getLinesNum(fmt.Sprintf("%v/net/tcp", root)) + if err != nil { + return tcp4, err + } + tcp6, err := getLinesNum(fmt.Sprintf("%v/net/tcp6", root)) + if err != nil { + return tcp4 + tcp6, nil + } + + return tcp4 + tcp6, nil +} + +func GetUDPCount() (int, error) { + root := HostProc() + + udp4, err := getLinesNum(fmt.Sprintf("%v/net/udp", root)) + if err != nil { + return udp4, err + } + udp6, err := getLinesNum(fmt.Sprintf("%v/net/udp6", root)) + if err != nil { + return udp4 + udp6, nil + } + + return udp4 + udp6, nil +} diff --git a/v2ui/db.go b/v2ui/db.go new file mode 100644 index 00000000..2745b9de --- /dev/null +++ b/v2ui/db.go @@ -0,0 +1,28 @@ +package v2ui + +import ( + "gorm.io/driver/sqlite" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +var v2db *gorm.DB + +func initDB(dbPath string) error { + c := &gorm.Config{ + Logger: logger.Discard, + } + var err error + v2db, err = gorm.Open(sqlite.Open(dbPath), c) + if err != nil { + return err + } + + return nil +} + +func getV2Inbounds() ([]*V2Inbound, error) { + inbounds := make([]*V2Inbound, 0) + err := v2db.Model(V2Inbound{}).Find(&inbounds).Error + return inbounds, err +} diff --git a/v2ui/models.go b/v2ui/models.go new file mode 100644 index 00000000..9ac50ed7 --- /dev/null +++ b/v2ui/models.go @@ -0,0 +1,41 @@ +package v2ui + +import "x-ui/database/model" + +type V2Inbound struct { + Id int `gorm:"primaryKey;autoIncrement"` + Port int `gorm:"unique"` + Listen string + Protocol string + Settings string + StreamSettings string + Tag string `gorm:"unique"` + Sniffing string + Remark string + Up int64 + Down int64 + Enable bool +} + +func (i *V2Inbound) TableName() string { + return "inbound" +} + +func (i *V2Inbound) ToInbound(userId int) *model.Inbound { + return &model.Inbound{ + UserId: userId, + Up: i.Up, + Down: i.Down, + Total: 0, + Remark: i.Remark, + Enable: i.Enable, + ExpiryTime: 0, + Listen: i.Listen, + Port: i.Port, + Protocol: model.Protocol(i.Protocol), + Settings: i.Settings, + StreamSettings: i.StreamSettings, + Tag: i.Tag, + Sniffing: i.Sniffing, + } +} diff --git a/v2ui/v2ui.go b/v2ui/v2ui.go new file mode 100644 index 00000000..57d673cf --- /dev/null +++ b/v2ui/v2ui.go @@ -0,0 +1,51 @@ +package v2ui + +import ( + "fmt" + "x-ui/config" + "x-ui/database" + "x-ui/database/model" + "x-ui/util/common" + "x-ui/web/service" +) + +func MigrateFromV2UI(dbPath string) error { + err := initDB(dbPath) + if err != nil { + return common.NewError("init v2-ui database failed:", err) + } + err = database.InitDB(config.GetDBPath()) + if err != nil { + return common.NewError("init x-ui database failed:", err) + } + + v2Inbounds, err := getV2Inbounds() + if err != nil { + return common.NewError("get v2-ui inbounds failed:", err) + } + if len(v2Inbounds) == 0 { + fmt.Println("migrate v2-ui inbounds success: 0") + return nil + } + + userService := service.UserService{} + user, err := userService.GetFirstUser() + if err != nil { + return common.NewError("get x-ui user failed:", err) + } + + inbounds := make([]*model.Inbound, 0) + for _, v2inbound := range v2Inbounds { + inbounds = append(inbounds, v2inbound.ToInbound(user.Id)) + } + + inboundService := service.InboundService{} + err = inboundService.AddInbounds(inbounds) + if err != nil { + return common.NewError("add x-ui inbounds failed:", err) + } + + fmt.Println("migrate v2-ui inbounds success:", len(inbounds)) + + return nil +} diff --git a/web/assets/ant-design-vue@1.7.2/antd-with-locales.min.js b/web/assets/ant-design-vue@1.7.2/antd-with-locales.min.js new file mode 100644 index 00000000..3bf52de5 --- /dev/null +++ b/web/assets/ant-design-vue@1.7.2/antd-with-locales.min.js @@ -0,0 +1,3 @@ +/*! For license information please see antd-with-locales.min.js.LICENSE.txt */ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("moment"),require("vue")):"function"==typeof define&&define.amd?define(["moment","vue"],t):"object"==typeof exports?exports.antd=t(require("moment"),require("vue")):e.antd=t(e.moment,e.Vue)}(window,(function(e,t){return function(e){var t={};function n(i){if(t[i])return t[i].exports;var r=t[i]={i:i,l:!1,exports:{}};return e[i].call(r.exports,r,r.exports,n),r.l=!0,r.exports}return n.m=e,n.c=t,n.d=function(e,t,i){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:i})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var i=Object.create(null);if(n.r(i),Object.defineProperty(i,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var r in e)n.d(i,r,function(t){return e[t]}.bind(null,r));return i},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=547)}([function(e,t,n){"use strict";var i=n(14),r=n.n(i),a=n(36),o=n.n(a),s=Object.prototype,c=s.toString,l=s.hasOwnProperty,u=/^\s*function (\w+)/,h=function(e){var t=null!=e?e.type?e.type:e:null,n=t&&t.toString().match(u);return n&&n[1]},d=function(e){if(null==e)return null;var t=e.constructor.toString().match(u);return t&&t[1]},f=Number.isInteger||function(e){return"number"==typeof e&&isFinite(e)&&Math.floor(e)===e},p=Array.isArray||function(e){return"[object Array]"===c.call(e)},v=function(e){return"[object Function]"===c.call(e)},m=function(e,t){var n;return Object.defineProperty(t,"_vueTypes_name",{enumerable:!1,writable:!1,value:e}),n=t,Object.defineProperty(n,"isRequired",{get:function(){return this.required=!0,this},enumerable:!1}),function(e){Object.defineProperty(e,"def",{value:function(e){return void 0===e&&void 0===this.default?(this.default=void 0,this):v(e)||g(this,e)?(this.default=p(e)||o()(e)?function(){return e}:e,this):(b(this._vueTypes_name+' - invalid default value: "'+e+'"',e),this)},enumerable:!1,writable:!1})}(t),v(t.validator)&&(t.validator=t.validator.bind(t)),t},g=function e(t,n){var i=arguments.length>2&&void 0!==arguments[2]&&arguments[2],r=t,a=!0,s=void 0;o()(t)||(r={type:t});var c=r._vueTypes_name?r._vueTypes_name+" - ":"";return l.call(r,"type")&&null!==r.type&&(p(r.type)?(a=r.type.some((function(t){return e(t,n,!0)})),s=r.type.map((function(e){return h(e)})).join(" or ")):a="Array"===(s=h(r))?p(n):"Object"===s?o()(n):"String"===s||"Number"===s||"Boolean"===s||"Function"===s?d(n)===s:n instanceof r.type),a?l.call(r,"validator")&&v(r.validator)?((a=r.validator(n))||!1!==i||b(c+"custom validation failed"),a):a:(!1===i&&b(c+'value "'+n+'" should be of type "'+s+'"'),!1)},b=function(){},y={get any(){return m("any",{type:null})},get func(){return m("function",{type:Function}).def(C.func)},get bool(){return m("boolean",{type:Boolean}).def(C.bool)},get string(){return m("string",{type:String}).def(C.string)},get number(){return m("number",{type:Number}).def(C.number)},get array(){return m("array",{type:Array}).def(C.array)},get object(){return m("object",{type:Object}).def(C.object)},get integer(){return m("integer",{type:Number,validator:function(e){return f(e)}}).def(C.integer)},get symbol(){return m("symbol",{type:null,validator:function(e){return"symbol"===(void 0===e?"undefined":r()(e))}})},custom:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"custom validation failed";if("function"!=typeof e)throw new TypeError("[VueTypes error]: You must provide a function as argument");return m(e.name||"<>",{validator:function(){var n=e.apply(void 0,arguments);return n||b(this._vueTypes_name+" - "+t),n}})},oneOf:function(e){if(!p(e))throw new TypeError("[VueTypes error]: You must provide an array as argument");var t='oneOf - value should be one of "'+e.join('", "')+'"',n=e.reduce((function(e,t){return null!=t&&-1===e.indexOf(t.constructor)&&e.push(t.constructor),e}),[]);return m("oneOf",{type:n.length>0?n:null,validator:function(n){var i=-1!==e.indexOf(n);return i||b(t),i}})},instanceOf:function(e){return m("instanceOf",{type:e})},oneOfType:function(e){if(!p(e))throw new TypeError("[VueTypes error]: You must provide an array as argument");var t=!1,n=e.reduce((function(e,n){if(o()(n)){if("oneOf"===n._vueTypes_name)return e.concat(n.type||[]);if(n.type&&!v(n.validator)){if(p(n.type))return e.concat(n.type);e.push(n.type)}else v(n.validator)&&(t=!0);return e}return e.push(n),e}),[]);if(!t)return m("oneOfType",{type:n}).def(void 0);var i=e.map((function(e){return e&&p(e.type)?e.type.map(h):h(e)})).reduce((function(e,t){return e.concat(p(t)?t:[t])}),[]).join('", "');return this.custom((function(t){var n=e.some((function(e){return"oneOf"===e._vueTypes_name?!e.type||g(e.type,t,!0):g(e,t,!0)}));return n||b('oneOfType - value type should be one of "'+i+'"'),n})).def(void 0)},arrayOf:function(e){return m("arrayOf",{type:Array,validator:function(t){var n=t.every((function(t){return g(e,t)}));return n||b('arrayOf - value must be an array of "'+h(e)+'"'),n}})},objectOf:function(e){return m("objectOf",{type:Object,validator:function(t){var n=Object.keys(t).every((function(n){return g(e,t[n])}));return n||b('objectOf - value must be an object of "'+h(e)+'"'),n}})},shape:function(e){var t=Object.keys(e),n=t.filter((function(t){return e[t]&&!0===e[t].required})),i=m("shape",{type:Object,validator:function(i){var r=this;if(!o()(i))return!1;var a=Object.keys(i);return n.length>0&&n.some((function(e){return-1===a.indexOf(e)}))?(b('shape - at least one of required properties "'+n.join('", "')+'" is not present'),!1):a.every((function(n){if(-1===t.indexOf(n))return!0===r._vueTypes_isLoose||(b('shape - object is missing "'+n+'" property'),!1);var a=e[n];return g(a,i[n])}))}});return Object.defineProperty(i,"_vueTypes_isLoose",{enumerable:!1,writable:!0,value:!1}),Object.defineProperty(i,"loose",{get:function(){return this._vueTypes_isLoose=!0,this},enumerable:!1}),i}},C={func:void 0,bool:void 0,string:void 0,number:void 0,array:void 0,object:void 0,integer:void 0};Object.defineProperty(y,"sensibleDefaults",{enumerable:!1,set:function(e){!1===e?C={}:!0===e?C={func:void 0,bool:void 0,string:void 0,number:void 0,array:void 0,object:void 0,integer:void 0}:o()(e)&&(C=e)},get:function(){return C}});t.a=y},function(e,t,n){"use strict";n.d(t,"i",(function(){return T})),n.d(t,"h",(function(){return V})),n.d(t,"k",(function(){return P})),n.d(t,"f",(function(){return j})),n.d(t,"q",(function(){return H})),n.d(t,"u",(function(){return _})),n.d(t,"v",(function(){return L})),n.d(t,"c",(function(){return F})),n.d(t,"x",(function(){return A})),n.d(t,"s",(function(){return m})),n.d(t,"l",(function(){return k})),n.d(t,"g",(function(){return z})),n.d(t,"o",(function(){return x})),n.d(t,"m",(function(){return w})),n.d(t,"j",(function(){return M})),n.d(t,"e",(function(){return O})),n.d(t,"r",(function(){return S})),n.d(t,"y",(function(){return v})),n.d(t,"t",(function(){return E})),n.d(t,"w",(function(){return D})),n.d(t,"a",(function(){return p})),n.d(t,"p",(function(){return b})),n.d(t,"n",(function(){return y})),n.d(t,"d",(function(){return C}));var i=n(14),r=n.n(i),a=n(22),o=n.n(a),s=n(2),c=n.n(s),l=n(36),u=n.n(l),h=n(5),d=n.n(h);var f=/-(\w)/g,p=function(e){return e.replace(f,(function(e,t){return t?t.toUpperCase():""}))},v=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=arguments[1],n={},i=/;(?![^(]*\))/g,r=/:(.+)/;return e.split(i).forEach((function(e){if(e){var i=e.split(r);if(i.length>1){var a=t?p(i[0].trim()):i[0].trim();n[a]=i[1].trim()}}})),n},m=function(e,t){return t in((e.$options||{}).propsData||{})},g=function(e){return e.data&&e.data.scopedSlots||{}},b=function(e){var t=e.componentOptions||{};e.$vnode&&(t=e.$vnode.componentOptions||{});var n=e.children||t.children||[],i={};return n.forEach((function(e){if(!_(e)){var t=e.data&&e.data.slot||"default";i[t]=i[t]||[],i[t].push(e)}})),c()({},i,g(e))},y=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"default",n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return e.$scopedSlots&&e.$scopedSlots[t]&&e.$scopedSlots[t](n)||e.$slots[t]||[]},C=function(e){var t=e.componentOptions||{};return e.$vnode&&(t=e.$vnode.componentOptions||{}),e.children||t.children||[]},x=function(e){if(e.fnOptions)return e.fnOptions;var t=e.componentOptions;return e.$vnode&&(t=e.$vnode.componentOptions),t&&t.Ctor.options||{}},k=function(e){if(e.componentOptions){var t=e.componentOptions,n=t.propsData,i=void 0===n?{}:n,r=t.Ctor,a=((void 0===r?{}:r).options||{}).props||{},s={},l=!0,u=!1,h=void 0;try{for(var d,f=Object.entries(a)[Symbol.iterator]();!(l=(d=f.next()).done);l=!0){var p=d.value,v=o()(p,2),m=v[0],g=v[1],b=g.default;void 0!==b&&(s[m]="function"==typeof b&&"Function"!==(y=g.type,C=void 0,(C=y&&y.toString().match(/^\s*function (\w+)/))?C[1]:"")?b.call(e):b)}}catch(e){u=!0,h=e}finally{try{!l&&f.return&&f.return()}finally{if(u)throw h}}return c()({},s,i)}var y,C,x=e.$options,k=void 0===x?{}:x,z=e.$props;return function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n={};return Object.keys(e).forEach((function(i){(i in t||void 0!==e[i])&&(n[i]=e[i])})),n}(void 0===z?{}:z,k.propsData)},z=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e,i=!(arguments.length>3&&void 0!==arguments[3])||arguments[3];if(e.$createElement){var r=e.$createElement,a=e[t];return void 0!==a?"function"==typeof a&&i?a(r,n):a:e.$scopedSlots[t]&&i&&e.$scopedSlots[t](n)||e.$scopedSlots[t]||e.$slots[t]||void 0}var o=e.context.$createElement,s=w(e)[t];if(void 0!==s)return"function"==typeof s&&i?s(o,n):s;var c=g(e)[t];if(void 0!==c)return"function"==typeof c&&i?c(o,n):c;var l=[],u=e.componentOptions||{};return(u.children||[]).forEach((function(e){e.data&&e.data.slot===t&&(e.data.attrs&&delete e.data.attrs.slot,"template"===e.tag?l.push(e.children):l.push(e))})),l.length?l:void 0},w=function(e){var t=e.componentOptions;return e.$vnode&&(t=e.$vnode.componentOptions),t&&t.propsData||{}},S=function(e,t){return w(e)[t]},O=function(e){var t=e.data;return e.$vnode&&(t=e.$vnode.data),t&&t.attrs||{}},M=function(e){var t=e.key;return e.$vnode&&(t=e.$vnode.key),t};function T(e){var t={};return e.componentOptions&&e.componentOptions.listeners?t=e.componentOptions.listeners:e.data&&e.data.on&&(t=e.data.on),c()({},t)}function V(e){var t={};return e.data&&e.data.on&&(t=e.data.on),c()({},t)}function P(e){return(e.$vnode?e.$vnode.componentOptions.listeners:e.$listeners)||{}}function j(e){var t={};e.data?t=e.data:e.$vnode&&e.$vnode.data&&(t=e.$vnode.data);var n=t.class||{},i=t.staticClass,r={};return i&&i.split(" ").forEach((function(e){r[e.trim()]=!0})),"string"==typeof n?n.split(" ").forEach((function(e){r[e.trim()]=!0})):Array.isArray(n)?d()(n).split(" ").forEach((function(e){r[e.trim()]=!0})):r=c()({},r,n),r}function H(e,t){var n={};e.data?n=e.data:e.$vnode&&e.$vnode.data&&(n=e.$vnode.data);var i=n.style||n.staticStyle;if("string"==typeof i)i=v(i,t);else if(t&&i){var r={};return Object.keys(i).forEach((function(e){return r[p(e)]=i[e]})),r}return i}function _(e){return!(e.tag||e.text&&""!==e.text.trim())}function L(e){return!e.tag}function F(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return e.filter((function(e){return!_(e)}))}var E=function(e,t){return Object.keys(t).forEach((function(n){if(!e[n])throw new Error("not have "+n+" prop");e[n].def&&(e[n]=e[n].def(t[n]))})),e};function A(){var e=[].slice.call(arguments,0),t={};return e.forEach((function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},n=!0,i=!1,r=void 0;try{for(var a,s=Object.entries(e)[Symbol.iterator]();!(n=(a=s.next()).done);n=!0){var l=a.value,h=o()(l,2),d=h[0],f=h[1];t[d]=t[d]||{},u()(f)?c()(t[d],f):t[d]=f}}catch(e){i=!0,r=e}finally{try{!n&&s.return&&s.return()}finally{if(i)throw r}}})),t}function D(e){return e&&"object"===(void 0===e?"undefined":r()(e))&&"componentOptions"in e&&"context"in e&&void 0!==e.tag}t.b=m},function(e,t,n){"use strict";t.__esModule=!0;var i,r=n(247),a=(i=r)&&i.__esModule?i:{default:i};t.default=a.default||function(e){for(var t=1;t0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1],n="function"==typeof e?e(this.$data,this.$props):e;if(this.getDerivedStateFromProps){var i=this.getDerivedStateFromProps(Object(s.l)(this),o()({},this.$data,n));if(null===i)return;n=o()({},n,i||{})}o()(this.$data,n),this.$forceUpdate(),this.$nextTick((function(){t&&t()}))},__emit:function(){var e=[].slice.call(arguments,0),t=e[0],n=this.$listeners[t];if(e.length&&n)if(Array.isArray(n))for(var i=0,a=n.length;i0&&void 0!==arguments[0]?arguments[0]:[],t={};return e.forEach((function(e){t[e]=function(t){this._proxyVm._data[e]=t}})),t}(["prefixCls","csp","autoInsertSpaceInButton","locale","pageHeader","transformCellText"])),methods:{renderEmptyComponent:function(e,t){return(Object(c.g)(this,"renderEmpty",{},!1)||h)(e,t)},getPrefixCls:function(e,t){var n=this.$props.prefixCls,i=void 0===n?"ant":n;return t||(e?i+"-"+e:i)},renderProvider:function(e){return(0,this.$createElement)(f.b,{attrs:{locale:this.locale||e,_ANT_MARK__:f.a}},[this.$slots.default?Object(c.c)(this.$slots.default)[0]:null])}},render:function(){var e=this,t=arguments[0];return t(p.a,{scopedSlots:{default:function(t,n,i){return e.renderProvider(i)}}})}},m={getPrefixCls:function(e,t){return t||"ant-"+e},renderEmpty:h};v.install=function(e){e.use(d.a),e.component(v.name,v)};t.b=v},function(e,t,n){"use strict";var i=n(6),r=n.n(i),a=n(2),o=n.n(a),s=n(3),c=n.n(s),l=n(11),u=n.n(l),h=n(5),d=n.n(h),f=n(160),p=n(62),v={primaryColor:"#333",secondaryColor:"#E6E6E6"},m={name:"AntdIcon",props:["type","primaryColor","secondaryColor"],displayName:"IconVue",definitions:new p.a,data:function(){return{twoToneColorPalette:v}},add:function(){for(var e=arguments.length,t=Array(e),n=0;n1&&void 0!==arguments[1]?arguments[1]:v;if(e){var n=m.definitions.get(e);return n&&"function"==typeof n.icon&&(n=o()({},n,{icon:n.icon(t.primaryColor,t.secondaryColor)})),n}},setTwoToneColors:function(e){var t=e.primaryColor,n=e.secondaryColor;v.primaryColor=t,v.secondaryColor=n||Object(p.c)(t)},getTwoToneColors:function(){return o()({},v)},render:function(e){var t=this.$props,n=t.type,i=t.primaryColor,r=t.secondaryColor,a=void 0,s=v;if(i&&(s={primaryColor:i,secondaryColor:r||Object(p.c)(i)}),Object(p.d)(n))a=n;else if("string"==typeof n&&!(a=m.get(n,s)))return null;return a?(a&&"function"==typeof a.icon&&(a=o()({},a,{icon:a.icon(s.primaryColor,s.secondaryColor)})),Object(p.b)(e,a.icon,"svg-"+a.name,{attrs:{"data-icon":a.name,width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true"},on:this.$listeners})):(Object(p.e)("type should be string or icon definiton, but got "+n),null)},install:function(e){e.component(m.name,m)}},g=m,b=n(0),y=n(12),C=n.n(y),x=n(1),k=new Set;var z=n(13),w={width:"1em",height:"1em",fill:"currentColor","aria-hidden":"true",focusable:"false"},S=/-fill$/,O=/-o$/,M=/-twotone$/;var T=n(26);function V(e){return g.setTwoToneColors({primaryColor:e})}var P=n(10);g.add.apply(g,u()(Object.keys(f).map((function(e){return f[e]})))),V("#1890ff");function j(e,t,n){var i,a=n.$props,s=n.$slots,l=Object(x.k)(n),u=a.type,h=a.component,f=a.viewBox,p=a.spin,v=a.theme,m=a.twoToneColor,b=a.rotate,y=a.tabIndex,C=Object(x.c)(s.default);C=0===C.length?void 0:C,Object(z.a)(Boolean(u||h||C),"Icon","Icon should have `type` prop or `component` prop or `children`.");var k=d()((i={},c()(i,"anticon",!0),c()(i,"anticon-"+u,!!u),i)),T=d()(c()({},"anticon-spin",!!p||"loading"===u)),V=b?{msTransform:"rotate("+b+"deg)",transform:"rotate("+b+"deg)"}:void 0,P={attrs:o()({},w,{viewBox:f}),class:T,style:V};f||delete P.attrs.viewBox;var j=y;void 0===j&&"click"in l&&(j=-1);var H={attrs:{"aria-label":u&&t.icon+": "+u,tabIndex:j},on:l,class:k,staticClass:""};return e("i",H,[function(){if(h)return e(h,P,[C]);if(C){Object(z.a)(Boolean(f)||1===C.length&&"use"===C[0].tag,"Icon","Make sure that you provide correct `viewBox` prop (default `0 0 1024 1024`) to the icon.");var t={attrs:o()({},w),class:T,style:V};return e("svg",r()([t,{attrs:{viewBox:f}}]),[C])}if("string"==typeof u){var n=u;if(v){var i=function(e){var t=null;return S.test(e)?t="filled":O.test(e)?t="outlined":M.test(e)&&(t="twoTone"),t}(u);Object(z.a)(!i||v===i,"Icon","The icon name '"+u+"' already specify a theme '"+i+"', the 'theme' prop '"+v+"' will be ignored.")}return n=function(e,t){var n=e;return"filled"===t?n+="-fill":"outlined"===t?n+="-o":"twoTone"===t?n+="-twotone":Object(z.a)(!1,"Icon","This icon '"+e+"' has unknown theme '"+t+"'"),n}(function(e){return e.replace(S,"").replace(O,"").replace(M,"")}(function(e){var t=e;switch(e){case"cross":t="close";break;case"interation":t="interaction";break;case"canlendar":t="calendar";break;case"colum-height":t="column-height"}return Object(z.a)(t===e,"Icon","Icon '"+e+"' was a typo and is now deprecated, please use '"+t+"' instead."),t}(n)),v||"outlined"),e(g,{attrs:{focusable:"false",type:n,primaryColor:m},class:T,style:V})}}()])}var H={name:"AIcon",props:{tabIndex:b.a.number,type:b.a.string,component:b.a.any,viewBox:b.a.any,spin:b.a.bool.def(!1),rotate:b.a.number,theme:b.a.oneOf(["filled","outlined","twoTone"]),twoToneColor:b.a.string,role:b.a.string},render:function(e){var t=this;return e(T.a,{attrs:{componentName:"Icon"},scopedSlots:{default:function(n){return j(e,n,t)}}})},createFromIconfontCN:function(e){var t=e.scriptUrl,n=e.extraCommonProps,i=void 0===n?{}:n;if("undefined"!=typeof document&&"undefined"!=typeof window&&"function"==typeof document.createElement&&"string"==typeof t&&t.length&&!k.has(t)){var r=document.createElement("script");r.setAttribute("src",t),r.setAttribute("data-namespace",t),k.add(t),document.body.appendChild(r)}return{functional:!0,name:"AIconfont",props:_.props,render:function(e,t){var n=t.props,r=t.slots,a=t.listeners,o=t.data,s=n.type,c=C()(n,["type"]),l=r().default,u=null;s&&(u=e("use",{attrs:{"xlink:href":"#"+s}})),l&&(u=l);var h=Object(x.x)(i,o,{props:c,on:a});return e(_,h,[u])}}},getTwoToneColor:function(){return g.getTwoToneColors().primaryColor}};H.setTwoToneColor=V,H.install=function(e){e.use(P.a),e.component(H.name,H)};var _=t.a=H},function(e,t,n){"use strict";n.d(t,"b",(function(){return h})),n.d(t,"a",(function(){return d}));var i=n(11),r=n.n(i),a=n(2),o=n.n(a),s=n(1),c=n(5),l=n.n(c);function u(e,t){var n=e.componentOptions,i=e.data,r={};n&&n.listeners&&(r=o()({},n.listeners));var a={};i&&i.on&&(a=o()({},i.on));var s=new e.constructor(e.tag,i?o()({},i,{on:a}):i,e.children,e.text,e.elm,e.context,n?o()({},n,{listeners:r}):n,e.asyncFactory);return s.ns=e.ns,s.isStatic=e.isStatic,s.key=e.key,s.isComment=e.isComment,s.fnContext=e.fnContext,s.fnOptions=e.fnOptions,s.fnScopeId=e.fnScopeId,s.isCloned=!0,t&&(e.children&&(s.children=h(e.children,!0)),n&&n.children&&(n.children=h(n.children,!0))),s}function h(e,t){for(var n=e.length,i=new Array(n),r=0;r1&&void 0!==arguments[1]?arguments[1]:{},n=arguments[2],i=e;if(Array.isArray(e)&&(i=Object(s.c)(e)[0]),!i)return null;var a=u(i,n),c=t.props,h=void 0===c?{}:c,d=t.key,f=t.on,p=void 0===f?{}:f,v=t.nativeOn,m=void 0===v?{}:v,g=t.children,b=t.directives,y=void 0===b?[]:b,C=a.data||{},x={},k={},z=t.attrs,w=void 0===z?{}:z,S=t.ref,O=t.domProps,M=void 0===O?{}:O,T=t.style,V=void 0===T?{}:T,P=t.class,j=void 0===P?{}:P,H=t.scopedSlots,_=void 0===H?{}:H;return k="string"==typeof C.style?Object(s.y)(C.style):o()({},C.style,k),k="string"==typeof V?o()({},k,Object(s.y)(k)):o()({},k,V),"string"==typeof C.class&&""!==C.class.trim()?C.class.split(" ").forEach((function(e){x[e.trim()]=!0})):Array.isArray(C.class)?l()(C.class).split(" ").forEach((function(e){x[e.trim()]=!0})):x=o()({},C.class,x),"string"==typeof j&&""!==j.trim()?j.split(" ").forEach((function(e){x[e.trim()]=!0})):x=o()({},x,j),a.data=o()({},C,{style:k,attrs:o()({},C.attrs,w),class:x,domProps:o()({},C.domProps,M),scopedSlots:o()({},C.scopedSlots,_),directives:[].concat(r()(C.directives||[]),r()(y))}),a.componentOptions?(a.componentOptions.propsData=a.componentOptions.propsData||{},a.componentOptions.listeners=a.componentOptions.listeners||{},a.componentOptions.propsData=o()({},a.componentOptions.propsData,h),a.componentOptions.listeners=o()({},a.componentOptions.listeners,p),g&&(a.componentOptions.children=g)):(g&&(a.children=g),a.data.on=o()({},a.data.on||{},p)),a.data.on=o()({},a.data.on||{},m),void 0!==d&&(a.key=d,a.data.key=d),"string"==typeof S&&(a.data.ref=S),a}},function(e,t,n){"use strict";var i=n(25),r=n.n(i),a=n(116),o=n(80);function s(e){return e.directive("ant-portal",{inserted:function(e,t){var n=t.value,i="function"==typeof n?n(e):n;i!==e.parentNode&&i.appendChild(e)},componentUpdated:function(e,t){var n=t.value,i="function"==typeof n?n(e):n;i!==e.parentNode&&i.appendChild(e)}})}var c={install:function(e){e.use(r.a,{name:"ant-ref"}),Object(a.a)(e),Object(o.a)(e),s(e)}},l={};l.install=function(e){l.Vue=e,e.use(c)};t.a=l},function(e,t,n){"use strict";t.__esModule=!0;var i,r=n(276),a=(i=r)&&i.__esModule?i:{default:i};t.default=function(e){if(Array.isArray(e)){for(var t=0,n=Array(e.length);t=0||Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);return n}},function(e,t,n){"use strict";var i={};function r(e,t){0}function a(e,t,n){t||i[n]||(e(!1,n),i[n]=!0)}var o=function(e,t){a(r,e,t)};t.a=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";o(e,"[antdv: "+t+"] "+n)}},function(e,t,n){"use strict";t.__esModule=!0;var i=o(n(253)),r=o(n(263)),a="function"==typeof r.default&&"symbol"==typeof i.default?function(e){return typeof e}:function(e){return e&&"function"==typeof r.default&&e.constructor===r.default&&e!==r.default.prototype?"symbol":typeof e};function o(e){return e&&e.__esModule?e:{default:e}}t.default="function"==typeof r.default&&"symbol"===a(i.default)?function(e){return void 0===e?"undefined":a(e)}:function(e){return e&&"function"==typeof r.default&&e.constructor===r.default&&e!==r.default.prototype?"symbol":void 0===e?"undefined":a(e)}},function(t,n){t.exports=e},function(e,t,n){"use strict";var i=n(2),r=n.n(i);t.a=function(e,t){for(var n=r()({},e),i=0;i=0&&n.splice(i,1),n}function y(e,t){var n=e.slice();return-1===n.indexOf(t)&&n.push(t),n}function C(e){return e.split("-")}function x(e,t){return e+"-"+t}function k(e){return Object(v.o)(e).isTreeNode}function z(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];return e.filter(k)}function w(e){var t=Object(v.l)(e)||{},n=t.disabled,i=t.disableCheckbox,r=t.checkable;return!(!n&&!i)||!1===r}function S(e,t){!function n(i,r,a){var o=i?i.componentOptions.children:e,s=i?x(a.pos,r):0,c=z(o);if(i){var l=i.key;l||null!=l||(l=s);var u={node:i,index:r,pos:s,key:l,parentPos:a.node?a.pos:null};t(u)}c.forEach((function(e,t){n(e,t,{node:i,pos:s})}))}(null)}function O(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],t=arguments[1],n=e.map(t);return 1===n.length?n[0]:n}function M(e,t){var n=Object(v.l)(t),i=n.eventKey,r=n.pos,a=[];return S(e,(function(e){var t=e.key;a.push(t)})),a.push(i||r),a}function T(e,t){var n=e.clientY,i=t.$refs.selectHandle.getBoundingClientRect(),r=i.top,a=i.bottom,o=i.height,s=Math.max(.25*o,2);return n<=r+s?-1:n>=a-s?1:0}function V(e,t){if(e)return t.multiple?e.slice():e.length?[e[0]]:e}var P=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{props:Object(f.a)(e,["on","key","class","className","style"]),on:e.on||{},class:e.class||e.className,style:e.style,key:e.key}};function j(e,t,n){if(!t)return[];var i=(n||{}).processProps,r=void 0===i?P:i;return(Array.isArray(t)?t:[t]).map((function(t){var i=t.children,a=u()(t,["children"]),o=j(e,i,n);return e(p.a,r(a),[o])}))}function H(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.initWrapper,i=t.processEntity,r=t.onProcessFinished,a=new Map,o=new Map,s={posEntities:a,keyEntities:o};return n&&(s=n(s)||s),S(e,(function(e){var t=e.node,n=e.index,r=e.pos,c=e.key,l=e.parentPos,u={node:t,index:n,key:c,pos:r};a.set(r,u),o.set(c,u),u.parent=a.get(l),u.parent&&(u.parent.children=u.parent.children||[],u.parent.children.push(u)),i&&i(u,s)})),r&&r(s),s}function _(e){if(!e)return null;var t=void 0;if(Array.isArray(e))t={checkedKeys:e,halfCheckedKeys:void 0};else{if("object"!==(void 0===e?"undefined":c()(e)))return d()(!1,"`checkedKeys` is not an array or an object"),null;t={checkedKeys:e.checked||void 0,halfCheckedKeys:e.halfChecked||void 0}}return t}function L(e,t,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},r=new Map,a=new Map;function s(e){if(r.get(e)!==t){var i=n.get(e);if(i){var o=i.children,c=i.parent;if(!w(i.node)){var l=!0,u=!1;(o||[]).filter((function(e){return!w(e.node)})).forEach((function(e){var t=e.key,n=r.get(t),i=a.get(t);(n||i)&&(u=!0),n||(l=!1)})),t?r.set(e,l):r.set(e,!1),a.set(e,u),c&&s(c.key)}}}}function c(e){if(r.get(e)!==t){var i=n.get(e);if(i){var a=i.children;w(i.node)||(r.set(e,t),(a||[]).forEach((function(e){c(e.key)})))}}}function l(e){var i=n.get(e);if(i){var a=i.children,o=i.parent,l=i.node;r.set(e,t),w(l)||((a||[]).filter((function(e){return!w(e.node)})).forEach((function(e){c(e.key)})),o&&s(o.key))}else d()(!1,"'"+e+"' does not exist in the tree.")}(i.checkedKeys||[]).forEach((function(e){r.set(e,!0)})),(i.halfCheckedKeys||[]).forEach((function(e){a.set(e,!0)})),(e||[]).forEach((function(e){l(e)}));var u=[],h=[],f=!0,p=!1,v=void 0;try{for(var m,g=r[Symbol.iterator]();!(f=(m=g.next()).done);f=!0){var b=m.value,y=o()(b,2),C=y[0],x=y[1];x&&u.push(C)}}catch(e){p=!0,v=e}finally{try{!f&&g.return&&g.return()}finally{if(p)throw v}}var k=!0,z=!1,S=void 0;try{for(var O,M=a[Symbol.iterator]();!(k=(O=M.next()).done);k=!0){var T=O.value,V=o()(T,2),P=V[0],j=V[1];!r.get(P)&&j&&h.push(P)}}catch(e){z=!0,S=e}finally{try{!k&&M.return&&M.return()}finally{if(z)throw S}}return{checkedKeys:u,halfCheckedKeys:h}}function F(e,t){var n=new Map;return(e||[]).forEach((function(e){!function e(i){if(!n.get(i)){var r=t.get(i);if(r){n.set(i,!0);var a=r.parent,o=r.node,s=Object(v.l)(o);s&&s.disabled||a&&e(a.key)}}}(e)})),[].concat(r()(n.keys()))}},function(e,n){e.exports=t},function(e,t,n){(function(t){for(var i=n(289),r="undefined"==typeof window?t:window,a=["moz","webkit"],o="AnimationFrame",s=r["request"+o],c=r["cancel"+o]||r["cancelRequest"+o],l=0;!s&&l1&&void 0!==arguments[1]?arguments[1]:{},n=t.beforeEnter,a=t.enter,o=t.afterEnter,s=t.leave,c=t.afterLeave,l=t.appear,u=void 0===l||l,h=t.tag,d=t.nativeOn,f={props:{appear:u,css:!1},on:{beforeEnter:n||r,enter:a||function(t,n){Object(i.a)(t,e+"-enter",n)},afterEnter:o||r,leave:s||function(t,n){Object(i.a)(t,e+"-leave",n)},afterLeave:c||r},nativeOn:d};return h&&(f.tag=h),f}},function(e,t,n){"use strict";var i=function(){};e.exports=i},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default={install:function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=t.name||"ref";e.directive(n,{bind:function(t,n,i){e.nextTick((function(){n.value(i.componentInstance||t,i.key)})),n.value(i.componentInstance||t,i.key)},update:function(e,t,i,r){if(r.data&&r.data.directives){var a=r.data.directives.find((function(e){return e.name===n}));if(a&&a.value!==t.value)return a&&a.value(null,r.key),void t.value(i.componentInstance||e,i.key)}i.componentInstance===r.componentInstance&&i.elm===r.elm||t.value(i.componentInstance||e,i.key)},unbind:function(e,t,n){t.value(null,n.key)}})}}},function(e,t,n){"use strict";var i=n(2),r=n.n(i),a=n(0),o=n(37);t.a={name:"LocaleReceiver",props:{componentName:a.a.string.def("global"),defaultLocale:a.a.oneOfType([a.a.object,a.a.func]),children:a.a.func},inject:{localeData:{default:function(){return{}}}},methods:{getLocale:function(){var e=this.componentName,t=this.defaultLocale||o.a[e||"global"],n=this.localeData.antLocale,i=e&&n?n[e]:{};return r()({},"function"==typeof t?t():t,i||{})},getLocaleCode:function(){var e=this.localeData.antLocale,t=e&&e.locale;return e&&e.exist&&!t?o.a.locale:t}},render:function(){var e=this.$scopedSlots,t=this.children||e.default,n=this.localeData.antLocale;return t(this.getLocale(),this.getLocaleCode(),n)}}},function(e,t,n){"use strict";function i(e){return e.default||e}n.d(t,"a",(function(){return i}))},function(e,t){e.exports=function(e,t,n,i){var r=n?n.call(i,e,t):void 0;if(void 0!==r)return!!r;if(e===t)return!0;if("object"!=typeof e||!e||"object"!=typeof t||!t)return!1;var a=Object.keys(e),o=Object.keys(t);if(a.length!==o.length)return!1;for(var s=Object.prototype.hasOwnProperty.bind(t),c=0;c=0&&n.left>=0&&n.bottom>n.top&&n.right>n.left?n:null}function oe(e){var t,n,i;if(te.isWindow(e)||9===e.nodeType){var r=te.getWindow(e);t={left:te.getWindowScrollLeft(r),top:te.getWindowScrollTop(r)},n=te.viewportWidth(r),i=te.viewportHeight(r)}else t=te.offset(e),n=te.outerWidth(e),i=te.outerHeight(e);return t.width=n,t.height=i,t}function se(e,t){var n=t.charAt(0),i=t.charAt(1),r=e.width,a=e.height,o=e.left,s=e.top;return"c"===n?s+=a/2:"b"===n&&(s+=a),"c"===i?o+=r/2:"r"===i&&(o+=r),{left:o,top:s}}function ce(e,t,n,i,r){var a=se(t,n[1]),o=se(e,n[0]),s=[o.left-a.left,o.top-a.top];return{left:Math.round(e.left-s[0]+i[0]-r[0]),top:Math.round(e.top-s[1]+i[1]-r[1])}}function le(e,t,n){return e.leftn.right}function ue(e,t,n){return e.topn.bottom}function he(e,t,n){var i=[];return te.each(e,(function(e){i.push(e.replace(t,(function(e){return n[e]})))})),i}function de(e,t){return e[t]=-e[t],e}function fe(e,t){return(/%$/.test(e)?parseInt(e.substring(0,e.length-1),10)/100*t:parseInt(e,10))||0}function pe(e,t){e[0]=fe(e[0],t.width),e[1]=fe(e[1],t.height)}function ve(e,t,n,i){var r=n.points,a=n.offset||[0,0],o=n.targetOffset||[0,0],s=n.overflow,c=n.source||e;a=[].concat(a),o=[].concat(o);var l={},u=0,h=ae(c,!(!(s=s||{})||!s.alwaysByViewport)),d=oe(c);pe(a,d),pe(o,t);var f=ce(d,t,r,a,o),p=te.merge(d,f);if(h&&(s.adjustX||s.adjustY)&&i){if(s.adjustX&&le(f,d,h)){var v=he(r,/[lr]/gi,{l:"r",r:"l"}),m=de(a,0),g=de(o,0);(function(e,t,n){return e.left>n.right||e.left+t.widthn.bottom||e.top+t.height=n.left&&r.left+a.width>n.right&&(a.width-=r.left+a.width-n.right),i.adjustX&&r.left+a.width>n.right&&(r.left=Math.max(n.right-a.width,n.left)),i.adjustY&&r.top=n.top&&r.top+a.height>n.bottom&&(a.height-=r.top+a.height-n.bottom),i.adjustY&&r.top+a.height>n.bottom&&(r.top=Math.max(n.bottom-a.height,n.top)),te.mix(r,a)}(f,d,h,l))}return p.width!==d.width&&te.css(c,"width",te.width(c)+p.width-d.width),p.height!==d.height&&te.css(c,"height",te.height(c)+p.height-d.height),te.offset(c,{left:p.left,top:p.top},{useCssRight:n.useCssRight,useCssBottom:n.useCssBottom,useCssTransform:n.useCssTransform,ignoreShake:n.ignoreShake}),{points:r,offset:a,targetOffset:o,overflow:l}}function me(e,t,n){var i=n.target||t;return ve(e,oe(i),n,!function(e,t){var n=ae(e,t),i=oe(e);return!n||i.left+i.width<=n.left||i.top+i.height<=n.top||i.left>=n.right||i.top>=n.bottom}(i,n.overflow&&n.overflow.alwaysByViewport))}function ge(e,t,n){var i,r,a=te.getDocument(e),o=a.defaultView||a.parentWindow,s=te.getWindowScrollLeft(o),c=te.getWindowScrollTop(o),l=te.viewportWidth(o),u=te.viewportHeight(o);i="pageX"in t?t.pageX:s+t.clientX,r="pageY"in t?t.pageY:c+t.clientY;var h=i>=0&&i<=s+l&&r>=0&&r<=c+u;return ve(e,{left:i,top:r,width:0,height:0},function(e){for(var t=1;t1){var r="";i=e("div",{class:r},[this.$slots.default])}else i=this.$slots.default[0];return i}},Ve={props:{hiddenClassName:u.a.string.def(""),prefixCls:u.a.string,visible:u.a.bool},render:function(){var e=arguments[0],t=this.$props,n=t.prefixCls,i=t.visible,r=t.hiddenClassName,a={on:Object(d.k)(this)};return e("div",Me()([a,{class:i?"":r}]),[e(Te,{class:n+"-content",attrs:{visible:i}},[this.$slots.default])])}},Pe=n(47),je=n(4),He={name:"VCTriggerPopup",mixins:[je.a],props:{visible:u.a.bool,getClassNameFromAlign:u.a.func,getRootDomNode:u.a.func,align:u.a.any,destroyPopupOnHide:u.a.bool,prefixCls:u.a.string,getContainer:u.a.func,transitionName:u.a.string,animation:u.a.any,maskAnimation:u.a.string,maskTransitionName:u.a.string,mask:u.a.bool,zIndex:u.a.number,popupClassName:u.a.any,popupStyle:u.a.object.def((function(){return{}})),stretch:u.a.string,point:u.a.shape({pageX:u.a.number,pageY:u.a.number})},data:function(){return this.domEl=null,{stretchChecked:!1,targetWidth:void 0,targetHeight:void 0}},mounted:function(){var e=this;this.$nextTick((function(){e.rootNode=e.getPopupDomNode(),e.setStretchSize()}))},updated:function(){var e=this;this.$nextTick((function(){e.setStretchSize()}))},beforeDestroy:function(){this.$el.parentNode?this.$el.parentNode.removeChild(this.$el):this.$el.remove&&this.$el.remove()},methods:{onAlign:function(e,t){var n=this.$props.getClassNameFromAlign(t);this.currentAlignClassName!==n&&(this.currentAlignClassName=n,e.className=this.getClassName(n));var i=Object(d.k)(this);i.align&&i.align(e,t)},setStretchSize:function(){var e=this.$props,t=e.stretch,n=e.getRootDomNode,i=e.visible,r=this.$data,a=r.stretchChecked,o=r.targetHeight,s=r.targetWidth;if(t&&i){var c=n();if(c){var l=c.offsetHeight,u=c.offsetWidth;o===l&&s===u&&a||this.setState({stretchChecked:!0,targetHeight:l,targetWidth:u})}}else a&&this.setState({stretchChecked:!1})},getPopupDomNode:function(){return this.$refs.popupInstance?this.$refs.popupInstance.$el:null},getTargetElement:function(){return this.$props.getRootDomNode()},getAlignTarget:function(){var e=this.$props.point;return e||this.getTargetElement},getMaskTransitionName:function(){var e=this.$props,t=e.maskTransitionName,n=e.maskAnimation;return!t&&n&&(t=e.prefixCls+"-"+n),t},getTransitionName:function(){var e=this.$props,t=e.transitionName,n=e.animation;return t||("string"==typeof n?t=""+n:n&&n.props&&n.props.name&&(t=n.props.name)),t},getClassName:function(e){return this.$props.prefixCls+" "+this.$props.popupClassName+" "+e},getPopupElement:function(){var e=this,t=this.$createElement,n=this.$props,i=this.$slots,r=this.getTransitionName,o=this.$data,s=o.stretchChecked,c=o.targetHeight,l=o.targetWidth,u=n.align,h=n.visible,f=n.prefixCls,p=n.animation,v=n.popupStyle,m=n.getClassNameFromAlign,b=n.destroyPopupOnHide,y=n.stretch,C=this.getClassName(this.currentAlignClassName||m(u));h||(this.currentAlignClassName=null);var x={};y&&(-1!==y.indexOf("height")?x.height="number"==typeof c?c+"px":c:-1!==y.indexOf("minHeight")&&(x.minHeight="number"==typeof c?c+"px":c),-1!==y.indexOf("width")?x.width="number"==typeof l?l+"px":l:-1!==y.indexOf("minWidth")&&(x.minWidth="number"==typeof l?l+"px":l),s||setTimeout((function(){e.$refs.alignInstance&&e.$refs.alignInstance.forceAlign()}),0));var k={props:{prefixCls:f,visible:h},class:C,on:Object(d.k)(this),ref:"popupInstance",style:a()({},x,v,this.getZIndexStyle())},z={props:{appear:!0,css:!1}},w=r(),S=!!w,O={beforeEnter:function(){},enter:function(t,n){e.$nextTick((function(){e.$refs.alignInstance?e.$refs.alignInstance.$nextTick((function(){e.domEl=t,Object(Pe.a)(t,w+"-enter",n)})):n()}))},beforeLeave:function(){e.domEl=null},leave:function(e,t){Object(Pe.a)(e,w+"-leave",t)}};if("object"===(void 0===p?"undefined":g()(p))){S=!0;var M=p.on,T=void 0===M?{}:M,V=p.props,P=void 0===V?{}:V;z.props=a()({},z.props,P),z.on=a()({},O,T)}else z.on=O;return S||(z={}),t("transition",z,b?[h?t(Se,{attrs:{target:this.getAlignTarget(),monitorWindowResize:!0,align:u},key:"popup",ref:"alignInstance",on:{align:this.onAlign}},[t(Ve,k,[i.default])]):null]:[t(Se,{directives:[{name:"show",value:h}],attrs:{target:this.getAlignTarget(),monitorWindowResize:!0,disabled:!h,align:u},key:"popup",ref:"alignInstance",on:{align:this.onAlign}},[t(Ve,k,[i.default])])])},getZIndexStyle:function(){var e={},t=this.$props;return void 0!==t.zIndex&&(e.zIndex=t.zIndex),e},getMaskElement:function(){var e=this.$createElement,t=this.$props,n=null;if(t.mask){var i=this.getMaskTransitionName();n=e(Te,{directives:[{name:"show",value:t.visible}],style:this.getZIndexStyle(),key:"mask",class:t.prefixCls+"-mask",attrs:{visible:t.visible}}),i&&(n=e("transition",{attrs:{appear:!0,name:i}},[n]))}return n}},render:function(){var e=arguments[0],t=this.getMaskElement,n=this.getPopupElement;return e("div",[t(),n()])}};function _e(e,t,n){return n?e[0]===t[0]:e[0]===t[0]&&e[1]===t[1]}function Le(){}var Fe={props:{autoMount:u.a.bool.def(!0),autoDestroy:u.a.bool.def(!0),visible:u.a.bool,forceRender:u.a.bool.def(!1),parent:u.a.any,getComponent:u.a.func.isRequired,getContainer:u.a.func.isRequired,children:u.a.func.isRequired},mounted:function(){this.autoMount&&this.renderComponent()},updated:function(){this.autoMount&&this.renderComponent()},beforeDestroy:function(){this.autoDestroy&&this.removeContainer()},methods:{removeContainer:function(){this.container&&(this._component&&this._component.$destroy(),this.container.parentNode.removeChild(this.container),this.container=null,this._component=null)},renderComponent:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments[1],n=this.visible,i=this.forceRender,r=this.getContainer,a=this.parent,o=this;if(n||a._component||a.$refs._component||i){var s=this.componentEl;this.container||(this.container=r(),s=document.createElement("div"),this.componentEl=s,this.container.appendChild(s));var c={component:o.getComponent(e)};this._component?this._component.setComponent(c):this._component=new this.$root.constructor({el:s,parent:o,data:{_com:c},mounted:function(){this.$nextTick((function(){t&&t.call(o)}))},updated:function(){this.$nextTick((function(){t&&t.call(o)}))},methods:{setComponent:function(e){this.$data._com=e}},render:function(){return this.$data._com.component}})}}},render:function(){return this.children({renderComponent:this.renderComponent,removeContainer:this.removeContainer})}};s.a.use(l.a,{name:"ant-ref"});var Ee=["click","mousedown","touchstart","mouseenter","mouseleave","focus","blur","contextmenu"],Ae={name:"Trigger",mixins:[je.a],props:{action:u.a.oneOfType([u.a.string,u.a.arrayOf(u.a.string)]).def([]),showAction:u.a.any.def([]),hideAction:u.a.any.def([]),getPopupClassNameFromAlign:u.a.any.def((function(){return""})),afterPopupVisibleChange:u.a.func.def(Le),popup:u.a.any,popupStyle:u.a.object.def((function(){return{}})),prefixCls:u.a.string.def("rc-trigger-popup"),popupClassName:u.a.string.def(""),popupPlacement:u.a.string,builtinPlacements:u.a.object,popupTransitionName:u.a.oneOfType([u.a.string,u.a.object]),popupAnimation:u.a.any,mouseEnterDelay:u.a.number.def(0),mouseLeaveDelay:u.a.number.def(.1),zIndex:u.a.number,focusDelay:u.a.number.def(0),blurDelay:u.a.number.def(.15),getPopupContainer:u.a.func,getDocument:u.a.func.def((function(){return window.document})),forceRender:u.a.bool,destroyPopupOnHide:u.a.bool.def(!1),mask:u.a.bool.def(!1),maskClosable:u.a.bool.def(!0),popupAlign:u.a.object.def((function(){return{}})),popupVisible:u.a.bool,defaultPopupVisible:u.a.bool.def(!1),maskTransitionName:u.a.oneOfType([u.a.string,u.a.object]),maskAnimation:u.a.string,stretch:u.a.string,alignPoint:u.a.bool},provide:function(){return{vcTriggerContext:this}},inject:{vcTriggerContext:{default:function(){return{}}},savePopupRef:{default:function(){return Le}},dialogContext:{default:function(){return null}}},data:function(){var e=this,t=this.$props,n=void 0;return n=Object(d.s)(this,"popupVisible")?!!t.popupVisible:!!t.defaultPopupVisible,Ee.forEach((function(t){e["fire"+t]=function(n){e.fireEvents(t,n)}})),{prevPopupVisible:n,sPopupVisible:n,point:null}},watch:{popupVisible:function(e){void 0!==e&&(this.prevPopupVisible=this.sPopupVisible,this.sPopupVisible=e)}},deactivated:function(){this.setPopupVisible(!1)},mounted:function(){var e=this;this.$nextTick((function(){e.renderComponent(null),e.updatedCal()}))},updated:function(){var e=this;this.renderComponent(null,(function(){e.sPopupVisible!==e.prevPopupVisible&&e.afterPopupVisibleChange(e.sPopupVisible),e.prevPopupVisible=e.sPopupVisible})),this.$nextTick((function(){e.updatedCal()}))},beforeDestroy:function(){this.clearDelayTimer(),this.clearOutsideHandler(),clearTimeout(this.mouseDownTimeout)},methods:{updatedCal:function(){var e=this.$props;if(this.$data.sPopupVisible){var t=void 0;this.clickOutsideHandler||!this.isClickToHide()&&!this.isContextmenuToShow()||(t=e.getDocument(),this.clickOutsideHandler=Object(p.a)(t,"mousedown",this.onDocumentClick)),this.touchOutsideHandler||(t=t||e.getDocument(),this.touchOutsideHandler=Object(p.a)(t,"touchstart",this.onDocumentClick)),!this.contextmenuOutsideHandler1&&this.isContextmenuToShow()&&(t=t||e.getDocument(),this.contextmenuOutsideHandler1=Object(p.a)(t,"scroll",this.onContextmenuClose)),!this.contextmenuOutsideHandler2&&this.isContextmenuToShow()&&(this.contextmenuOutsideHandler2=Object(p.a)(window,"blur",this.onContextmenuClose))}else this.clearOutsideHandler()},onMouseenter:function(e){var t=this.$props.mouseEnterDelay;this.fireEvents("mouseenter",e),this.delaySetPopupVisible(!0,t,t?null:e)},onMouseMove:function(e){this.fireEvents("mousemove",e),this.setPoint(e)},onMouseleave:function(e){this.fireEvents("mouseleave",e),this.delaySetPopupVisible(!1,this.$props.mouseLeaveDelay)},onPopupMouseenter:function(){this.clearDelayTimer()},onPopupMouseleave:function(e){e&&e.relatedTarget&&!e.relatedTarget.setTimeout&&this._component&&this._component.getPopupDomNode&&Object(h.a)(this._component.getPopupDomNode(),e.relatedTarget)||this.delaySetPopupVisible(!1,this.$props.mouseLeaveDelay)},onFocus:function(e){this.fireEvents("focus",e),this.clearDelayTimer(),this.isFocusToShow()&&(this.focusTime=Date.now(),this.delaySetPopupVisible(!0,this.$props.focusDelay))},onMousedown:function(e){this.fireEvents("mousedown",e),this.preClickTime=Date.now()},onTouchstart:function(e){this.fireEvents("touchstart",e),this.preTouchTime=Date.now()},onBlur:function(e){Object(h.a)(e.target,e.relatedTarget||document.activeElement)||(this.fireEvents("blur",e),this.clearDelayTimer(),this.isBlurToHide()&&this.delaySetPopupVisible(!1,this.$props.blurDelay))},onContextmenu:function(e){e.preventDefault(),this.fireEvents("contextmenu",e),this.setPopupVisible(!0,e)},onContextmenuClose:function(){this.isContextmenuToShow()&&this.close()},onClick:function(e){if(this.fireEvents("click",e),this.focusTime){var t=void 0;if(this.preClickTime&&this.preTouchTime?t=Math.min(this.preClickTime,this.preTouchTime):this.preClickTime?t=this.preClickTime:this.preTouchTime&&(t=this.preTouchTime),Math.abs(t-this.focusTime)<20)return;this.focusTime=0}this.preClickTime=0,this.preTouchTime=0,this.isClickToShow()&&(this.isClickToHide()||this.isBlurToHide())&&e&&e.preventDefault&&e.preventDefault(),e&&e.domEvent&&e.domEvent.preventDefault();var n=!this.$data.sPopupVisible;(this.isClickToHide()&&!n||n&&this.isClickToShow())&&this.setPopupVisible(!this.$data.sPopupVisible,e)},onPopupMouseDown:function(){var e=this,t=this.vcTriggerContext,n=void 0===t?{}:t;this.hasPopupMouseDown=!0,clearTimeout(this.mouseDownTimeout),this.mouseDownTimeout=setTimeout((function(){e.hasPopupMouseDown=!1}),0),n.onPopupMouseDown&&n.onPopupMouseDown.apply(n,arguments)},onDocumentClick:function(e){if(!this.$props.mask||this.$props.maskClosable){var t=e.target,n=this.$el;Object(h.a)(n,t)||this.hasPopupMouseDown||this.close()}},getPopupDomNode:function(){return this._component&&this._component.getPopupDomNode?this._component.getPopupDomNode():null},getRootDomNode:function(){return this.$el},handleGetPopupClassFromAlign:function(e){var t=[],n=this.$props,i=n.popupPlacement,r=n.builtinPlacements,a=n.prefixCls,o=n.alignPoint,s=n.getPopupClassNameFromAlign;return i&&r&&t.push(function(e,t,n,i){var r=n.points;for(var a in e)if(e.hasOwnProperty(a)&&_e(e[a].points,r,i))return t+"-placement-"+a;return""}(r,a,e,o)),s&&t.push(s(e)),t.join(" ")},getPopupAlign:function(){var e=this.$props,t=e.popupPlacement,n=e.popupAlign,i=e.builtinPlacements;return t&&i?function(e,t,n){var i=e[t]||{};return a()({},i,n)}(i,t,n):n},savePopup:function(e){this._component=e,this.savePopupRef(e)},getComponent:function(){var e=this.$createElement,t={};this.isMouseEnterToShow()&&(t.mouseenter=this.onPopupMouseenter),this.isMouseLeaveToHide()&&(t.mouseleave=this.onPopupMouseleave),t.mousedown=this.onPopupMouseDown,t.touchstart=this.onPopupMouseDown;var n=this.handleGetPopupClassFromAlign,i=this.getRootDomNode,r=this.getContainer,o=this.$props,s=o.prefixCls,c=o.destroyPopupOnHide,l=o.popupClassName,u=o.action,h=o.popupAnimation,f=o.popupTransitionName,p=o.popupStyle,v=o.mask,m=o.maskAnimation,g=o.maskTransitionName,b=o.zIndex,y=o.stretch,C=o.alignPoint,x=this.$data,k=x.sPopupVisible,z=x.point,w={props:{prefixCls:s,destroyPopupOnHide:c,visible:k,point:C&&z,action:u,align:this.getPopupAlign(),animation:h,getClassNameFromAlign:n,stretch:y,getRootDomNode:i,mask:v,zIndex:b,transitionName:f,maskAnimation:m,maskTransitionName:g,getContainer:r,popupClassName:l,popupStyle:p},on:a()({align:Object(d.k)(this).popupAlign||Le},t),directives:[{name:"ant-ref",value:this.savePopup}]};return e(He,w,[Object(d.g)(this,"popup")])},getContainer:function(){var e=this.$props,t=this.dialogContext,n=document.createElement("div");return n.style.position="absolute",n.style.top="0",n.style.left="0",n.style.width="100%",(e.getPopupContainer?e.getPopupContainer(this.$el,t):e.getDocument().body).appendChild(n),this.popupContainer=n,n},setPopupVisible:function(e,t){var n=this.alignPoint,i=this.sPopupVisible;if(this.clearDelayTimer(),i!==e){Object(d.s)(this,"popupVisible")||this.setState({sPopupVisible:e,prevPopupVisible:i});var r=Object(d.k)(this);r.popupVisibleChange&&r.popupVisibleChange(e)}n&&t&&this.setPoint(t)},setPoint:function(e){this.$props.alignPoint&&e&&this.setState({point:{pageX:e.pageX,pageY:e.pageY}})},delaySetPopupVisible:function(e,t,n){var i=this,r=1e3*t;if(this.clearDelayTimer(),r){var a=n?{pageX:n.pageX,pageY:n.pageY}:null;this.delayTimer=Object(f.b)((function(){i.setPopupVisible(e,a),i.clearDelayTimer()}),r)}else this.setPopupVisible(e,n)},clearDelayTimer:function(){this.delayTimer&&(Object(f.a)(this.delayTimer),this.delayTimer=null)},clearOutsideHandler:function(){this.clickOutsideHandler&&(this.clickOutsideHandler.remove(),this.clickOutsideHandler=null),this.contextmenuOutsideHandler1&&(this.contextmenuOutsideHandler1.remove(),this.contextmenuOutsideHandler1=null),this.contextmenuOutsideHandler2&&(this.contextmenuOutsideHandler2.remove(),this.contextmenuOutsideHandler2=null),this.touchOutsideHandler&&(this.touchOutsideHandler.remove(),this.touchOutsideHandler=null)},createTwoChains:function(e){var t=function(){},n=Object(d.k)(this);return this.childOriginEvents[e]&&n[e]?this["fire"+e]:t=this.childOriginEvents[e]||n[e]||t},isClickToShow:function(){var e=this.$props,t=e.action,n=e.showAction;return-1!==t.indexOf("click")||-1!==n.indexOf("click")},isContextmenuToShow:function(){var e=this.$props,t=e.action,n=e.showAction;return-1!==t.indexOf("contextmenu")||-1!==n.indexOf("contextmenu")},isClickToHide:function(){var e=this.$props,t=e.action,n=e.hideAction;return-1!==t.indexOf("click")||-1!==n.indexOf("click")},isMouseEnterToShow:function(){var e=this.$props,t=e.action,n=e.showAction;return-1!==t.indexOf("hover")||-1!==n.indexOf("mouseenter")},isMouseLeaveToHide:function(){var e=this.$props,t=e.action,n=e.hideAction;return-1!==t.indexOf("hover")||-1!==n.indexOf("mouseleave")},isFocusToShow:function(){var e=this.$props,t=e.action,n=e.showAction;return-1!==t.indexOf("focus")||-1!==n.indexOf("focus")},isBlurToHide:function(){var e=this.$props,t=e.action,n=e.hideAction;return-1!==t.indexOf("focus")||-1!==n.indexOf("blur")},forcePopupAlign:function(){this.$data.sPopupVisible&&this._component&&this._component.$refs.alignInstance&&this._component.$refs.alignInstance.forceAlign()},fireEvents:function(e,t){this.childOriginEvents[e]&&this.childOriginEvents[e](t),this.__emit(e,t)},close:function(){this.setPopupVisible(!1)}},render:function(){var e=this,t=arguments[0],n=this.sPopupVisible,i=Object(d.c)(this.$slots.default),r=this.$props,a=r.forceRender,o=r.alignPoint;i.length>1&&Object(v.a)(!1,"Trigger $slots.default.length > 1, just support only one default",!0);var s=i[0];this.childOriginEvents=Object(d.h)(s);var c={props:{},nativeOn:{},key:"trigger"};return this.isContextmenuToShow()?c.nativeOn.contextmenu=this.onContextmenu:c.nativeOn.contextmenu=this.createTwoChains("contextmenu"),this.isClickToHide()||this.isClickToShow()?(c.nativeOn.click=this.onClick,c.nativeOn.mousedown=this.onMousedown,c.nativeOn.touchstart=this.onTouchstart):(c.nativeOn.click=this.createTwoChains("click"),c.nativeOn.mousedown=this.createTwoChains("mousedown"),c.nativeOn.touchstart=this.createTwoChains("onTouchstart")),this.isMouseEnterToShow()?(c.nativeOn.mouseenter=this.onMouseenter,o&&(c.nativeOn.mousemove=this.onMouseMove)):c.nativeOn.mouseenter=this.createTwoChains("mouseenter"),this.isMouseLeaveToHide()?c.nativeOn.mouseleave=this.onMouseleave:c.nativeOn.mouseleave=this.createTwoChains("mouseleave"),this.isFocusToShow()||this.isBlurToHide()?(c.nativeOn.focus=this.onFocus,c.nativeOn.blur=this.onBlur):(c.nativeOn.focus=this.createTwoChains("focus"),c.nativeOn.blur=function(t){!t||t.relatedTarget&&Object(h.a)(t.target,t.relatedTarget)||e.createTwoChains("blur")(t)}),this.trigger=Object(Ce.a)(s,c),t(Fe,{attrs:{parent:this,visible:n,autoMount:!1,forceRender:a,getComponent:this.getComponent,getContainer:this.getContainer,children:function(t){var n=t.renderComponent;return e.renderComponent=n,e.trigger}}})}};t.a=Ae},function(e,t,n){var i=n(34),r=n(349),a=n(198),o=Math.max,s=Math.min;e.exports=function(e,t,n){var c,l,u,h,d,f,p=0,v=!1,m=!1,g=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function b(t){var n=c,i=l;return c=l=void 0,p=t,h=e.apply(i,n)}function y(e){return p=e,d=setTimeout(x,t),v?b(e):h}function C(e){var n=e-f;return void 0===f||n>=t||n<0||m&&e-p>=u}function x(){var e=r();if(C(e))return k(e);d=setTimeout(x,function(e){var n=t-(e-f);return m?s(n,u-(e-p)):n}(e))}function k(e){return d=void 0,g&&c?b(e):(c=l=void 0,h)}function z(){var e=r(),n=C(e);if(c=arguments,l=this,f=e,n){if(void 0===d)return y(f);if(m)return clearTimeout(d),d=setTimeout(x,t),b(f)}return void 0===d&&(d=setTimeout(x,t)),h}return t=a(t)||0,i(n)&&(v=!!n.leading,u=(m="maxWait"in n)?o(a(n.maxWait)||0,t):u,g="trailing"in n?!!n.trailing:g),z.cancel=function(){void 0!==d&&clearTimeout(d),p=0,c=f=l=d=void 0},z.flush=function(){return void 0===d?h:k(r())},z}},function(e,t,n){"use strict";var i=n(3),r=n.n(i),a=n(2),o=n.n(a),s=n(9),c=n(12),l=n.n(c),u=n(0),h=n(29),d={adjustX:1,adjustY:1},f=[0,0],p={left:{points:["cr","cl"],overflow:d,offset:[-4,0],targetOffset:f},right:{points:["cl","cr"],overflow:d,offset:[4,0],targetOffset:f},top:{points:["bc","tc"],overflow:d,offset:[0,-4],targetOffset:f},bottom:{points:["tc","bc"],overflow:d,offset:[0,4],targetOffset:f},topLeft:{points:["bl","tl"],overflow:d,offset:[0,-4],targetOffset:f},leftTop:{points:["tr","tl"],overflow:d,offset:[-4,0],targetOffset:f},topRight:{points:["br","tr"],overflow:d,offset:[0,-4],targetOffset:f},rightTop:{points:["tl","tr"],overflow:d,offset:[4,0],targetOffset:f},bottomRight:{points:["tr","br"],overflow:d,offset:[0,4],targetOffset:f},rightBottom:{points:["bl","br"],overflow:d,offset:[4,0],targetOffset:f},bottomLeft:{points:["tl","bl"],overflow:d,offset:[0,4],targetOffset:f},leftBottom:{points:["br","bl"],overflow:d,offset:[-4,0],targetOffset:f}},v={props:{prefixCls:u.a.string,overlay:u.a.any,trigger:u.a.any},updated:function(){var e=this.trigger;e&&e.forcePopupAlign()},render:function(){var e=arguments[0],t=this.overlay,n=this.prefixCls;return e("div",{class:n+"-inner",attrs:{role:"tooltip"}},["function"==typeof t?t():t])}},m=n(1);function g(){}var b={props:{trigger:u.a.any.def(["hover"]),defaultVisible:u.a.bool,visible:u.a.bool,placement:u.a.string.def("right"),transitionName:u.a.oneOfType([u.a.string,u.a.object]),animation:u.a.any,afterVisibleChange:u.a.func.def((function(){})),overlay:u.a.any,overlayStyle:u.a.object,overlayClassName:u.a.string,prefixCls:u.a.string.def("rc-tooltip"),mouseEnterDelay:u.a.number.def(0),mouseLeaveDelay:u.a.number.def(.1),getTooltipContainer:u.a.func,destroyTooltipOnHide:u.a.bool.def(!1),align:u.a.object.def((function(){return{}})),arrowContent:u.a.any.def(null),tipId:u.a.string,builtinPlacements:u.a.object},methods:{getPopupElement:function(){var e=this.$createElement,t=this.$props,n=t.prefixCls,i=t.tipId;return[e("div",{class:n+"-arrow",key:"arrow"},[Object(m.g)(this,"arrowContent")]),e(v,{key:"content",attrs:{trigger:this.$refs.trigger,prefixCls:n,id:i,overlay:Object(m.g)(this,"overlay")}})]},getPopupDomNode:function(){return this.$refs.trigger.getPopupDomNode()}},render:function(e){var t=Object(m.l)(this),n=t.overlayClassName,i=t.trigger,r=t.mouseEnterDelay,a=t.mouseLeaveDelay,s=t.overlayStyle,c=t.prefixCls,u=t.afterVisibleChange,d=t.transitionName,f=t.animation,v=t.placement,b=t.align,y=t.destroyTooltipOnHide,C=t.defaultVisible,x=t.getTooltipContainer,k=l()(t,["overlayClassName","trigger","mouseEnterDelay","mouseLeaveDelay","overlayStyle","prefixCls","afterVisibleChange","transitionName","animation","placement","align","destroyTooltipOnHide","defaultVisible","getTooltipContainer"]),z=o()({},k);Object(m.s)(this,"visible")&&(z.popupVisible=this.$props.visible);var w=Object(m.k)(this),S={props:o()({popupClassName:n,prefixCls:c,action:i,builtinPlacements:p,popupPlacement:v,popupAlign:b,getPopupContainer:x,afterPopupVisibleChange:u,popupTransitionName:d,popupAnimation:f,defaultPopupVisible:C,destroyPopupOnHide:y,mouseLeaveDelay:a,popupStyle:s,mouseEnterDelay:r},z),on:o()({},w,{popupVisibleChange:w.visibleChange||g,popupAlign:w.popupAlign||g}),ref:"trigger"};return e(h.a,S,[e("template",{slot:"popup"},[this.getPopupElement(e)]),this.$slots.default])}},y={adjustX:1,adjustY:1},C={adjustX:0,adjustY:0},x=[0,0];function k(e){return"boolean"==typeof e?e?y:C:o()({},C,e)}var z=n(7),w=n(55),S=Object(w.a)(),O={name:"ATooltip",model:{prop:"visible",event:"visibleChange"},props:o()({},S,{title:u.a.any}),inject:{configProvider:{default:function(){return z.a}}},data:function(){return{sVisible:!!this.$props.visible||!!this.$props.defaultVisible}},watch:{visible:function(e){this.sVisible=e}},methods:{onVisibleChange:function(e){Object(m.s)(this,"visible")||(this.sVisible=!this.isNoTitle()&&e),this.isNoTitle()||this.$emit("visibleChange",e)},getPopupDomNode:function(){return this.$refs.tooltip.getPopupDomNode()},getPlacements:function(){var e=this.$props,t=e.builtinPlacements,n=e.arrowPointAtCenter,i=e.autoAdjustOverflow;return t||function(e){var t=e.arrowWidth,n=void 0===t?5:t,i=e.horizontalArrowShift,r=void 0===i?16:i,a=e.verticalArrowShift,s=void 0===a?12:a,c=e.autoAdjustOverflow,l=void 0===c||c,u={left:{points:["cr","cl"],offset:[-4,0]},right:{points:["cl","cr"],offset:[4,0]},top:{points:["bc","tc"],offset:[0,-4]},bottom:{points:["tc","bc"],offset:[0,4]},topLeft:{points:["bl","tc"],offset:[-(r+n),-4]},leftTop:{points:["tr","cl"],offset:[-4,-(s+n)]},topRight:{points:["br","tc"],offset:[r+n,-4]},rightTop:{points:["tl","cr"],offset:[4,-(s+n)]},bottomRight:{points:["tr","bc"],offset:[r+n,4]},rightBottom:{points:["bl","cr"],offset:[4,s+n]},bottomLeft:{points:["tl","bc"],offset:[-(r+n),4]},leftBottom:{points:["br","cl"],offset:[-4,s+n]}};return Object.keys(u).forEach((function(t){u[t]=e.arrowPointAtCenter?o()({},u[t],{overflow:k(l),targetOffset:x}):o()({},p[t],{overflow:k(l)}),u[t].ignoreShake=!0})),u}({arrowPointAtCenter:n,verticalArrowShift:8,autoAdjustOverflow:i})},getDisabledCompatibleChildren:function(e){var t=this.$createElement,n=e.componentOptions&&e.componentOptions.Ctor.options||{};if((!0===n.__ANT_BUTTON||!0===n.__ANT_SWITCH||!0===n.__ANT_CHECKBOX)&&(e.componentOptions.propsData.disabled||""===e.componentOptions.propsData.disabled)||"button"===e.tag&&e.data&&e.data.attrs&&void 0!==e.data.attrs.disabled){var i=function(e,t){var n={},i=o()({},e);return t.forEach((function(t){e&&t in e&&(n[t]=e[t],delete i[t])})),{picked:n,omitted:i}}(Object(m.q)(e),["position","left","right","top","bottom","float","display","zIndex"]),r=i.picked,a=i.omitted,c=o()({display:"inline-block"},r,{cursor:"not-allowed",width:e.componentOptions.propsData.block?"100%":null}),l=o()({},a,{pointerEvents:"none"});return t("span",{style:c,class:Object(m.f)(e)},[Object(s.a)(e,{style:l,class:null})])}return e},isNoTitle:function(){var e=Object(m.g)(this,"title");return!e&&0!==e},getOverlay:function(){var e=Object(m.g)(this,"title");return 0===e?e:e||""},onPopupAlign:function(e,t){var n=this.getPlacements(),i=Object.keys(n).filter((function(e){return n[e].points[0]===t.points[0]&&n[e].points[1]===t.points[1]}))[0];if(i){var r=e.getBoundingClientRect(),a={top:"50%",left:"50%"};i.indexOf("top")>=0||i.indexOf("Bottom")>=0?a.top=r.height-t.offset[1]+"px":(i.indexOf("Top")>=0||i.indexOf("bottom")>=0)&&(a.top=-t.offset[1]+"px"),i.indexOf("left")>=0||i.indexOf("Right")>=0?a.left=r.width-t.offset[0]+"px":(i.indexOf("right")>=0||i.indexOf("Left")>=0)&&(a.left=-t.offset[0]+"px"),e.style.transformOrigin=a.left+" "+a.top}}},render:function(){var e=arguments[0],t=this.$props,n=this.$data,i=this.$slots,a=t.prefixCls,c=t.openClassName,l=t.getPopupContainer,u=this.configProvider.getPopupContainer,h=this.configProvider.getPrefixCls,d=h("tooltip",a),f=(i.default||[]).filter((function(e){return e.tag||""!==e.text.trim()}));f=1===f.length?f[0]:f;var p=n.sVisible;if(!Object(m.s)(this,"visible")&&this.isNoTitle()&&(p=!1),!f)return null;var v=this.getDisabledCompatibleChildren(Object(m.w)(f)?f:e("span",[f])),g=r()({},c||d+"-open",!0),y={props:o()({},t,{prefixCls:d,getTooltipContainer:l||u,builtinPlacements:this.getPlacements(),overlay:this.getOverlay(),visible:p}),ref:"tooltip",on:o()({},Object(m.k)(this),{visibleChange:this.onVisibleChange,popupAlign:this.onPopupAlign})};return e(b,y,[p?Object(s.a)(v,{class:g}):v])}},M=n(10);O.install=function(e){e.use(M.a),e.component(O.name,O)};t.a=O},function(e,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"b",(function(){return o}));var i=["moz","ms","webkit"];var r=function(){if("undefined"==typeof window)return function(){};if(window.requestAnimationFrame)return window.requestAnimationFrame.bind(window);var e,t=i.filter((function(e){return e+"RequestAnimationFrame"in window}))[0];return t?window[t+"RequestAnimationFrame"]:(e=0,function(t){var n=(new Date).getTime(),i=Math.max(0,16-(n-e)),r=window.setTimeout((function(){t(n+i)}),i);return e=n+i,r})}(),a=function(e){return function(e){if("undefined"==typeof window)return null;if(window.cancelAnimationFrame)return window.cancelAnimationFrame(e);var t=i.filter((function(e){return e+"CancelAnimationFrame"in window||e+"CancelRequestAnimationFrame"in window}))[0];return t?(window[t+"CancelAnimationFrame"]||window[t+"CancelRequestAnimationFrame"]).call(this,e):clearTimeout(e)}(e.id)},o=function(e,t){var n=Date.now();var i={id:r((function a(){Date.now()-n>=t?e.call():i.id=r(a)}))};return i}},function(e,t,n){var i=n(217);e.exports=function(e,t,n){return null==e?e:i(e,t,n)}},function(e,t){e.exports=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}},function(e,t){var n=Array.isArray;e.exports=n},function(e,t,n){var i=n(64),r=n(138),a=n(45),o=Function.prototype,s=Object.prototype,c=o.toString,l=s.hasOwnProperty,u=c.call(Object);e.exports=function(e){if(!a(e)||"[object Object]"!=i(e))return!1;var t=r(e);if(null===t)return!0;var n=l.call(t,"constructor")&&t.constructor;return"function"==typeof n&&n instanceof n&&c.call(n)==u}},function(e,t,n){"use strict";var i=n(85);t.a=i.a},function(e,t,n){"use strict";n.d(t,"a",(function(){return a})),n.d(t,"b",(function(){return o})),n.d(t,"c",(function(){return s})),n.d(t,"d",(function(){return c})),n.d(t,"g",(function(){return l})),n.d(t,"e",(function(){return h})),n.d(t,"f",(function(){return d}));var i=n(2),r=n.n(i);function a(){return!0}function o(e){return r()({},e,{lastModified:e.lastModified,lastModifiedDate:e.lastModifiedDate,name:e.name,size:e.size,type:e.type,uid:e.uid,percent:0,originFileObj:e})}function s(){var e=.1;return function(t){var n=t;return n>=.98||(n+=e,(e-=.01)<.001&&(e=.001)),n}}function c(e,t){var n=void 0!==e.uid?"uid":"name";return t.filter((function(t){return t[n]===e[n]}))[0]}function l(e,t){var n=void 0!==e.uid?"uid":"name",i=t.filter((function(t){return t[n]!==e[n]}));return i.length===t.length?null:i}var u=function(e){return!!e&&0===e.indexOf("image/")},h=function(e){if(u(e.type))return!0;var t=e.thumbUrl||e.url,n=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"",t=e.split("/"),n=t[t.length-1],i=n.split(/#|\?/)[0];return(/\.[^./\\]*$/.exec(i)||[""])[0]}(t);return!(!/^data:image\//.test(t)&&!/(webp|svg|png|gif|jpg|jpeg|jfif|bmp|dpg|ico)$/i.test(n))||!/^data:/.test(t)&&!n};function d(e){return new Promise((function(t){if(u(e.type)){var n=document.createElement("canvas");n.width=200,n.height=200,n.style.cssText="position: fixed; left: 0; top: 0; width: 200px; height: 200px; z-index: 9999; display: none;",document.body.appendChild(n);var i=n.getContext("2d"),r=new Image;r.onload=function(){var e=r.width,a=r.height,o=200,s=200,c=0,l=0;e0},e.prototype.connect_=function(){i&&!this.connected_&&(document.addEventListener("transitionend",this.onTransitionEnd_),window.addEventListener("resize",this.refresh),s?(this.mutationsObserver_=new MutationObserver(this.refresh),this.mutationsObserver_.observe(document,{attributes:!0,childList:!0,characterData:!0,subtree:!0})):(document.addEventListener("DOMSubtreeModified",this.refresh),this.mutationEventsAdded_=!0),this.connected_=!0)},e.prototype.disconnect_=function(){i&&this.connected_&&(document.removeEventListener("transitionend",this.onTransitionEnd_),window.removeEventListener("resize",this.refresh),this.mutationsObserver_&&this.mutationsObserver_.disconnect(),this.mutationEventsAdded_&&document.removeEventListener("DOMSubtreeModified",this.refresh),this.mutationsObserver_=null,this.mutationEventsAdded_=!1,this.connected_=!1)},e.prototype.onTransitionEnd_=function(e){var t=e.propertyName,n=void 0===t?"":t;o.some((function(e){return!!~n.indexOf(e)}))&&this.refresh()},e.getInstance=function(){return this.instance_||(this.instance_=new e),this.instance_},e.instance_=null,e}(),l=function(e,t){for(var n=0,i=Object.keys(t);n0},e}(),x="undefined"!=typeof WeakMap?new WeakMap:new n,k=function e(t){if(!(this instanceof e))throw new TypeError("Cannot call a class as a function.");if(!arguments.length)throw new TypeError("1 argument required, but only 0 present.");var n=c.getInstance(),i=new C(t,n,this);x.set(this,i)};["observe","unobserve","disconnect"].forEach((function(e){k.prototype[e]=function(){var t;return(t=x.get(this))[e].apply(t,arguments)}}));var z=void 0!==r.ResizeObserver?r.ResizeObserver:k;t.a=z}).call(this,n(137))},function(e,t,n){"use strict";t.__esModule=!0,t.default=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},function(e,t,n){"use strict";var i=n(0),r=i.a.oneOf(["hover","focus","click","contextmenu"]);t.a=function(){return{trigger:i.a.oneOfType([r,i.a.arrayOf(r)]).def("hover"),visible:i.a.bool,defaultVisible:i.a.bool,placement:i.a.oneOf(["top","left","right","bottom","topLeft","topRight","bottomLeft","bottomRight","leftTop","leftBottom","rightTop","rightBottom"]).def("top"),transitionName:i.a.string.def("zoom-big-fast"),overlayStyle:i.a.object.def((function(){return{}})),overlayClassName:i.a.string,prefixCls:i.a.string,mouseEnterDelay:i.a.number.def(.1),mouseLeaveDelay:i.a.number.def(.1),getPopupContainer:i.a.func,arrowPointAtCenter:i.a.bool.def(!1),autoAdjustOverflow:i.a.oneOfType([i.a.bool,i.a.object]).def(!0),destroyTooltipOnHide:i.a.bool.def(!1),align:i.a.object.def((function(){return{}})),builtinPlacements:i.a.object}}},function(e,t,n){"use strict";n.d(t,"a",(function(){return s})),n.d(t,"b",(function(){return c}));var i=n(2),r=n.n(i),a=n(85),o=r()({},a.a.Modal);function s(e){o=e?r()({},o,e):r()({},a.a.Modal)}function c(){return o}},function(e,t,n){try{var i=n(182)}catch(e){i=n(182)}var r=/\s+/,a=Object.prototype.toString;function o(e){if(!e||!e.nodeType)throw new Error("A DOM element reference is required");this.el=e,this.list=e.classList}e.exports=function(e){return new o(e)},o.prototype.add=function(e){if(this.list)return this.list.add(e),this;var t=this.array();return~i(t,e)||t.push(e),this.el.className=t.join(" "),this},o.prototype.remove=function(e){if("[object RegExp]"==a.call(e))return this.removeMatching(e);if(this.list)return this.list.remove(e),this;var t=this.array(),n=i(t,e);return~n&&t.splice(n,1),this.el.className=t.join(" "),this},o.prototype.removeMatching=function(e){for(var t=this.array(),n=0;n0&&void 0!==arguments[0]?arguments[0]:{};return Object.keys(e).reduce((function(t,n){var i=e[n];switch(n){case"class":t.className=i,delete t.class;break;default:t[n]=i}return t}),{})}var f=function(){function e(){o()(this,e),this.collection={}}return c()(e,[{key:"clear",value:function(){this.collection={}}},{key:"delete",value:function(e){return delete this.collection[e]}},{key:"get",value:function(e){return this.collection[e]}},{key:"has",value:function(e){return Boolean(this.collection[e])}},{key:"set",value:function(e,t){return this.collection[e]=t,this}},{key:"size",get:function(){return Object.keys(this.collection).length}}]),e}();function p(e,t,n,i){return e(t.tag,i?r()({key:n},i,{attrs:r()({},d(t.attrs),i.attrs)}):{key:n,attrs:r()({},d(t.attrs))},(t.children||[]).map((function(i,r){return p(e,i,n+"-"+t.tag+"-"+r)})))}function v(e){return Object(l.generate)(e)[0]}function m(e,t){switch(t){case"fill":return e+"-fill";case"outline":return e+"-o";case"twotone":return e+"-twotone";default:throw new TypeError("Unknown theme type: "+t+", name: "+e)}}}).call(this,n(101))},function(e,t){var n={}.hasOwnProperty;e.exports=function(e,t){return n.call(e,t)}},function(e,t,n){var i=n(74),r=n(274),a=n(275),o=i?i.toStringTag:void 0;e.exports=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":o&&o in Object(e)?r(e):a(e)}},function(e,t,n){var i=n(306),r=n(309);e.exports=function(e,t){var n=r(e,t);return i(n)?n:void 0}},function(e,t){e.exports=function(e,t){return e===t||e!=e&&t!=t}},function(e,t,n){"use strict";var i=n(2),r=n.n(i),a=n(46),o=n(68),s={lang:r()({placeholder:"Select date",rangePlaceholder:["Start date","End date"]},a.a),timePickerLocale:r()({},o.a)};t.a=s},function(e,t,n){"use strict";t.a={placeholder:"Select time"}},function(e,t,n){e.exports=function(){"use strict";return function(e,t,n){(n=n||{}).childrenKeyName=n.childrenKeyName||"children";var i=e||[],r=[],a=0;do{var o=i.filter((function(e){return t(e,a)}))[0];if(!o)break;r.push(o),i=o[n.childrenKeyName]||[],a+=1}while(i.length>0);return r}}()},function(e,t,n){var i=n(51),r=n(90);e.exports=n(52)?function(e,t,n){return i.f(e,t,r(1,n))}:function(e,t,n){return e[t]=n,e}},function(e,t,n){var i=n(88);e.exports=function(e){if(!i(e))throw TypeError(e+" is not an object!");return e}},function(e,t,n){var i=n(172),r=n(127);e.exports=function(e){return i(r(e))}},function(e,t){e.exports={}},function(e,t,n){var i=n(40).Symbol;e.exports=i},function(e,t,n){var i=n(142),r=n(143);e.exports=function(e,t,n,a){var o=!n;n||(n={});for(var s=-1,c=t.length;++s100?100:e}var b=function(e){var t=e.from,n=void 0===t?"#1890ff":t,i=e.to,r=void 0===i?"#1890ff":i,a=e.direction,o=void 0===a?"to right":a,s=p()(e,["from","to","direction"]);return 0!==Object.keys(s).length?{backgroundImage:"linear-gradient("+o+", "+function(e){var t=[],n=!0,i=!1,r=void 0;try{for(var a,o=Object.entries(e)[Symbol.iterator]();!(n=(a=o.next()).done);n=!0){var s=a.value,c=m()(s,2),l=c[0],u=c[1],h=parseFloat(l.replace(/%/g,""));if(isNaN(h))return{};t.push({key:h,value:u})}}catch(e){i=!0,r=e}finally{try{!n&&o.return&&o.return()}finally{if(i)throw r}}return(t=t.sort((function(e,t){return e.key-t.key}))).map((function(e){var t=e.key;return e.value+" "+t+"%"})).join(", ")}(s)+")"}:{backgroundImage:"linear-gradient("+o+", "+n+", "+r+")"}},y={functional:!0,render:function(e,t){var n=t.props,i=t.children,r=n.prefixCls,a=n.percent,s=n.successPercent,c=n.strokeWidth,l=n.size,u=n.strokeColor,h=n.strokeLinecap,d=void 0;d=u&&"string"!=typeof u?b(u):{background:u};var f=o()({width:g(a)+"%",height:(c||("small"===l?6:8))+"px",background:u,borderRadius:"square"===h?0:"100px"},d),p={width:g(s)+"%",height:(c||("small"===l?6:8))+"px",borderRadius:"square"===h?0:""},v=void 0!==s?e("div",{class:r+"-success-bg",style:p}):null;return e("div",[e("div",{class:r+"-outer"},[e("div",{class:r+"-inner"},[e("div",{class:r+"-bg",style:f}),v])]),i])}},C=n(6),x=n.n(C),k=n(18),z=n.n(k),w=n(25),S=n.n(w);var O=function(e){return{mixins:[e],updated:function(){var e=this,t=Date.now(),n=!1;Object.keys(this.paths).forEach((function(i){var r=e.paths[i];if(r){n=!0;var a=r.style;a.transitionDuration=".3s, .3s, .3s, .06s",e.prevTimeStamp&&t-e.prevTimeStamp<100&&(a.transitionDuration="0s, 0s")}})),n&&(this.prevTimeStamp=Date.now())}}},M=l.a.oneOfType([l.a.number,l.a.string]),T={percent:l.a.oneOfType([M,l.a.arrayOf(M)]),prefixCls:l.a.string,strokeColor:l.a.oneOfType([l.a.string,l.a.arrayOf(l.a.oneOfType([l.a.string,l.a.object])),l.a.object]),strokeLinecap:l.a.oneOf(["butt","round","square"]),strokeWidth:M,trailColor:l.a.string,trailWidth:M},V=o()({},T,{gapPosition:l.a.oneOf(["top","bottom","left","right"]),gapDegree:l.a.oneOfType([l.a.number,l.a.string,l.a.bool])}),P=o()({},{percent:0,prefixCls:"rc-progress",strokeColor:"#2db7f5",strokeLinecap:"round",strokeWidth:1,trailColor:"#D9D9D9",trailWidth:1},{gapPosition:"top"});z.a.use(S.a,{name:"ant-ref"});var j=0;function H(e){return+e.replace("%","")}function _(e){return Array.isArray(e)?e:[e]}function L(e,t,n,i){var r=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0,a=arguments[5],o=50-i/2,s=0,c=-o,l=0,u=-2*o;switch(a){case"left":s=-o,c=0,l=2*o,u=0;break;case"right":s=o,c=0,l=-2*o,u=0;break;case"bottom":c=o,u=2*o}var h="M 50,50 m "+s+","+c+"\n a "+o+","+o+" 0 1 1 "+l+","+-u+"\n a "+o+","+o+" 0 1 1 "+-l+","+u,d=2*Math.PI*o,f={stroke:n,strokeDasharray:t/100*(d-r)+"px "+d+"px",strokeDashoffset:"-"+(r/2+e/100*(d-r))+"px",transition:"stroke-dashoffset .3s ease 0s, stroke-dasharray .3s ease 0s, stroke .3s, stroke-width .06s ease .3s"};return{pathString:h,pathStyle:f}}var F=O({props:Object(u.t)(V,P),created:function(){this.paths={},this.gradientId=j,j+=1},methods:{getStokeList:function(){var e=this,t=this.$createElement,n=this.$props,i=n.prefixCls,r=n.percent,a=n.strokeColor,o=n.strokeWidth,s=n.strokeLinecap,c=n.gapDegree,l=n.gapPosition,u=_(r),h=_(a),d=0;return u.map((function(n,r){var a=h[r]||h[h.length-1],u="[object Object]"===Object.prototype.toString.call(a)?"url(#"+i+"-gradient-"+e.gradientId+")":"",f=L(d,n,a,o,c,l),p=f.pathString,v=f.pathStyle;return d+=n,t("path",{key:r,attrs:{d:p,stroke:u,"stroke-linecap":s,"stroke-width":0===n?0:o,"fill-opacity":"0"},class:i+"-circle-path",style:v,directives:[{name:"ant-ref",value:function(t){e.paths[r]=t}}]})}))}},render:function(){var e=arguments[0],t=this.$props,n=t.prefixCls,i=t.strokeWidth,r=t.trailWidth,a=t.gapDegree,o=t.gapPosition,s=t.trailColor,c=t.strokeLinecap,l=t.strokeColor,u=p()(t,["prefixCls","strokeWidth","trailWidth","gapDegree","gapPosition","trailColor","strokeLinecap","strokeColor"]),h=L(0,100,s,i,a,o),d=h.pathString,f=h.pathStyle;delete u.percent;var v=_(l),m=v.find((function(e){return"[object Object]"===Object.prototype.toString.call(e)})),g={attrs:{d:d,stroke:s,"stroke-linecap":c,"stroke-width":r||i,"fill-opacity":"0"},class:n+"-circle-trail",style:f};return e("svg",x()([{class:n+"-circle",attrs:{viewBox:"0 0 100 100"}},u]),[m&&e("defs",[e("linearGradient",{attrs:{id:n+"-gradient-"+this.gradientId,x1:"100%",y1:"0%",x2:"0%",y2:"0%"}},[Object.keys(m).sort((function(e,t){return H(e)-H(t)})).map((function(t,n){return e("stop",{key:n,attrs:{offset:t,"stop-color":m[t]}})}))])]),e("path",g),this.getStokeList().reverse()])}}),E={normal:"#108ee9",exception:"#ff5500",success:"#87d068"};function A(e){var t=e.percent,n=e.successPercent,i=g(t);if(!n)return i;var r=g(n);return[n,g(i-r)]}var D={functional:!0,render:function(e,t){var n,i,a,o,s,c=t.props,l=t.children,u=c.prefixCls,h=c.width,d=c.strokeWidth,f=c.trailColor,p=c.strokeLinecap,v=c.gapPosition,m=c.gapDegree,g=c.type,b=h||120,y={width:"number"==typeof b?b+"px":b,height:"number"==typeof b?b+"px":b,fontSize:.15*b+6},C=d||6,x=v||"dashboard"===g&&"bottom"||"top",k=m||"dashboard"===g&&75,z=(a=(i=c).progressStatus,o=i.successPercent,s=i.strokeColor||E[a],o?[E.success,s]:s),w="[object Object]"===Object.prototype.toString.call(z);return e("div",{class:(n={},r()(n,u+"-inner",!0),r()(n,u+"-circle-gradient",w),n),style:y},[e(F,{attrs:{percent:A(c),strokeWidth:C,trailWidth:C,strokeColor:z,strokeLinecap:p,trailColor:f,prefixCls:u,gapDegree:k,gapPosition:x}}),l])}},$=["normal","exception","active","success"],I=l.a.oneOf(["line","circle","dashboard"]),R=l.a.oneOf(["default","small"]),N={prefixCls:l.a.string,type:I,percent:l.a.number,successPercent:l.a.number,format:l.a.func,status:l.a.oneOf($),showInfo:l.a.bool,strokeWidth:l.a.number,strokeLinecap:l.a.oneOf(["butt","round","square"]),strokeColor:l.a.oneOfType([l.a.string,l.a.object]),trailColor:l.a.string,width:l.a.number,gapDegree:l.a.number,gapPosition:l.a.oneOf(["top","bottom","left","right"]),size:R},K={name:"AProgress",props:Object(u.t)(N,{type:"line",percent:0,showInfo:!0,trailColor:"#f3f3f3",size:"default",gapDegree:0,strokeLinecap:"round"}),inject:{configProvider:{default:function(){return h.a}}},methods:{getPercentNumber:function(){var e=this.$props,t=e.successPercent,n=e.percent,i=void 0===n?0:n;return parseInt(void 0!==t?t.toString():i.toString(),10)},getProgressStatus:function(){var e=this.$props.status;return $.indexOf(e)<0&&this.getPercentNumber()>=100?"success":e||"normal"},renderProcessInfo:function(e,t){var n=this.$createElement,i=this.$props,r=i.showInfo,a=i.format,o=i.type,s=i.percent,c=i.successPercent;if(!r)return null;var l=void 0,u=a||this.$scopedSlots.format||function(e){return e+"%"},h="circle"===o||"dashboard"===o?"":"-circle";return a||this.$scopedSlots.format||"exception"!==t&&"success"!==t?l=u(g(s),g(c)):"exception"===t?l=n(d.a,{attrs:{type:"close"+h,theme:"line"===o?"filled":"outlined"}}):"success"===t&&(l=n(d.a,{attrs:{type:"check"+h,theme:"line"===o?"filled":"outlined"}})),n("span",{class:e+"-text",attrs:{title:"string"==typeof l?l:void 0}},[l])}},render:function(){var e,t=arguments[0],n=Object(u.l)(this),i=n.prefixCls,a=n.size,s=n.type,l=n.showInfo,h=this.configProvider.getPrefixCls,d=h("progress",i),f=this.getProgressStatus(),p=this.renderProcessInfo(d,f),v=void 0;if("line"===s){var m={props:o()({},n,{prefixCls:d})};v=t(y,m,[p])}else if("circle"===s||"dashboard"===s){var g={props:o()({},n,{prefixCls:d,progressStatus:f})};v=t(D,g,[p])}var b=c()(d,(e={},r()(e,d+"-"+("dashboard"===s?"circle":s),!0),r()(e,d+"-status-"+f,!0),r()(e,d+"-show-info",l),r()(e,d+"-"+a,a),e)),C={on:Object(u.k)(this),class:b};return t("div",C,[v])}},Y=n(10);K.install=function(e){e.use(Y.a),e.component(K.name,K)};t.a=K},function(e,t,n){"use strict";t.a={items_per_page:"/ page",jump_to:"Go to",jump_to_confirm:"confirm",page:"",prev_page:"Previous Page",next_page:"Next Page",prev_5:"Previous 5 Pages",next_5:"Next 5 Pages",prev_3:"Previous 3 Pages",next_3:"Next 3 Pages"}},function(e,t,n){"use strict";var i=n(67);t.a=i.a},function(e,t,n){var i=n(171),r=n(131);e.exports=Object.keys||function(e){return i(e,r)}},function(e,t){e.exports=!0},function(e,t){var n=0,i=Math.random();e.exports=function(e){return"Symbol(".concat(void 0===e?"":e,")_",(++n+i).toString(36))}},function(e,t){t.f={}.propertyIsEnumerable},function(e,t,n){var i=n(127);e.exports=function(e){return Object(i(e))}},function(e,t,n){"use strict";var i=n(255)(!0);n(174)(String,"String",(function(e){this._t=String(e),this._i=0}),(function(){var e,t=this._t,n=this._i;return n>=t.length?{value:void 0,done:!0}:(e=i(t,n),this._i+=e.length,{value:e,done:!1})}))},function(e,t){var n,i,r=e.exports={};function a(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function s(e){if(n===setTimeout)return setTimeout(e,0);if((n===a||!n)&&setTimeout)return n=setTimeout,setTimeout(e,0);try{return n(e,0)}catch(t){try{return n.call(null,e,0)}catch(t){return n.call(this,e,0)}}}!function(){try{n="function"==typeof setTimeout?setTimeout:a}catch(e){n=a}try{i="function"==typeof clearTimeout?clearTimeout:o}catch(e){i=o}}();var c,l=[],u=!1,h=-1;function d(){u&&c&&(u=!1,c.length?l=c.concat(l):h=-1,l.length&&f())}function f(){if(!u){var e=s(d);u=!0;for(var t=l.length;t;){for(c=l,l=[];++h1)for(var n=1;n-1&&e%1==0&&e0;var a=function(e,t){for(var n=Object.create(null),i=e.split(","),r=0;r1),t})),s(e,u(e),n),l&&(n=r(n,7,c));for(var h=t.length;h--;)a(n,t[h]);return n}));e.exports=h},function(e,t,n){var i=n(368),r=n(110),a=n(111),o=a&&a.isRegExp,s=o?r(o):i;e.exports=s},function(e,t,n){"use strict";(function(e){function n(){return(n=Object.assign||function(e){for(var t=1;t=a)return e;switch(e){case"%s":return String(t[i++]);case"%d":return Number(t[i++]);case"%j":try{return JSON.stringify(t[i++])}catch(e){return"[Circular]"}break;default:return e}}));return o}return r}function d(e,t){return null==e||(!("array"!==t||!Array.isArray(e)||e.length)||!(!function(e){return"string"===e||"url"===e||"hex"===e||"email"===e||"date"===e||"pattern"===e}(t)||"string"!=typeof e||e))}function f(e,t,n){var i=0,r=e.length;!function a(o){if(o&&o.length)n(o);else{var s=i;i+=1,s()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,url:new RegExp("^(?!mailto:)(?:(?:http|https|ftp)://|//)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-*)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$","i"),hex:/^#?([a-f0-9]{6}|[a-f0-9]{3})$/i},C={integer:function(e){return C.number(e)&&parseInt(e,10)===e},float:function(e){return C.number(e)&&!C.integer(e)},array:function(e){return Array.isArray(e)},regexp:function(e){if(e instanceof RegExp)return!0;try{return!!new RegExp(e)}catch(e){return!1}},date:function(e){return"function"==typeof e.getTime&&"function"==typeof e.getMonth&&"function"==typeof e.getYear&&!isNaN(e.getTime())},number:function(e){return!isNaN(e)&&"number"==typeof e},object:function(e){return"object"==typeof e&&!C.array(e)},method:function(e){return"function"==typeof e},email:function(e){return"string"==typeof e&&!!e.match(y.email)&&e.length<255},url:function(e){return"string"==typeof e&&!!e.match(y.url)},hex:function(e){return"string"==typeof e&&!!e.match(y.hex)}};var x={required:b,whitespace:function(e,t,n,i,r){(/^\s+$/.test(t)||""===t)&&i.push(h(r.messages.whitespace,e.fullField))},type:function(e,t,n,i,r){if(e.required&&void 0===t)b(e,t,n,i,r);else{var a=e.type;["integer","float","array","regexp","object","method","email","number","date","url","hex"].indexOf(a)>-1?C[a](t)||i.push(h(r.messages.types[a],e.fullField,e.type)):a&&typeof t!==e.type&&i.push(h(r.messages.types[a],e.fullField,e.type))}},range:function(e,t,n,i,r){var a="number"==typeof e.len,o="number"==typeof e.min,s="number"==typeof e.max,c=t,l=null,u="number"==typeof t,d="string"==typeof t,f=Array.isArray(t);if(u?l="number":d?l="string":f&&(l="array"),!l)return!1;f&&(c=t.length),d&&(c=t.replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g,"_").length),a?c!==e.len&&i.push(h(r.messages[l].len,e.fullField,e.len)):o&&!s&&ce.max?i.push(h(r.messages[l].max,e.fullField,e.max)):o&&s&&(ce.max)&&i.push(h(r.messages[l].range,e.fullField,e.min,e.max))},enum:function(e,t,n,i,r){e.enum=Array.isArray(e.enum)?e.enum:[],-1===e.enum.indexOf(t)&&i.push(h(r.messages.enum,e.fullField,e.enum.join(", ")))},pattern:function(e,t,n,i,r){if(e.pattern)if(e.pattern instanceof RegExp)e.pattern.lastIndex=0,e.pattern.test(t)||i.push(h(r.messages.pattern.mismatch,e.fullField,t,e.pattern));else if("string"==typeof e.pattern){new RegExp(e.pattern).test(t)||i.push(h(r.messages.pattern.mismatch,e.fullField,t,e.pattern))}}};function k(e,t,n,i,r){var a=e.type,o=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t,a)&&!e.required)return n();x.required(e,t,i,o,r,a),d(t,a)||x.type(e,t,i,o,r)}n(o)}var z={string:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t,"string")&&!e.required)return n();x.required(e,t,i,a,r,"string"),d(t,"string")||(x.type(e,t,i,a,r),x.range(e,t,i,a,r),x.pattern(e,t,i,a,r),!0===e.whitespace&&x.whitespace(e,t,i,a,r))}n(a)},method:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t)&&!e.required)return n();x.required(e,t,i,a,r),void 0!==t&&x.type(e,t,i,a,r)}n(a)},number:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(""===t&&(t=void 0),d(t)&&!e.required)return n();x.required(e,t,i,a,r),void 0!==t&&(x.type(e,t,i,a,r),x.range(e,t,i,a,r))}n(a)},boolean:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t)&&!e.required)return n();x.required(e,t,i,a,r),void 0!==t&&x.type(e,t,i,a,r)}n(a)},regexp:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t)&&!e.required)return n();x.required(e,t,i,a,r),d(t)||x.type(e,t,i,a,r)}n(a)},integer:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t)&&!e.required)return n();x.required(e,t,i,a,r),void 0!==t&&(x.type(e,t,i,a,r),x.range(e,t,i,a,r))}n(a)},float:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t)&&!e.required)return n();x.required(e,t,i,a,r),void 0!==t&&(x.type(e,t,i,a,r),x.range(e,t,i,a,r))}n(a)},array:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t,"array")&&!e.required)return n();x.required(e,t,i,a,r,"array"),d(t,"array")||(x.type(e,t,i,a,r),x.range(e,t,i,a,r))}n(a)},object:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t)&&!e.required)return n();x.required(e,t,i,a,r),void 0!==t&&x.type(e,t,i,a,r)}n(a)},enum:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t)&&!e.required)return n();x.required(e,t,i,a,r),void 0!==t&&x.enum(e,t,i,a,r)}n(a)},pattern:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t,"string")&&!e.required)return n();x.required(e,t,i,a,r),d(t,"string")||x.pattern(e,t,i,a,r)}n(a)},date:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t,"date")&&!e.required)return n();var o;if(x.required(e,t,i,a,r),!d(t,"date"))o=t instanceof Date?t:new Date(t),x.type(e,o,i,a,r),o&&x.range(e,o.getTime(),i,a,r)}n(a)},url:k,hex:k,email:k,required:function(e,t,n,i,r){var a=[],o=Array.isArray(t)?"array":typeof t;x.required(e,t,i,a,r,o),n(a)},any:function(e,t,n,i,r){var a=[];if(e.required||!e.required&&i.hasOwnProperty(e.field)){if(d(t)&&!e.required)return n();x.required(e,t,i,a,r)}n(a)}};function w(){return{default:"Validation error on field %s",required:"%s is required",enum:"%s must be one of %s",whitespace:"%s cannot be empty",date:{format:"%s date %s is invalid for format %s",parse:"%s date could not be parsed, %s is invalid ",invalid:"%s date %s is invalid"},types:{string:"%s is not a %s",method:"%s is not a %s (function)",array:"%s is not an %s",object:"%s is not an %s",number:"%s is not a %s",date:"%s is not a %s",boolean:"%s is not a %s",integer:"%s is not an %s",float:"%s is not a %s",regexp:"%s is not a valid %s",email:"%s is not a valid %s",url:"%s is not a valid %s",hex:"%s is not a valid %s"},string:{len:"%s must be exactly %s characters",min:"%s must be at least %s characters",max:"%s cannot be longer than %s characters",range:"%s must be between %s and %s characters"},number:{len:"%s must equal %s",min:"%s cannot be less than %s",max:"%s cannot be greater than %s",range:"%s must be between %s and %s"},array:{len:"%s must be exactly %s in length",min:"%s cannot be less than %s in length",max:"%s cannot be greater than %s in length",range:"%s must be between %s and %s in length"},pattern:{mismatch:"%s value %s does not match pattern %s"},clone:function(){var e=JSON.parse(JSON.stringify(this));return e.clone=this.clone,e}}}var S=w();function O(e){this.rules=null,this._messages=S,this.define(e)}O.prototype={messages:function(e){return e&&(this._messages=g(w(),e)),this._messages},define:function(e){if(!e)throw new Error("Cannot configure a schema with no rules");if("object"!=typeof e||Array.isArray(e))throw new Error("Rules must be an object");var t,n;for(t in this.rules={},e)e.hasOwnProperty(t)&&(n=e[t],this.rules[t]=Array.isArray(n)?n:[n])},validate:function(e,t,i){var r=this;void 0===t&&(t={}),void 0===i&&(i=function(){});var a,o,s=e,c=t,l=i;if("function"==typeof c&&(l=c,c={}),!this.rules||0===Object.keys(this.rules).length)return l&&l(),Promise.resolve();if(c.messages){var d=this.messages();d===S&&(d=w()),g(d,c.messages),c.messages=d}else c.messages=this.messages();var f={};(c.keys||Object.keys(this.rules)).forEach((function(t){a=r.rules[t],o=s[t],a.forEach((function(i){var a=i;"function"==typeof a.transform&&(s===e&&(s=n({},s)),o=s[t]=a.transform(o)),(a="function"==typeof a?{validator:a}:n({},a)).validator=r.getValidationMethod(a),a.field=t,a.fullField=a.fullField||t,a.type=r.getType(a),a.validator&&(f[t]=f[t]||[],f[t].push({rule:a,value:o,source:s,field:t}))}))}));var p={};return v(f,c,(function(e,t){var i,r=e.rule,a=!("object"!==r.type&&"array"!==r.type||"object"!=typeof r.fields&&"object"!=typeof r.defaultField);function o(e,t){return n(n({},t),{},{fullField:r.fullField+"."+e})}function s(i){void 0===i&&(i=[]);var s=i;if(Array.isArray(s)||(s=[s]),!c.suppressWarning&&s.length&&O.warning("async-validator:",s),s.length&&r.message&&(s=[].concat(r.message)),s=s.map(m(r)),c.first&&s.length)return p[r.field]=1,t(s);if(a){if(r.required&&!e.value)return r.message?s=[].concat(r.message).map(m(r)):c.error&&(s=[c.error(r,h(c.messages.required,r.field))]),t(s);var l={};if(r.defaultField)for(var u in e.value)e.value.hasOwnProperty(u)&&(l[u]=r.defaultField);for(var d in l=n(n({},l),e.rule.fields))if(l.hasOwnProperty(d)){var f=Array.isArray(l[d])?l[d]:[l[d]];l[d]=f.map(o.bind(null,d))}var v=new O(l);v.messages(c.messages),e.rule.options&&(e.rule.options.messages=c.messages,e.rule.options.error=c.error),v.validate(e.value,e.rule.options||c,(function(e){var n=[];s&&s.length&&n.push.apply(n,s),e&&e.length&&n.push.apply(n,e),t(n.length?n:null)}))}else t(s)}a=a&&(r.required||!r.required&&e.value),r.field=e.field,r.asyncValidator?i=r.asyncValidator(r,e.value,s,e.source,c):r.validator&&(!0===(i=r.validator(r,e.value,s,e.source,c))?s():!1===i?s(r.message||r.field+" fails"):i instanceof Array?s(i):i instanceof Error&&s(i.message)),i&&i.then&&i.then((function(){return s()}),(function(e){return s(e)}))}),(function(e){!function(e){var t,n,i,r=[],a={};for(t=0;t0?i:n)(e)}},function(e,t,n){var i=n(130)("keys"),r=n(97);e.exports=function(e){return i[e]||(i[e]=r(e))}},function(e,t,n){var i=n(44),r=n(50),a=r["__core-js_shared__"]||(r["__core-js_shared__"]={});(e.exports=function(e,t){return a[e]||(a[e]=void 0!==t?t:{})})("versions",[]).push({version:i.version,mode:n(96)?"pure":"global",copyright:"© 2019 Denis Pushkarev (zloirock.ru)"})},function(e,t){e.exports="constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf".split(",")},function(e,t){t.f=Object.getOwnPropertySymbols},function(e,t,n){var i=n(51).f,r=n(63),a=n(39)("toStringTag");e.exports=function(e,t,n){e&&!r(e=n?e:e.prototype,a)&&i(e,a,{configurable:!0,value:t})}},function(e,t,n){n(260);for(var i=n(50),r=n(70),a=n(73),o=n(39)("toStringTag"),s="CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,TextTrackList,TouchList".split(","),c=0;c-1&&e%1==0&&e<=9007199254740991}},function(e,t){var n=Object.prototype;e.exports=function(e){var t=e&&e.constructor;return e===("function"==typeof t&&t.prototype||n)}},function(e,t,n){var i=n(334),r=n(189),a=Object.prototype.propertyIsEnumerable,o=Object.getOwnPropertySymbols,s=o?function(e){return null==e?[]:(e=Object(e),i(o(e),(function(t){return a.call(e,t)})))}:r;e.exports=s},function(e,t){e.exports=function(e,t){for(var n=-1,i=t.length,r=e.length;++n0&&(t.percent=t.loaded/t.total*100),e.onProgress(t)});var n=new window.FormData;e.data&&Object.keys(e.data).forEach((function(t){var i=e.data[t];Array.isArray(i)?i.forEach((function(e){n.append(t+"[]",e)})):n.append(t,e.data[t])})),n.append(e.filename,e.file),t.onerror=function(t){e.onError(t)},t.onload=function(){if(t.status<200||t.status>=300)return e.onError(function(e, t){var n="cannot "+e.method+" "+e.action+" "+t.status+"'",i=new Error(n);return i.status=t.status,i.method=e.method,i.url=e.action,i}(e,t),p(t));e.onSuccess(p(t),t)},t.open(e.method,e.action,!0),e.withCredentials&&"withCredentials"in t&&(t.withCredentials=!0);var i=e.headers||{};for(var r in null!==i["X-Requested-With"]&&t.setRequestHeader("X-Requested-With","XMLHttpRequest"),i)i.hasOwnProperty(r)&&null!==i[r]&&t.setRequestHeader(r,i[r]);return t.send(n),{abort:function(){t.abort()}}}var m=+new Date,g=0;function b(){return"vc-upload-"+m+"-"+ ++g}var y=function(e, t){if(e&&t){var n=Array.isArray(t)?t:t.split(","),i=e.name||"",r=e.type||"",a=r.replace(/\/.*$/,"");return n.some((function(e){var t,n,o=e.trim();return"."===o.charAt(0)?(t=i.toLowerCase(),n=o.toLowerCase(),-1!==t.indexOf(n,t.length-n.length)):/\/\*$/.test(o)?a===o.replace(/\/.*$/,""):r===o}))}return!0};var C=function(e, t, n){var i=function e(i, r){r=r||"",i.isFile?i.file((function(e){n(e)&&(i.fullPath&&!e.webkitRelativePath&&(Object.defineProperties(e,{webkitRelativePath:{writable:!0}}),e.webkitRelativePath=i.fullPath.replace(/^\//,""),Object.defineProperties(e,{webkitRelativePath:{writable:!1}})),t([e]))})):i.isDirectory&&function(e, t){var n=e.createReader(),i=[];!function e(){n.readEntries((function(n){var r=Array.prototype.slice.apply(n);i=i.concat(r),!r.length?t(i):e()}))}()}(i,(function(t){t.forEach((function(t){e(t,""+r+i.name+"/")}))}))},r=!0,a=!1,o=void 0;try{for(var s,c=e[Symbol.iterator](); !(r=(s=c.next()).done); r=!0){i(s.value.webkitGetAsEntry())}}catch(e){a=!0,o=e}finally{try{!r&&c.return&&c.return()}finally{if(a)throw o}}},x={componentTag:a.a.string,prefixCls:a.a.string,name:a.a.string,multiple:a.a.bool,directory:a.a.bool,disabled:a.a.bool,accept:a.a.string,data:a.a.oneOfType([a.a.object,a.a.func]),action:a.a.oneOfType([a.a.string,a.a.func]),headers:a.a.object,beforeUpload:a.a.func,customRequest:a.a.func,withCredentials:a.a.bool,openFileDialogOnClick:a.a.bool,transformFile:a.a.func,method:a.a.string},k={inheritAttrs:!1,name:"ajaxUploader",mixins:[s.a],props:x,data:function(){return this.reqs={},{uid:b()}},mounted:function(){this._isMounted=!0},beforeDestroy:function(){this._isMounted=!1,this.abort()},methods:{onChange:function(e){var t=e.target.files;this.uploadFiles(t),this.reset()},onClick:function(){var e=this.$refs.fileInputRef;e&&e.click()},onKeyDown:function(e){"Enter"===e.key&&this.onClick()},onFileDrop:function(e){var t=this,n=this.$props.multiple;if(e.preventDefault(),"dragover"!==e.type)if(this.directory)C(e.dataTransfer.items,this.uploadFiles,(function(e){return y(e,t.accept)}));else{var i=h()(Array.prototype.slice.call(e.dataTransfer.files),(function(e){return y(e,t.accept)})),r=i[0],a=i[1];!1===n&&(r=r.slice(0,1)),this.uploadFiles(r),a.length&&this.$emit("reject",a)}},uploadFiles:function(e){var t=this,n=Array.prototype.slice.call(e);n.map((function(e){return e.uid=b(),e})).forEach((function(e){t.upload(e,n)}))},upload:function(e, t){var n=this;if(!this.beforeUpload)return setTimeout((function(){return n.post(e)}),0);var i=this.beforeUpload(e,t);i&&i.then?i.then((function(t){var i=Object.prototype.toString.call(t);return"[object File]"===i||"[object Blob]"===i?n.post(t):n.post(e)})).catch((function(e){console&&console.log(e)})):!1!==i&&setTimeout((function(){return n.post(e)}),0)},post:function(e){var t=this;if(this._isMounted){var n=this.$props,i=n.data,r=n.transformFile,a=void 0===r?function(e){return e}:r;new Promise((function(n){var i=t.action;if("function"==typeof i)return n(i(e));n(i)})).then((function(r){var o=e.uid,s=t.customRequest||v;Promise.resolve(a(e)).catch((function(e){console.error(e)})).then((function(a){"function"==typeof i&&(i=i(e));var c={action:r,filename:t.name,data:i,file:a,headers:t.headers,withCredentials:t.withCredentials,method:n.method||"post",onProgress:function(n){t.$emit("progress",n,e)},onSuccess:function(n, i){delete t.reqs[o],t.$emit("success",n,e,i)},onError:function(n, i){delete t.reqs[o],t.$emit("error",n,i,e)}};t.reqs[o]=s(c),t.$emit("start",e)}))}))}},reset:function(){this.setState({uid:b()})},abort:function(e){var t=this.reqs;if(e){var n=e;e&&e.uid&&(n=e.uid),t[n]&&t[n].abort&&t[n].abort(),delete t[n]}else Object.keys(t).forEach((function(e){t[e]&&t[e].abort&&t[e].abort(),delete t[e]}))}},render:function(){var e,t=arguments[0],n=this.$props,i=this.$attrs,a=n.componentTag,s=n.prefixCls,c=n.disabled,u=n.multiple,h=n.accept,d=n.directory,p=n.openFileDialogOnClick,v=f()((e={},l()(e,s,!0),l()(e,s+"-disabled",c),e)),m=c?{}:{click:p?this.onClick:function(){},keydown:p?this.onKeyDown:function(){},drop:this.onFileDrop,dragover:this.onFileDrop},g={on:r()({},Object(o.k)(this),m),attrs:{role:"button",tabIndex:c?null:"0"},class:v};return t(a,g,[t("input",{attrs:{id:i.id,type:"file",accept:h,directory:d?"directory":null,webkitdirectory:d?"webkitdirectory":null,multiple:u},ref:"fileInputRef",on:{click:function(e){return e.stopPropagation()},change:this.onChange},key:this.uid,style:{display:"none"}}),this.$slots.default])}},z=n(13),w={position:"absolute",top:0,opacity:0,filter:"alpha(opacity=0)",left:0,zIndex:9999},S={mixins:[s.a],props:{componentTag:a.a.string,disabled:a.a.bool,prefixCls:a.a.string,accept:a.a.string,multiple:a.a.bool,data:a.a.oneOfType([a.a.object,a.a.func]),action:a.a.oneOfType([a.a.string,a.a.func]),name:a.a.string},data:function(){return this.file={},{uploading:!1}},methods:{onLoad:function(){if(this.uploading){var e=this.file,t=void 0;try{var n=this.getIframeDocument(),i=n.getElementsByTagName("script")[0];i&&i.parentNode===n.body&&n.body.removeChild(i),t=n.body.innerHTML,this.$emit("success",t,e)}catch(n){Object(z.a)(!1,"cross domain error for Upload. Maybe server should return document.domain script. see Note from https://github.com/react-component/upload"),t="cross-domain",this.$emit("error",n,null,e)}this.endUpload()}},onChange:function(){var e=this,t=this.getFormInputNode(),n=this.file={uid:b(),name:t.value&&t.value.substring(t.value.lastIndexOf("\\")+1,t.value.length)};this.startUpload();var i=this.$props;if(!i.beforeUpload)return this.post(n);var r=i.beforeUpload(n);r&&r.then?r.then((function(){e.post(n)}),(function(){e.endUpload()})):!1!==r?this.post(n):this.endUpload()},getIframeNode:function(){return this.$refs.iframeRef},getIframeDocument:function(){return this.getIframeNode().contentDocument},getFormNode:function(){return this.getIframeDocument().getElementById("form")},getFormInputNode:function(){return this.getIframeDocument().getElementById("input")},getFormDataNode:function(){return this.getIframeDocument().getElementById("data")},getFileForMultiple:function(e){return this.multiple?[e]:e},getIframeHTML:function(e){var t="",n="";if(e){t=' + + + + + + + + + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/common/prompt_modal.html b/web/html/common/prompt_modal.html new file mode 100644 index 00000000..91c26615 --- /dev/null +++ b/web/html/common/prompt_modal.html @@ -0,0 +1,67 @@ +{{define "promptModal"}} + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/common/qrcode_modal.html b/web/html/common/qrcode_modal.html new file mode 100644 index 00000000..c80f8a0e --- /dev/null +++ b/web/html/common/qrcode_modal.html @@ -0,0 +1,120 @@ +{{define "qrcodeModal"}} + + click on QR Code to Copy + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/common/text_modal.html b/web/html/common/text_modal.html new file mode 100644 index 00000000..0ae04a88 --- /dev/null +++ b/web/html/common/text_modal.html @@ -0,0 +1,58 @@ +{{define "textModal"}} + + + {{ i18n "download" }} [[ txtModal.fileName ]] + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/login.html b/web/html/login.html new file mode 100644 index 00000000..5138f15e --- /dev/null +++ b/web/html/login.html @@ -0,0 +1,123 @@ + + +{{template "head" .}} + + + + + + + +

{{ i18n "pages.login.title" }}

+
+
+ + + + + + + + + + + + + + + {{ i18n "login" }} + + + + + Language : + + + + + +    + + + + + + + + + + + + +
+
+
+{{template "js" .}} + + + \ No newline at end of file diff --git a/web/html/xui/common_sider.html b/web/html/xui/common_sider.html new file mode 100644 index 00000000..f4499eeb --- /dev/null +++ b/web/html/xui/common_sider.html @@ -0,0 +1,73 @@ +{{define "menuItems"}} + + + {{ i18n "menu.dashboard"}} + + + + {{ i18n "menu.inbounds"}} + + + + {{ i18n "menu.setting"}} + + + + + + + + + + Github + + + + Telegram Group + + + + + {{ i18n "menu.logout"}} + +{{end}} + + +{{define "commonSider"}} + + + {{template "menuItems" .}} + + + +
+ +
+ + {{template "menuItems" .}} + +
+ +{{end}} diff --git a/web/html/xui/component/inbound_info.html b/web/html/xui/component/inbound_info.html new file mode 100644 index 00000000..cbf156d1 --- /dev/null +++ b/web/html/xui/component/inbound_info.html @@ -0,0 +1,94 @@ +{{define "inboundInfoStream"}} +

{{ i18n "transmission" }}: [[ inbound.network ]]

+ + + + + + + + + + + +

+ tls {{ i18n "domainName" }}: [[ inbound.serverName ? inbound.serverName : '' ]] +

+

+ xtls {{ i18n "domainName" }}: [[ inbound.serverName ? inbound.serverName : '' ]] +

+{{end}} + + +{{define "component/inboundInfoComponent"}} +
+

{{ i18n "protocol"}}: [[ dbInbound.protocol ]]

+

{{ i18n "pages.inbounds.address"}}: [[ dbInbound.address ]]

+

{{ i18n "pages.inbounds.port"}}: [[ dbInbound.port ]]

+ + + + + + + + + + + + + + +
+{{end}} + +{{define "component/inboundInfo"}} + +{{end}} \ No newline at end of file diff --git a/web/html/xui/component/setting.html b/web/html/xui/component/setting.html new file mode 100644 index 00000000..9f8e8cbc --- /dev/null +++ b/web/html/xui/component/setting.html @@ -0,0 +1,32 @@ +{{define "component/settingListItem"}} + + + + + + + + + + + + + +{{end}} + +{{define "component/setting"}} + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/inbound.html b/web/html/xui/form/inbound.html new file mode 100644 index 00000000..1a2e7ca1 --- /dev/null +++ b/web/html/xui/form/inbound.html @@ -0,0 +1,106 @@ +{{define "form/inbound"}} + + + + + + + + + + + [[ p ]] + + + + + {{ i18n "monitor" }} + + + + + + + + + + + + + {{ i18n "pages.inbounds.totalFlow" }}(GB) + + + + + + + + + + {{ i18n "pages.inbounds.expireDate" }} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/protocol/dokodemo.html b/web/html/xui/form/protocol/dokodemo.html new file mode 100644 index 00000000..a4dde06d --- /dev/null +++ b/web/html/xui/form/protocol/dokodemo.html @@ -0,0 +1,17 @@ +{{define "form/dokodemo"}} + + + + + + + + + + tcp+udp + tcp + udp + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/protocol/http.html b/web/html/xui/form/protocol/http.html new file mode 100644 index 00000000..b4ba59b7 --- /dev/null +++ b/web/html/xui/form/protocol/http.html @@ -0,0 +1,10 @@ +{{define "form/http"}} + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/protocol/shadowsocks.html b/web/html/xui/form/protocol/shadowsocks.html new file mode 100644 index 00000000..18bcf727 --- /dev/null +++ b/web/html/xui/form/protocol/shadowsocks.html @@ -0,0 +1,19 @@ +{{define "form/shadowsocks"}} + + + + [[ method ]] + + + + + + + + tcp+udp + tcp + udp + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/protocol/socks.html b/web/html/xui/form/protocol/socks.html new file mode 100644 index 00000000..35c1c0b5 --- /dev/null +++ b/web/html/xui/form/protocol/socks.html @@ -0,0 +1,24 @@ +{{define "form/socks"}} + + + + + + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/protocol/trojan.html b/web/html/xui/form/protocol/trojan.html new file mode 100644 index 00000000..69c67052 --- /dev/null +++ b/web/html/xui/form/protocol/trojan.html @@ -0,0 +1,141 @@ +{{define "form/trojan"}} + + + + + + Account is (Expired|Traffic Ended) And Disabled + + + + Email + + + + + + + + + + + + + + + none + [[ key ]] + + + + + {{ i18n "pages.inbounds.totalFlow" }}(GB) + + + + + + + + + + {{ i18n "pages.inbounds.expireDate" }} + + + + + + + + + + + + + + + [[ sizeFormat(getUpStats(trojan.email)) ]] / [[ sizeFormat(getDownStats(trojan.email)) ]] + used : [[ sizeFormat(getUpStats(trojan.email) + getDownStats(trojan.email)) ]] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + fallback[[ index + 1 ]] + + + + + + + + + + + + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/protocol/vless.html b/web/html/xui/form/protocol/vless.html new file mode 100644 index 00000000..e858906e --- /dev/null +++ b/web/html/xui/form/protocol/vless.html @@ -0,0 +1,155 @@ +{{define "form/vless"}} + + + + + Account is (Expired|Traffic Ended) And Disabled + + + + + Email + + + + + + + + + + + + + + + none + [[ key ]] + + + + + none + [[ key ]] + + + + + [[ key ]] + + + + + {{ i18n "pages.inbounds.totalFlow" }}(GB) + + + + + + + + + + {{ i18n "pages.inbounds.expireDate" }} + + + + + + + + + + + + + + + [[ sizeFormat(getUpStats(vless.email)) ]] / [[ sizeFormat(getDownStats(vless.email)) ]] + used : [[ sizeFormat(getUpStats(vless.email) + getDownStats(vless.email)) ]] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + fallback[[ index + 1 ]] + + + + + + + + + + + + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/protocol/vmess.html b/web/html/xui/form/protocol/vmess.html new file mode 100644 index 00000000..df532767 --- /dev/null +++ b/web/html/xui/form/protocol/vmess.html @@ -0,0 +1,119 @@ +{{define "form/vmess"}} + + + + Account is (Expired|Traffic Ended) And Disabled + + + + + Email + + + + + + + + + + + + + + + + + + {{ i18n "pages.inbounds.totalFlow" }}(GB) + + + + + + + + + + {{ i18n "pages.inbounds.expireDate" }} + + + + + + + + + + + + + + + [[ sizeFormat(getUpStats(vmess.email)) ]] / [[ sizeFormat(getDownStats(vmess.email)) ]] + used : [[ sizeFormat(getUpStats(vmess.email) + getDownStats(vmess.email)) ]] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +{{end}} diff --git a/web/html/xui/form/sniffing.html b/web/html/xui/form/sniffing.html new file mode 100644 index 00000000..838c92fc --- /dev/null +++ b/web/html/xui/form/sniffing.html @@ -0,0 +1,16 @@ +{{define "form/sniffing"}} + + + + sniffing + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/stream/stream_grpc.html b/web/html/xui/form/stream/stream_grpc.html new file mode 100644 index 00000000..205a4c84 --- /dev/null +++ b/web/html/xui/form/stream/stream_grpc.html @@ -0,0 +1,7 @@ +{{define "form/streamGRPC"}} + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/stream/stream_http.html b/web/html/xui/form/stream/stream_http.html new file mode 100644 index 00000000..ad30c45a --- /dev/null +++ b/web/html/xui/form/stream/stream_http.html @@ -0,0 +1,12 @@ +{{define "form/streamHTTP"}} + + + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/stream/stream_kcp.html b/web/html/xui/form/stream/stream_kcp.html new file mode 100644 index 00000000..ff14d5b7 --- /dev/null +++ b/web/html/xui/form/stream/stream_kcp.html @@ -0,0 +1,38 @@ +{{define "form/streamKCP"}} + + + + none(not camouflage) + srtp(camouflage video call) + utp(camouflage BT download) + wechat-video(camouflage WeChat video) + dtls(camouflage DTLS 1.2 packages) + wireguard(camouflage wireguard packages) + + + + + + + + + + + + + + + + + + + + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/stream/stream_quic.html b/web/html/xui/form/stream/stream_quic.html new file mode 100644 index 00000000..942461ad --- /dev/null +++ b/web/html/xui/form/stream/stream_quic.html @@ -0,0 +1,24 @@ +{{define "form/streamQUIC"}} + + + + none + aes-128-gcm + chacha20-poly1305 + + + + + + + + none(not camouflage) + srtp(camouflage video call) + utp(camouflage BT download) + wechat-video(camouflage WeChat video) + dtls(camouflage DTLS 1.2 packages) + wireguard(camouflage wireguard packages) + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/stream/stream_settings.html b/web/html/xui/form/stream/stream_settings.html new file mode 100644 index 00000000..7fc9ad2c --- /dev/null +++ b/web/html/xui/form/stream/stream_settings.html @@ -0,0 +1,45 @@ +{{define "form/streamSettings"}} + + + + + tcp + kcp + ws + http + quic + grpc + + + + + + + + + + + + + + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/stream/stream_tcp.html b/web/html/xui/form/stream/stream_tcp.html new file mode 100644 index 00000000..fc19506d --- /dev/null +++ b/web/html/xui/form/stream/stream_tcp.html @@ -0,0 +1,86 @@ +{{define "form/streamTCP"}} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/stream/stream_ws.html b/web/html/xui/form/stream/stream_ws.html new file mode 100644 index 00000000..46d6f7a3 --- /dev/null +++ b/web/html/xui/form/stream/stream_ws.html @@ -0,0 +1,33 @@ +{{define "form/streamWS"}} + + + + + + + + + + + + + + + + + + + + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/form/tls_settings.html b/web/html/xui/form/tls_settings.html new file mode 100644 index 00000000..06dbaa4f --- /dev/null +++ b/web/html/xui/form/tls_settings.html @@ -0,0 +1,60 @@ +{{define "form/tlsSettings"}} + + + + + + + + + + + + + + + + [[ key ]] + + + + + [[ key ]] + + + + + auto + [[ key ]] + + + + + + + + + + + {{ i18n "pages.inbounds.certificatePath" }} + {{ i18n "pages.inbounds.certificateContent" }} + + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/inbound_info_modal.html b/web/html/xui/inbound_info_modal.html new file mode 100644 index 00000000..bcd2b25f --- /dev/null +++ b/web/html/xui/inbound_info_modal.html @@ -0,0 +1,61 @@ +{{define "inboundInfoModal"}} +{{template "component/inboundInfo"}} + + + + +{{end}} \ No newline at end of file diff --git a/web/html/xui/inbound_modal.html b/web/html/xui/inbound_modal.html new file mode 100644 index 00000000..8d72ca2f --- /dev/null +++ b/web/html/xui/inbound_modal.html @@ -0,0 +1,178 @@ +{{define "inboundModal"}} + + {{template "form/inbound"}} + + +{{end}} diff --git a/web/html/xui/inbounds.html b/web/html/xui/inbounds.html new file mode 100644 index 00000000..d7e56612 --- /dev/null +++ b/web/html/xui/inbounds.html @@ -0,0 +1,457 @@ + + +{{template "head" .}} + + + + {{ template "commonSider" . }} + + + + + + Please go to the panel settings as soon as possible to modify the username and password, otherwise there may be a risk of leaking account information + + + + + + + {{ i18n "pages.inbounds.totalDownUp" }}: + [[ sizeFormat(total.up) ]] / [[ sizeFormat(total.down) ]] + + + {{ i18n "pages.inbounds.totalUsage" }}: + [[ sizeFormat(total.up + total.down) ]] + + + {{ i18n "pages.inbounds.inboundCount" }}: + [[ dbInbounds.length ]] + + + + + + +
+ Add Inbound +
+ + + + + + + + + + + +
+
+
+
+
+
+{{template "js" .}} + + +{{template "inboundModal"}} +{{template "promptModal"}} +{{template "qrcodeModal"}} +{{template "textModal"}} +{{template "inboundInfoModal"}} + + \ No newline at end of file diff --git a/web/html/xui/inbounds_client_row.html b/web/html/xui/inbounds_client_row.html new file mode 100644 index 00000000..cb231f5e --- /dev/null +++ b/web/html/xui/inbounds_client_row.html @@ -0,0 +1,22 @@ +{{define "form/client_row"}} + + + +{{end}} diff --git a/web/html/xui/index.html b/web/html/xui/index.html new file mode 100644 index 00000000..b4e5be7f --- /dev/null +++ b/web/html/xui/index.html @@ -0,0 +1,334 @@ + + +{{template "head" .}} + + + + {{ template "commonSider" . }} + + + + + + + + + + + +
CPU
+
+ + +
+ {{ i18n "pages.index.memory"}}: [[ sizeFormat(status.mem.current) ]] / [[ sizeFormat(status.mem.total) ]] +
+
+
+
+ + + + +
+ swap: [[ sizeFormat(status.swap.current) ]] / [[ sizeFormat(status.swap.total) ]] +
+
+ + +
+ {{ i18n "pages.index.hard"}}: [[ sizeFormat(status.disk.current) ]] / [[ sizeFormat(status.disk.total) ]] +
+
+
+
+
+
+
+
+ + + + + {{ i18n "pages.index.xrayStatus" }}: + [[ status.xray.state ]] + + + + + [[ status.xray.version ]] + {{ i18n "pages.index.xraySwitch"}} + + + + + {{ i18n "pages.index.operationHours" }}: + [[ formatSecond(status.uptime) ]] + + + + + + + + + {{ i18n "pages.index.systemLoad" }}: [[ status.loads[0] ]] | [[ status.loads[1] ]] | [[ status.loads[2] ]] + + + + + tcp / udp {{ i18n "pages.index.connectionCount" }}: [[ status.tcpCount ]] / [[ status.udpCount ]] + + + + + + + + + + + + [[ sizeFormat(status.netIO.up) ]] / S + + + + + + + + [[ sizeFormat(status.netIO.down) ]] / S + + + + + + + + + + + + + + [[ sizeFormat(status.netTraffic.sent) ]] + + + + + + + + [[ sizeFormat(status.netTraffic.recv) ]] + + + + + + + + + + +
+
+ +

{{ i18n "pages.index.xraySwitchClick"}}

+

{{ i18n "pages.index.xraySwitchClickDesk"}}

+ +
+
+{{template "js" .}} + + + \ No newline at end of file diff --git a/web/html/xui/setting.html b/web/html/xui/setting.html new file mode 100644 index 00000000..67ceaff9 --- /dev/null +++ b/web/html/xui/setting.html @@ -0,0 +1,196 @@ + + +{{template "head" .}} + + + + {{ template "commonSider" . }} + + + + + + {{ i18n "pages.setting.save" }} + {{ i18n "pages.setting.restartPanel" }} + + + + + + + + + + + + + + + + + + + + + +    + + + + + + + + + + + + + + + + + + + + + + + + + + {{ i18n "confirm" }} + + + + + + + + + + + + + + + + + + + + + + + + + + + +{{template "js" .}} +{{template "component/setting"}} + + + \ No newline at end of file diff --git a/web/job/check_inbound_job.go b/web/job/check_inbound_job.go new file mode 100644 index 00000000..2b24afb0 --- /dev/null +++ b/web/job/check_inbound_job.go @@ -0,0 +1,33 @@ +package job + +import ( + "x-ui/logger" + "x-ui/web/service" +) + +type CheckInboundJob struct { + xrayService service.XrayService + inboundService service.InboundService +} + +func NewCheckInboundJob() *CheckInboundJob { + return new(CheckInboundJob) +} + +func (j *CheckInboundJob) Run() { + count, err := j.inboundService.DisableInvalidClients() + if err != nil { + logger.Warning("disable invalid Client err:", err) + } else if count > 0 { + logger.Debugf("disabled %v Client", count) + j.xrayService.SetToNeedRestart() + } + + count, err = j.inboundService.DisableInvalidInbounds() + if err != nil { + logger.Warning("disable invalid inbounds err:", err) + } else if count > 0 { + logger.Debugf("disabled %v inbounds", count) + j.xrayService.SetToNeedRestart() + } +} diff --git a/web/job/check_xray_running_job.go b/web/job/check_xray_running_job.go new file mode 100644 index 00000000..f1a848bf --- /dev/null +++ b/web/job/check_xray_running_job.go @@ -0,0 +1,25 @@ +package job + +import "x-ui/web/service" + +type CheckXrayRunningJob struct { + xrayService service.XrayService + + checkTime int +} + +func NewCheckXrayRunningJob() *CheckXrayRunningJob { + return new(CheckXrayRunningJob) +} + +func (j *CheckXrayRunningJob) Run() { + if j.xrayService.IsXrayRunning() { + j.checkTime = 0 + return + } + j.checkTime++ + if j.checkTime < 2 { + return + } + j.xrayService.SetToNeedRestart() +} diff --git a/web/job/stats_notify_job.go b/web/job/stats_notify_job.go new file mode 100644 index 00000000..5209e204 --- /dev/null +++ b/web/job/stats_notify_job.go @@ -0,0 +1,248 @@ +package job + +import ( + "fmt" + "net" + "os" + "time" + "x-ui/logger" + "x-ui/util/common" + "x-ui/web/service" + tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5" +) + +type LoginStatus byte + +const ( + LoginSuccess LoginStatus = 1 + LoginFail LoginStatus = 0 +) + +type StatsNotifyJob struct { + enable bool + xrayService service.XrayService + inboundService service.InboundService + settingService service.SettingService +} + +func NewStatsNotifyJob() *StatsNotifyJob { + return new(StatsNotifyJob) +} + +func (j *StatsNotifyJob) SendMsgToTgbot(msg string) { + //Telegram bot basic info + tgBottoken, err := j.settingService.GetTgBotToken() + if err != nil || tgBottoken == "" { + logger.Warning("sendMsgToTgbot failed,GetTgBotToken fail:", err) + return + } + tgBotid, err := j.settingService.GetTgBotChatId() + if err != nil { + logger.Warning("sendMsgToTgbot failed,GetTgBotChatId fail:", err) + return + } + + bot, err := tgbotapi.NewBotAPI(tgBottoken) + if err != nil { + fmt.Println("get tgbot error:", err) + return + } + bot.Debug = true + fmt.Printf("Authorized on account %s", bot.Self.UserName) + info := tgbotapi.NewMessage(int64(tgBotid), msg) + //msg.ReplyToMessageID = int(tgBotid) + bot.Send(info) +} + +//Here run is a interface method of Job interface +func (j *StatsNotifyJob) Run() { + if !j.xrayService.IsXrayRunning() { + return + } + var info string + //get hostname + name, err := os.Hostname() + if err != nil { + fmt.Println("get hostname error:", err) + return + } + info = fmt.Sprintf("Hostname:%s\r\n", name) + //get ip address + var ip string + netInterfaces, err := net.Interfaces() + if err != nil { + fmt.Println("net.Interfaces failed, err:", err.Error()) + return + } + + for i := 0; i < len(netInterfaces); i++ { + if (netInterfaces[i].Flags & net.FlagUp) != 0 { + addrs, _ := netInterfaces[i].Addrs() + + for _, address := range addrs { + if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() { + if ipnet.IP.To4() != nil { + ip = ipnet.IP.String() + break + } else { + ip = ipnet.IP.String() + break + } + } + } + } + } + info += fmt.Sprintf("IP:%s\r\n \r\n", ip) + + //get traffic + inbouds, err := j.inboundService.GetAllInbounds() + if err != nil { + logger.Warning("StatsNotifyJob run failed:", err) + return + } + //NOTE:If there no any sessions here,need to notify here + //TODO:分节点推送,自动转化格式 + for _, inbound := range inbouds { + info += fmt.Sprintf("Node name:%s\r\nPort:%d\r\nUpload↑:%s\r\nDownload↓:%s\r\nTotal:%s\r\n", inbound.Remark, inbound.Port, common.FormatTraffic(inbound.Up), common.FormatTraffic(inbound.Down), common.FormatTraffic((inbound.Up + inbound.Down))) + if inbound.ExpiryTime == 0 { + info += fmt.Sprintf("Expire date:unlimited\r\n \r\n") + } else { + info += fmt.Sprintf("Expire date:%s\r\n \r\n", time.Unix((inbound.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05")) + } + } + j.SendMsgToTgbot(info) +} + +func (j *StatsNotifyJob) UserLoginNotify(username string, ip string, time string, status LoginStatus) { + if username == "" || ip == "" || time == "" { + logger.Warning("UserLoginNotify failed,invalid info") + return + } + var msg string + //get hostname + name, err := os.Hostname() + if err != nil { + fmt.Println("get hostname error:", err) + return + } + if status == LoginSuccess { + msg = fmt.Sprintf("Successfully logged-in to the panel\r\nHostname:%s\r\n", name) + } else if status == LoginFail { + msg = fmt.Sprintf("Login to the panel was unsuccessful\r\nHostname:%s\r\n", name) + } + msg += fmt.Sprintf("Time:%s\r\n", time) + msg += fmt.Sprintf("Username:%s\r\n", username) + msg += fmt.Sprintf("IP:%s\r\n", ip) + j.SendMsgToTgbot(msg) +} + + +var numericKeyboard = tgbotapi.NewInlineKeyboardMarkup( + tgbotapi.NewInlineKeyboardRow( + tgbotapi.NewInlineKeyboardButtonData("Get Usage", "get_usage"), + ), +) + +func (j *StatsNotifyJob) OnReceive() *StatsNotifyJob { + tgBottoken, err := j.settingService.GetTgBotToken() + if err != nil || tgBottoken == "" { + logger.Warning("sendMsgToTgbot failed,GetTgBotToken fail:", err) + return j + } + bot, err := tgbotapi.NewBotAPI(tgBottoken) + if err != nil { + fmt.Println("get tgbot error:", err) + return j + } + bot.Debug = false + u := tgbotapi.NewUpdate(0) + u.Timeout = 10 + + updates := bot.GetUpdatesChan(u) + + for update := range updates { + if update.Message == nil { + + if update.CallbackQuery != nil { + // Respond to the callback query, telling Telegram to show the user + // a message with the data received. + callback := tgbotapi.NewCallback(update.CallbackQuery.ID, update.CallbackQuery.Data) + if _, err := bot.Request(callback); err != nil { + logger.Warning(err) + } + + // And finally, send a message containing the data received. + msg := tgbotapi.NewMessage(update.CallbackQuery.Message.Chat.ID, "") + + switch update.CallbackQuery.Data { + case "get_usage": + msg.Text = "for get your usage send command like this : \n /usage uuid | id \n example : /usage fc3239ed-8f3b-4151-ff51-b183d5182142" + msg.ParseMode = "HTML" + } + if _, err := bot.Send(msg); err != nil { + logger.Warning(err) + } + } + + continue + } + + if !update.Message.IsCommand() { // ignore any non-command Messages + continue + } + + // Create a new MessageConfig. We don't have text yet, + // so we leave it empty. + msg := tgbotapi.NewMessage(update.Message.Chat.ID, "") + + // Extract the command from the Message. + switch update.Message.Command() { + case "help": + msg.Text = "What you need?" + msg.ReplyMarkup = numericKeyboard + case "start": + msg.Text = "Hi :) \n What you need?" + msg.ReplyMarkup = numericKeyboard + + case "status": + msg.Text = "bot is ok." + + case "usage": + msg.Text = j.getClientUsage(update.Message.CommandArguments()) + default: + msg.Text = "I don't know that command, /help" + msg.ReplyMarkup = numericKeyboard + + } + + if _, err := bot.Send(msg); err != nil { + logger.Warning(err) + } + } + return j + +} +func (j *StatsNotifyJob) getClientUsage(id string) string { + traffic , err := j.inboundService.GetClientTrafficById(id) + if err != nil { + logger.Warning(err) + return "something wrong!" + } + expiryTime := "" + if traffic.ExpiryTime == 0 { + expiryTime = fmt.Sprintf("unlimited") + } else { + expiryTime = fmt.Sprintf("%s", time.Unix((traffic.ExpiryTime/1000), 0).Format("2006-01-02 15:04:05")) + } + total := "" + if traffic.Total == 0 { + total = fmt.Sprintf("unlimited") + } else { + total = fmt.Sprintf("%s", common.FormatTraffic((traffic.Total))) + } + output := fmt.Sprintf("💡 Active: %t\r\n📧 Email: %s\r\n🔼 Upload↑: %s\r\n🔽 Download↓: %s\r\n🔄 Total: %s / %s\r\n📅 Expire in: %s\r\n", + traffic.Enable, traffic.Email, common.FormatTraffic(traffic.Up), common.FormatTraffic(traffic.Down), common.FormatTraffic((traffic.Up + traffic.Down)), + total, expiryTime) + + return output +} diff --git a/web/job/xray_traffic_job.go b/web/job/xray_traffic_job.go new file mode 100644 index 00000000..97f85c24 --- /dev/null +++ b/web/job/xray_traffic_job.go @@ -0,0 +1,38 @@ +package job + +import ( + "x-ui/logger" + "x-ui/web/service" +) + +type XrayTrafficJob struct { + xrayService service.XrayService + inboundService service.InboundService +} + +func NewXrayTrafficJob() *XrayTrafficJob { + return new(XrayTrafficJob) +} + +func (j *XrayTrafficJob) Run() { + if !j.xrayService.IsXrayRunning() { + return + } + + traffics, clientTraffics, err := j.xrayService.GetXrayTraffic() + if err != nil { + logger.Warning("get xray traffic failed:", err) + return + } + err = j.inboundService.AddTraffic(traffics) + if err != nil { + logger.Warning("add traffic failed:", err) + } + + err = j.inboundService.AddClientTraffic(clientTraffics) + if err != nil { + logger.Warning("add client traffic failed:", err) + } + + +} diff --git a/web/network/auto_https_listener.go b/web/network/auto_https_listener.go new file mode 100644 index 00000000..26614696 --- /dev/null +++ b/web/network/auto_https_listener.go @@ -0,0 +1,21 @@ +package network + +import "net" + +type AutoHttpsListener struct { + net.Listener +} + +func NewAutoHttpsListener(listener net.Listener) net.Listener { + return &AutoHttpsListener{ + Listener: listener, + } +} + +func (l *AutoHttpsListener) Accept() (net.Conn, error) { + conn, err := l.Listener.Accept() + if err != nil { + return nil, err + } + return NewAutoHttpsConn(conn), nil +} diff --git a/web/network/autp_https_conn.go b/web/network/autp_https_conn.go new file mode 100644 index 00000000..d1a9d521 --- /dev/null +++ b/web/network/autp_https_conn.go @@ -0,0 +1,67 @@ +package network + +import ( + "bufio" + "bytes" + "fmt" + "net" + "net/http" + "sync" +) + +type AutoHttpsConn struct { + net.Conn + + firstBuf []byte + bufStart int + + readRequestOnce sync.Once +} + +func NewAutoHttpsConn(conn net.Conn) net.Conn { + return &AutoHttpsConn{ + Conn: conn, + } +} + +func (c *AutoHttpsConn) readRequest() bool { + c.firstBuf = make([]byte, 2048) + n, err := c.Conn.Read(c.firstBuf) + c.firstBuf = c.firstBuf[:n] + if err != nil { + return false + } + reader := bytes.NewReader(c.firstBuf) + bufReader := bufio.NewReader(reader) + request, err := http.ReadRequest(bufReader) + if err != nil { + return false + } + resp := http.Response{ + Header: http.Header{}, + } + resp.StatusCode = http.StatusTemporaryRedirect + location := fmt.Sprintf("https://%v%v", request.Host, request.RequestURI) + resp.Header.Set("Location", location) + resp.Write(c.Conn) + c.Close() + c.firstBuf = nil + return true +} + +func (c *AutoHttpsConn) Read(buf []byte) (int, error) { + c.readRequestOnce.Do(func() { + c.readRequest() + }) + + if c.firstBuf != nil { + n := copy(buf, c.firstBuf[c.bufStart:]) + c.bufStart += n + if c.bufStart >= len(c.firstBuf) { + c.firstBuf = nil + } + return n, nil + } + + return c.Conn.Read(buf) +} diff --git a/web/service/config.json b/web/service/config.json new file mode 100644 index 00000000..5370fcf4 --- /dev/null +++ b/web/service/config.json @@ -0,0 +1,75 @@ +{ + "log": { + "loglevel": "warning", + "access": "./access.log" + }, + + "api": { + "services": [ + "HandlerService", + "LoggerService", + "StatsService" + ], + "tag": "api" + }, + "inbounds": [ + { + "listen": "127.0.0.1", + "port": 62789, + "protocol": "dokodemo-door", + "settings": { + "address": "127.0.0.1" + }, + "tag": "api" + } + ], + "outbounds": [ + { + "protocol": "freedom", + "settings": {} + }, + { + "protocol": "blackhole", + "settings": {}, + "tag": "blocked" + } + ], + "policy": { + "levels": { + "0": { + "statsUserUplink": true, + "statsUserDownlink": true + } + }, + "system": { + "statsInboundDownlink": true, + "statsInboundUplink": true + } + }, + "routing": { + "rules": [ + { + "inboundTag": [ + "api" + ], + "outboundTag": "api", + "type": "field" + }, + { + "ip": [ + "geoip:private" + ], + "outboundTag": "blocked", + "type": "field" + }, + { + "outboundTag": "blocked", + "protocol": [ + "bittorrent" + ], + "type": "field" + } + ] + }, + "stats": {} +} diff --git a/web/service/inbound.go b/web/service/inbound.go new file mode 100644 index 00000000..37888729 --- /dev/null +++ b/web/service/inbound.go @@ -0,0 +1,417 @@ +package service + +import ( + "fmt" + "time" + "x-ui/database" + "encoding/json" + "x-ui/database/model" + "x-ui/util/common" + "x-ui/xray" + "x-ui/logger" + + "gorm.io/gorm" +) + +type InboundService struct { +} + +func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) { + db := database.GetDB() + var inbounds []*model.Inbound + err := db.Model(model.Inbound{}).Preload("ClientStats").Where("user_id = ?", userId).Find(&inbounds).Error + if err != nil && err != gorm.ErrRecordNotFound { + return nil, err + } + return inbounds, nil +} + +func (s *InboundService) GetAllInbounds() ([]*model.Inbound, error) { + db := database.GetDB() + var inbounds []*model.Inbound + err := db.Model(model.Inbound{}).Preload("ClientStats").Find(&inbounds).Error + if err != nil && err != gorm.ErrRecordNotFound { + return nil, err + } + return inbounds, nil +} + +func (s *InboundService) checkPortExist(port int, ignoreId int) (bool, error) { + db := database.GetDB() + db = db.Model(model.Inbound{}).Where("port = ?", port) + if ignoreId > 0 { + db = db.Where("id != ?", ignoreId) + } + var count int64 + err := db.Count(&count).Error + if err != nil { + return false, err + } + return count > 0, nil +} + +func (s *InboundService) getClients(inbound *model.Inbound) ([]model.Client, error) { + settings := map[string][]model.Client{} + json.Unmarshal([]byte(inbound.Settings), &settings) + if settings == nil { + return nil, fmt.Errorf("Setting is null") + } + + clients := settings["clients"] + if clients == nil { + return nil, nil + } + return clients, nil +} + +func (s *InboundService) checkEmailsExist(emails map[string] bool, ignoreId int) (string, error) { + db := database.GetDB() + var inbounds []*model.Inbound + db = db.Model(model.Inbound{}).Where("Protocol in ?", []model.Protocol{model.VMess, model.VLESS}) + if (ignoreId > 0) { + db = db.Where("id != ?", ignoreId) + } + db = db.Find(&inbounds) + if db.Error != nil { + return "", db.Error + } + + for _, inbound := range inbounds { + clients, err := s.getClients(inbound) + if err != nil { + return "", err + } + + for _, client := range clients { + if emails[client.Email] { + return client.Email, nil + } + } + } + return "", nil +} + +func (s *InboundService) checkEmailExistForInbound(inbound *model.Inbound) (string, error) { + clients, err := s.getClients(inbound) + if err != nil { + return "", err + } + emails := make(map[string] bool) + for _, client := range clients { + if (client.Email != "") { + if emails[client.Email] { + return client.Email, nil + } + emails[client.Email] = true; + } + } + return s.checkEmailsExist(emails, inbound.Id) +} + +func (s *InboundService) AddInbound(inbound *model.Inbound) (*model.Inbound,error) { + exist, err := s.checkPortExist(inbound.Port, 0) + if err != nil { + return inbound, err + } + if exist { + return inbound, common.NewError("端口已存在:", inbound.Port) + } + + existEmail, err := s.checkEmailExistForInbound(inbound) + if err != nil { + return inbound, err + } + if existEmail != "" { + return inbound, common.NewError("Duplicate email:", existEmail) + } + + db := database.GetDB() + + err = db.Save(inbound).Error + if err == nil { + s.UpdateClientStat(inbound.Id,inbound.Settings) + } + return inbound, err +} + +func (s *InboundService) AddInbounds(inbounds []*model.Inbound) error { + for _, inbound := range inbounds { + exist, err := s.checkPortExist(inbound.Port, 0) + if err != nil { + return err + } + if exist { + return common.NewError("端口已存在:", inbound.Port) + } + } + + db := database.GetDB() + tx := db.Begin() + var err error + defer func() { + if err == nil { + tx.Commit() + } else { + tx.Rollback() + } + }() + + for _, inbound := range inbounds { + err = tx.Save(inbound).Error + if err != nil { + return err + } + } + + return nil +} + +func (s *InboundService) DelInbound(id int) error { + db := database.GetDB() + return db.Delete(model.Inbound{}, id).Error +} + +func (s *InboundService) GetInbound(id int) (*model.Inbound, error) { + db := database.GetDB() + inbound := &model.Inbound{} + err := db.Model(model.Inbound{}).First(inbound, id).Error + if err != nil { + return nil, err + } + return inbound, nil +} + +func (s *InboundService) UpdateInbound(inbound *model.Inbound) (*model.Inbound, error) { + exist, err := s.checkPortExist(inbound.Port, inbound.Id) + if err != nil { + return inbound, err + } + if exist { + return inbound, common.NewError("端口已存在:", inbound.Port) + } + + existEmail, err := s.checkEmailExistForInbound(inbound) + if err != nil { + return inbound, err + } + if existEmail != "" { + return inbound, common.NewError("Duplicate email:", existEmail) + } + + oldInbound, err := s.GetInbound(inbound.Id) + if err != nil { + return inbound, err + } + oldInbound.Up = inbound.Up + oldInbound.Down = inbound.Down + oldInbound.Total = inbound.Total + oldInbound.Remark = inbound.Remark + oldInbound.Enable = inbound.Enable + oldInbound.ExpiryTime = inbound.ExpiryTime + oldInbound.Listen = inbound.Listen + oldInbound.Port = inbound.Port + oldInbound.Protocol = inbound.Protocol + oldInbound.Settings = inbound.Settings + oldInbound.StreamSettings = inbound.StreamSettings + oldInbound.Sniffing = inbound.Sniffing + oldInbound.Tag = fmt.Sprintf("inbound-%v", inbound.Port) + + s.UpdateClientStat(inbound.Id,inbound.Settings) + db := database.GetDB() + return inbound, db.Save(oldInbound).Error +} + +func (s *InboundService) AddTraffic(traffics []*xray.Traffic) (err error) { + if len(traffics) == 0 { + return nil + } + db := database.GetDB() + db = db.Model(model.Inbound{}) + tx := db.Begin() + defer func() { + if err != nil { + tx.Rollback() + } else { + tx.Commit() + } + }() + for _, traffic := range traffics { + if traffic.IsInbound { + err = tx.Where("tag = ?", traffic.Tag). + UpdateColumn("up", gorm.Expr("up + ?", traffic.Up)). + UpdateColumn("down", gorm.Expr("down + ?", traffic.Down)). + Error + if err != nil { + return + } + } + } + return +} +func (s *InboundService) AddClientTraffic(traffics []*xray.ClientTraffic) (err error) { + if len(traffics) == 0 { + return nil + } + db := database.GetDB() + dbInbound := db.Model(model.Inbound{}) + + db = db.Model(xray.ClientTraffic{}) + tx := db.Begin() + defer func() { + if err != nil { + tx.Rollback() + } else { + tx.Commit() + } + }() + txInbound := dbInbound.Begin() + defer func() { + if err != nil { + txInbound.Rollback() + } else { + txInbound.Commit() + } + }() + + for _, traffic := range traffics { + inbound := &model.Inbound{} + + err := txInbound.Where("settings like ?", "%" + traffic.Email + "%").First(inbound).Error + traffic.InboundId = inbound.Id + if err != nil { + if err == gorm.ErrRecordNotFound { + // delete removed client record + clientErr := s.DelClientStat(tx, traffic.Email) + logger.Warning(err, traffic.Email,clientErr) + + } + continue + } + // get settings clients + settings := map[string][]model.Client{} + json.Unmarshal([]byte(inbound.Settings), &settings) + clients := settings["clients"] + for _, client := range clients { + if traffic.Email == client.Email { + traffic.ExpiryTime = client.ExpiryTime + traffic.Total = client.TotalGB + } + } + if tx.Where("inbound_id = ?", inbound.Id).Where("email = ?", traffic.Email). + UpdateColumn("enable", true). + UpdateColumn("expiry_time", traffic.ExpiryTime). + UpdateColumn("total",traffic.Total). + UpdateColumn("up", gorm.Expr("up + ?", traffic.Up)). + UpdateColumn("down", gorm.Expr("down + ?", traffic.Down)).RowsAffected == 0 { + err = tx.Create(traffic).Error + } + + if err != nil { + logger.Warning("AddClientTraffic update data ", err) + continue + } + + } + return +} + +func (s *InboundService) DisableInvalidInbounds() (int64, error) { + db := database.GetDB() + now := time.Now().Unix() * 1000 + result := db.Model(model.Inbound{}). + Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true). + Update("enable", false) + err := result.Error + count := result.RowsAffected + return count, err +} +func (s *InboundService) DisableInvalidClients() (int64, error) { + db := database.GetDB() + now := time.Now().Unix() * 1000 + result := db.Model(xray.ClientTraffic{}). + Where("((total > 0 and up + down >= total) or (expiry_time > 0 and expiry_time <= ?)) and enable = ?", now, true). + Update("enable", false) + err := result.Error + count := result.RowsAffected + return count, err +} +func (s *InboundService) UpdateClientStat(inboundId int, inboundSettings string) (error) { + db := database.GetDB() + + // get settings clients + settings := map[string][]model.Client{} + json.Unmarshal([]byte(inboundSettings), &settings) + clients := settings["clients"] + for _, client := range clients { + result := db.Model(xray.ClientTraffic{}). + Where("inbound_id = ? and email = ?", inboundId, client.Email). + Updates(map[string]interface{}{"enable": true, "total": client.TotalGB, "expiry_time": client.ExpiryTime}) + if result.RowsAffected == 0 { + clientTraffic := xray.ClientTraffic{} + clientTraffic.InboundId = inboundId + clientTraffic.Email = client.Email + clientTraffic.Total = client.TotalGB + clientTraffic.ExpiryTime = client.ExpiryTime + clientTraffic.Enable = true + clientTraffic.Up = 0 + clientTraffic.Down = 0 + db.Create(&clientTraffic) + } + err := result.Error + if err != nil { + return err + } + + } + return nil +} +func (s *InboundService) DelClientStat(tx *gorm.DB, email string) error { + return tx.Where("email = ?", email).Delete(xray.ClientTraffic{}).Error +} + +func (s *InboundService) ResetClientTraffic(clientEmail string) (error) { + db := database.GetDB() + + result := db.Model(xray.ClientTraffic{}). + Where("email = ?", clientEmail). + Update("up", 0). + Update("down", 0) + + err := result.Error + + + if err != nil { + return err + } + return nil +} +func (s *InboundService) GetClientTrafficById(uuid string) (traffic *xray.ClientTraffic, err error) { + db := database.GetDB() + inbound := &model.Inbound{} + traffic = &xray.ClientTraffic{} + + err = db.Model(model.Inbound{}).Where("settings like ?", "%" + uuid + "%").First(inbound).Error + if err != nil { + if err == gorm.ErrRecordNotFound { + logger.Warning(err) + return nil, err + } + } + traffic.InboundId = inbound.Id + + // get settings clients + settings := map[string][]model.Client{} + json.Unmarshal([]byte(inbound.Settings), &settings) + clients := settings["clients"] + for _, client := range clients { + if uuid == client.ID { + traffic.Email = client.Email + } + } + err = db.Model(xray.ClientTraffic{}).Where("email = ?", traffic.Email).First(traffic).Error + if err != nil { + logger.Warning(err) + return nil, err + } + return traffic, err +} diff --git a/web/service/panel.go b/web/service/panel.go new file mode 100644 index 00000000..f90d3e66 --- /dev/null +++ b/web/service/panel.go @@ -0,0 +1,26 @@ +package service + +import ( + "os" + "syscall" + "time" + "x-ui/logger" +) + +type PanelService struct { +} + +func (s *PanelService) RestartPanel(delay time.Duration) error { + p, err := os.FindProcess(syscall.Getpid()) + if err != nil { + return err + } + go func() { + time.Sleep(delay) + err := p.Signal(syscall.SIGHUP) + if err != nil { + logger.Error("send signal SIGHUP failed:", err) + } + }() + return nil +} diff --git a/web/service/server.go b/web/service/server.go new file mode 100644 index 00000000..efd985e6 --- /dev/null +++ b/web/service/server.go @@ -0,0 +1,302 @@ +package service + +import ( + "archive/zip" + "bytes" + "encoding/json" + "fmt" + "io" + "io/fs" + "net/http" + "os" + "runtime" + "time" + "x-ui/logger" + "x-ui/util/sys" + "x-ui/xray" + + "github.com/shirou/gopsutil/cpu" + "github.com/shirou/gopsutil/disk" + "github.com/shirou/gopsutil/host" + "github.com/shirou/gopsutil/load" + "github.com/shirou/gopsutil/mem" + "github.com/shirou/gopsutil/net" +) + +type ProcessState string + +const ( + Running ProcessState = "running" + Stop ProcessState = "stop" + Error ProcessState = "error" +) + +type Status struct { + T time.Time `json:"-"` + Cpu float64 `json:"cpu"` + Mem struct { + Current uint64 `json:"current"` + Total uint64 `json:"total"` + } `json:"mem"` + Swap struct { + Current uint64 `json:"current"` + Total uint64 `json:"total"` + } `json:"swap"` + Disk struct { + Current uint64 `json:"current"` + Total uint64 `json:"total"` + } `json:"disk"` + Xray struct { + State ProcessState `json:"state"` + ErrorMsg string `json:"errorMsg"` + Version string `json:"version"` + } `json:"xray"` + Uptime uint64 `json:"uptime"` + Loads []float64 `json:"loads"` + TcpCount int `json:"tcpCount"` + UdpCount int `json:"udpCount"` + NetIO struct { + Up uint64 `json:"up"` + Down uint64 `json:"down"` + } `json:"netIO"` + NetTraffic struct { + Sent uint64 `json:"sent"` + Recv uint64 `json:"recv"` + } `json:"netTraffic"` +} + +type Release struct { + TagName string `json:"tag_name"` +} + +type ServerService struct { + xrayService XrayService +} + +func (s *ServerService) GetStatus(lastStatus *Status) *Status { + now := time.Now() + status := &Status{ + T: now, + } + + percents, err := cpu.Percent(0, false) + if err != nil { + logger.Warning("get cpu percent failed:", err) + } else { + status.Cpu = percents[0] + } + + upTime, err := host.Uptime() + if err != nil { + logger.Warning("get uptime failed:", err) + } else { + status.Uptime = upTime + } + + memInfo, err := mem.VirtualMemory() + if err != nil { + logger.Warning("get virtual memory failed:", err) + } else { + status.Mem.Current = memInfo.Used + status.Mem.Total = memInfo.Total + } + + swapInfo, err := mem.SwapMemory() + if err != nil { + logger.Warning("get swap memory failed:", err) + } else { + status.Swap.Current = swapInfo.Used + status.Swap.Total = swapInfo.Total + } + + distInfo, err := disk.Usage("/") + if err != nil { + logger.Warning("get dist usage failed:", err) + } else { + status.Disk.Current = distInfo.Used + status.Disk.Total = distInfo.Total + } + + avgState, err := load.Avg() + if err != nil { + logger.Warning("get load avg failed:", err) + } else { + status.Loads = []float64{avgState.Load1, avgState.Load5, avgState.Load15} + } + + ioStats, err := net.IOCounters(false) + if err != nil { + logger.Warning("get io counters failed:", err) + } else if len(ioStats) > 0 { + ioStat := ioStats[0] + status.NetTraffic.Sent = ioStat.BytesSent + status.NetTraffic.Recv = ioStat.BytesRecv + + if lastStatus != nil { + duration := now.Sub(lastStatus.T) + seconds := float64(duration) / float64(time.Second) + up := uint64(float64(status.NetTraffic.Sent-lastStatus.NetTraffic.Sent) / seconds) + down := uint64(float64(status.NetTraffic.Recv-lastStatus.NetTraffic.Recv) / seconds) + status.NetIO.Up = up + status.NetIO.Down = down + } + } else { + logger.Warning("can not find io counters") + } + + status.TcpCount, err = sys.GetTCPCount() + if err != nil { + logger.Warning("get tcp connections failed:", err) + } + + status.UdpCount, err = sys.GetUDPCount() + if err != nil { + logger.Warning("get udp connections failed:", err) + } + + if s.xrayService.IsXrayRunning() { + status.Xray.State = Running + status.Xray.ErrorMsg = "" + } else { + err := s.xrayService.GetXrayErr() + if err != nil { + status.Xray.State = Error + } else { + status.Xray.State = Stop + } + status.Xray.ErrorMsg = s.xrayService.GetXrayResult() + } + status.Xray.Version = s.xrayService.GetXrayVersion() + + return status +} + +func (s *ServerService) GetXrayVersions() ([]string, error) { + url := "https://api.github.com/repos/XTLS/Xray-core/releases" + resp, err := http.Get(url) + if err != nil { + return nil, err + } + + defer resp.Body.Close() + buffer := bytes.NewBuffer(make([]byte, 8192)) + buffer.Reset() + _, err = buffer.ReadFrom(resp.Body) + if err != nil { + return nil, err + } + + releases := make([]Release, 0) + err = json.Unmarshal(buffer.Bytes(), &releases) + if err != nil { + return nil, err + } + versions := make([]string, 0, len(releases)) + for _, release := range releases { + versions = append(versions, release.TagName) + } + return versions, nil +} + +func (s *ServerService) downloadXRay(version string) (string, error) { + osName := runtime.GOOS + arch := runtime.GOARCH + + switch osName { + case "darwin": + osName = "macos" + } + + switch arch { + case "amd64": + arch = "64" + case "arm64": + arch = "arm64-v8a" + } + + fileName := fmt.Sprintf("Xray-%s-%s.zip", osName, arch) + url := fmt.Sprintf("https://github.com/XTLS/Xray-core/releases/download/%s/%s", version, fileName) + resp, err := http.Get(url) + if err != nil { + return "", err + } + defer resp.Body.Close() + + os.Remove(fileName) + file, err := os.Create(fileName) + if err != nil { + return "", err + } + defer file.Close() + + _, err = io.Copy(file, resp.Body) + if err != nil { + return "", err + } + + return fileName, nil +} + +func (s *ServerService) UpdateXray(version string) error { + zipFileName, err := s.downloadXRay(version) + if err != nil { + return err + } + + zipFile, err := os.Open(zipFileName) + if err != nil { + return err + } + defer func() { + zipFile.Close() + os.Remove(zipFileName) + }() + + stat, err := zipFile.Stat() + if err != nil { + return err + } + reader, err := zip.NewReader(zipFile, stat.Size()) + if err != nil { + return err + } + + s.xrayService.StopXray() + defer func() { + err := s.xrayService.RestartXray(true) + if err != nil { + logger.Error("start xray failed:", err) + } + }() + + copyZipFile := func(zipName string, fileName string) error { + zipFile, err := reader.Open(zipName) + if err != nil { + return err + } + os.Remove(fileName) + file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR|os.O_TRUNC, fs.ModePerm) + if err != nil { + return err + } + defer file.Close() + _, err = io.Copy(file, zipFile) + return err + } + + err = copyZipFile("xray", xray.GetBinaryPath()) + if err != nil { + return err + } + err = copyZipFile("geosite.dat", xray.GetGeositePath()) + if err != nil { + return err + } + err = copyZipFile("geoip.dat", xray.GetGeoipPath()) + if err != nil { + return err + } + + return nil + +} diff --git a/web/service/setting.go b/web/service/setting.go new file mode 100644 index 00000000..a0592e93 --- /dev/null +++ b/web/service/setting.go @@ -0,0 +1,303 @@ +package service + +import ( + _ "embed" + "errors" + "fmt" + "reflect" + "strconv" + "strings" + "time" + "x-ui/database" + "x-ui/database/model" + "x-ui/logger" + "x-ui/util/common" + "x-ui/util/random" + "x-ui/util/reflect_util" + "x-ui/web/entity" +) + +//go:embed config.json +var xrayTemplateConfig string + +var defaultValueMap = map[string]string{ + "xrayTemplateConfig": xrayTemplateConfig, + "webListen": "", + "webPort": "54321", + "webCertFile": "", + "webKeyFile": "", + "secret": random.Seq(32), + "webBasePath": "/", + "timeLocation": "Asia/Tehran", + "tgBotEnable": "false", + "tgBotToken": "", + "tgBotChatId": "0", + "tgRunTime": "", +} + +type SettingService struct { +} + +func (s *SettingService) GetAllSetting() (*entity.AllSetting, error) { + db := database.GetDB() + settings := make([]*model.Setting, 0) + err := db.Model(model.Setting{}).Find(&settings).Error + if err != nil { + return nil, err + } + allSetting := &entity.AllSetting{} + t := reflect.TypeOf(allSetting).Elem() + v := reflect.ValueOf(allSetting).Elem() + fields := reflect_util.GetFields(t) + + setSetting := func(key, value string) (err error) { + defer func() { + panicErr := recover() + if panicErr != nil { + err = errors.New(fmt.Sprint(panicErr)) + } + }() + + var found bool + var field reflect.StructField + for _, f := range fields { + if f.Tag.Get("json") == key { + field = f + found = true + break + } + } + + if !found { + // 有些设置自动生成,不需要返回到前端给用户修改 + return nil + } + + fieldV := v.FieldByName(field.Name) + switch t := fieldV.Interface().(type) { + case int: + n, err := strconv.ParseInt(value, 10, 64) + if err != nil { + return err + } + fieldV.SetInt(n) + case string: + fieldV.SetString(value) + case bool: + fieldV.SetBool(value == "true") + default: + return common.NewErrorf("unknown field %v type %v", key, t) + } + return + } + + keyMap := map[string]bool{} + for _, setting := range settings { + err := setSetting(setting.Key, setting.Value) + if err != nil { + return nil, err + } + keyMap[setting.Key] = true + } + + for key, value := range defaultValueMap { + if keyMap[key] { + continue + } + err := setSetting(key, value) + if err != nil { + return nil, err + } + } + + return allSetting, nil +} + +func (s *SettingService) ResetSettings() error { + db := database.GetDB() + return db.Where("1 = 1").Delete(model.Setting{}).Error +} + +func (s *SettingService) getSetting(key string) (*model.Setting, error) { + db := database.GetDB() + setting := &model.Setting{} + err := db.Model(model.Setting{}).Where("key = ?", key).First(setting).Error + if err != nil { + return nil, err + } + return setting, nil +} + +func (s *SettingService) saveSetting(key string, value string) error { + setting, err := s.getSetting(key) + db := database.GetDB() + if database.IsNotFound(err) { + return db.Create(&model.Setting{ + Key: key, + Value: value, + }).Error + } else if err != nil { + return err + } + setting.Key = key + setting.Value = value + return db.Save(setting).Error +} + +func (s *SettingService) getString(key string) (string, error) { + setting, err := s.getSetting(key) + if database.IsNotFound(err) { + value, ok := defaultValueMap[key] + if !ok { + return "", common.NewErrorf("key <%v> not in defaultValueMap", key) + } + return value, nil + } else if err != nil { + return "", err + } + return setting.Value, nil +} + +func (s *SettingService) setString(key string, value string) error { + return s.saveSetting(key, value) +} + +func (s *SettingService) getBool(key string) (bool, error) { + str, err := s.getString(key) + if err != nil { + return false, err + } + return strconv.ParseBool(str) +} + +func (s *SettingService) setBool(key string, value bool) error { + return s.setString(key, strconv.FormatBool(value)) +} + +func (s *SettingService) getInt(key string) (int, error) { + str, err := s.getString(key) + if err != nil { + return 0, err + } + return strconv.Atoi(str) +} + +func (s *SettingService) setInt(key string, value int) error { + return s.setString(key, strconv.Itoa(value)) +} + +func (s *SettingService) GetXrayConfigTemplate() (string, error) { + return s.getString("xrayTemplateConfig") +} + +func (s *SettingService) GetListen() (string, error) { + return s.getString("webListen") +} + +func (s *SettingService) GetTgBotToken() (string, error) { + return s.getString("tgBotToken") +} + +func (s *SettingService) SetTgBotToken(token string) error { + return s.setString("tgBotToken", token) +} + +func (s *SettingService) GetTgBotChatId() (int, error) { + return s.getInt("tgBotChatId") +} + +func (s *SettingService) SetTgBotChatId(chatId int) error { + return s.setInt("tgBotChatId", chatId) +} + +func (s *SettingService) SetTgbotenabled(value bool) error { + return s.setBool("tgBotEnable", value) +} + +func (s *SettingService) GetTgbotenabled() (bool, error) { + return s.getBool("tgBotEnable") +} + +func (s *SettingService) SetTgbotRuntime(time string) error { + return s.setString("tgRunTime", time) +} + +func (s *SettingService) GetTgbotRuntime() (string, error) { + return s.getString("tgRunTime") +} + +func (s *SettingService) GetPort() (int, error) { + return s.getInt("webPort") +} + +func (s *SettingService) SetPort(port int) error { + return s.setInt("webPort", port) +} + +func (s *SettingService) GetCertFile() (string, error) { + return s.getString("webCertFile") +} + +func (s *SettingService) GetKeyFile() (string, error) { + return s.getString("webKeyFile") +} + +func (s *SettingService) GetSecret() ([]byte, error) { + secret, err := s.getString("secret") + if secret == defaultValueMap["secret"] { + err := s.saveSetting("secret", secret) + if err != nil { + logger.Warning("save secret failed:", err) + } + } + return []byte(secret), err +} + +func (s *SettingService) GetBasePath() (string, error) { + basePath, err := s.getString("webBasePath") + if err != nil { + return "", err + } + if !strings.HasPrefix(basePath, "/") { + basePath = "/" + basePath + } + if !strings.HasSuffix(basePath, "/") { + basePath += "/" + } + return basePath, nil +} + +func (s *SettingService) GetTimeLocation() (*time.Location, error) { + l, err := s.getString("timeLocation") + if err != nil { + return nil, err + } + location, err := time.LoadLocation(l) + if err != nil { + defaultLocation := defaultValueMap["timeLocation"] + logger.Errorf("location <%v> not exist, using default location: %v", l, defaultLocation) + return time.LoadLocation(defaultLocation) + } + return location, nil +} + +func (s *SettingService) UpdateAllSetting(allSetting *entity.AllSetting) error { + if err := allSetting.CheckValid(); err != nil { + return err + } + + v := reflect.ValueOf(allSetting).Elem() + t := reflect.TypeOf(allSetting).Elem() + fields := reflect_util.GetFields(t) + errs := make([]error, 0) + for _, field := range fields { + key := field.Tag.Get("json") + fieldV := v.FieldByName(field.Name) + value := fmt.Sprint(fieldV.Interface()) + err := s.saveSetting(key, value) + if err != nil { + errs = append(errs, err) + } + } + return common.Combine(errs...) +} diff --git a/web/service/user.go b/web/service/user.go new file mode 100644 index 00000000..e4e7572d --- /dev/null +++ b/web/service/user.go @@ -0,0 +1,73 @@ +package service + +import ( + "errors" + "x-ui/database" + "x-ui/database/model" + "x-ui/logger" + + "gorm.io/gorm" +) + +type UserService struct { +} + +func (s *UserService) GetFirstUser() (*model.User, error) { + db := database.GetDB() + + user := &model.User{} + err := db.Model(model.User{}). + First(user). + Error + if err != nil { + return nil, err + } + return user, nil +} + +func (s *UserService) CheckUser(username string, password string) *model.User { + db := database.GetDB() + + user := &model.User{} + err := db.Model(model.User{}). + Where("username = ? and password = ?", username, password). + First(user). + Error + if err == gorm.ErrRecordNotFound { + return nil + } else if err != nil { + logger.Warning("check user err:", err) + return nil + } + return user +} + +func (s *UserService) UpdateUser(id int, username string, password string) error { + db := database.GetDB() + return db.Model(model.User{}). + Where("id = ?", id). + Update("username", username). + Update("password", password). + Error +} + +func (s *UserService) UpdateFirstUser(username string, password string) error { + if username == "" { + return errors.New("username can not be empty") + } else if password == "" { + return errors.New("password can not be empty") + } + db := database.GetDB() + user := &model.User{} + err := db.Model(model.User{}).First(user).Error + if database.IsNotFound(err) { + user.Username = username + user.Password = password + return db.Model(model.User{}).Create(user).Error + } else if err != nil { + return err + } + user.Username = username + user.Password = password + return db.Save(user).Error +} diff --git a/web/service/xray.go b/web/service/xray.go new file mode 100644 index 00000000..37fd3b05 --- /dev/null +++ b/web/service/xray.go @@ -0,0 +1,163 @@ +package service + +import ( + "encoding/json" + "errors" + "sync" + "x-ui/logger" + "x-ui/xray" + "go.uber.org/atomic" +) + +var p *xray.Process +var lock sync.Mutex +var isNeedXrayRestart atomic.Bool +var result string + +type XrayService struct { + inboundService InboundService + settingService SettingService +} + +func (s *XrayService) IsXrayRunning() bool { + return p != nil && p.IsRunning() +} + +func (s *XrayService) GetXrayErr() error { + if p == nil { + return nil + } + return p.GetErr() +} + +func (s *XrayService) GetXrayResult() string { + if result != "" { + return result + } + if s.IsXrayRunning() { + return "" + } + if p == nil { + return "" + } + result = p.GetResult() + return result +} + +func (s *XrayService) GetXrayVersion() string { + if p == nil { + return "Unknown" + } + return p.GetVersion() +} +func RemoveIndex(s []interface{}, index int) []interface{} { + return append(s[:index], s[index+1:]...) +} + +func (s *XrayService) GetXrayConfig() (*xray.Config, error) { + templateConfig, err := s.settingService.GetXrayConfigTemplate() + if err != nil { + return nil, err + } + + xrayConfig := &xray.Config{} + err = json.Unmarshal([]byte(templateConfig), xrayConfig) + if err != nil { + return nil, err + } + + s.inboundService.DisableInvalidClients() + + inbounds, err := s.inboundService.GetAllInbounds() + if err != nil { + return nil, err + } + for _, inbound := range inbounds { + if !inbound.Enable { + continue + } + // get settings clients + settings := map[string]interface{}{} + json.Unmarshal([]byte(inbound.Settings), &settings) + clients, ok := settings["clients"].([]interface{}) + if ok { + // check users active or not + + clientStats := inbound.ClientStats + for _, clientTraffic := range clientStats { + + for index, client := range clients { + c := client.(map[string]interface{}) + if c["email"] == clientTraffic.Email { + if ! clientTraffic.Enable { + clients = RemoveIndex(clients,index) + logger.Info("Remove Inbound User",c["email"] ,"due the expire or traffic limit") + + } + + } + } + + + } + settings["clients"] = clients + modifiedSettings, err := json.Marshal(settings) + if err != nil { + return nil, err + } + + inbound.Settings = string(modifiedSettings) + } + inboundConfig := inbound.GenXrayInboundConfig() + xrayConfig.InboundConfigs = append(xrayConfig.InboundConfigs, *inboundConfig) + } + return xrayConfig, nil +} + +func (s *XrayService) GetXrayTraffic() ([]*xray.Traffic, []*xray.ClientTraffic, error) { + if !s.IsXrayRunning() { + return nil, nil, errors.New("xray is not running") + } + return p.GetTraffic(true) +} + +func (s *XrayService) RestartXray(isForce bool) error { + lock.Lock() + defer lock.Unlock() + logger.Debug("restart xray, force:", isForce) + + xrayConfig, err := s.GetXrayConfig() + if err != nil { + return err + } + + if p != nil && p.IsRunning() { + if !isForce && p.GetConfig().Equals(xrayConfig) { + logger.Debug("not need to restart xray") + return nil + } + p.Stop() + } + + p = xray.NewProcess(xrayConfig) + result = "" + return p.Start() +} + +func (s *XrayService) StopXray() error { + lock.Lock() + defer lock.Unlock() + logger.Debug("stop xray") + if s.IsXrayRunning() { + return p.Stop() + } + return errors.New("xray is not running") +} + +func (s *XrayService) SetToNeedRestart() { + isNeedXrayRestart.Store(true) +} + +func (s *XrayService) IsNeedRestartAndSetFalse() bool { + return isNeedXrayRestart.CAS(true, false) +} diff --git a/web/session/session.go b/web/session/session.go new file mode 100644 index 00000000..2dfe94b6 --- /dev/null +++ b/web/session/session.go @@ -0,0 +1,46 @@ +package session + +import ( + "encoding/gob" + "github.com/gin-contrib/sessions" + "github.com/gin-gonic/gin" + "x-ui/database/model" +) + +const ( + loginUser = "LOGIN_USER" +) + +func init() { + gob.Register(model.User{}) +} + +func SetLoginUser(c *gin.Context, user *model.User) error { + s := sessions.Default(c) + s.Set(loginUser, user) + return s.Save() +} + +func GetLoginUser(c *gin.Context) *model.User { + s := sessions.Default(c) + obj := s.Get(loginUser) + if obj == nil { + return nil + } + user := obj.(model.User) + return &user +} + +func IsLogin(c *gin.Context) bool { + return GetLoginUser(c) != nil +} + +func ClearSession(c *gin.Context) { + s := sessions.Default(c) + s.Clear() + s.Options(sessions.Options{ + Path: "/", + MaxAge: -1, + }) + s.Save() +} diff --git a/web/translation/translate.en_US.toml b/web/translation/translate.en_US.toml new file mode 100644 index 00000000..eb31af3b --- /dev/null +++ b/web/translation/translate.en_US.toml @@ -0,0 +1,192 @@ +"username" = "username" +"password" = "password" +"login" = "login" +"confirm" = "confirm" +"cancel" = "cancel" +"close" = "close" +"copy" = "copy" +"copied" = "copied" +"download" = "download" +"remark" = "remark" +"enable" = "enable" +"protocol" = "protocol" + +"loading" = "Loading" +"second" = "second" +"minute" = "minute" +"hour" = "hour" +"day" = "day" +"check" = "check" +"indefinite" = "indefinite" +"unlimited" = "unlimited" +"none" = "none" +"qrCode" = "QR Code" +"edit" = "edit" +"delete" = "delete" +"reset" = "reset" +"copySuccess" = "Copy successfully" +"sure" = "Sure" +"encryption" = "encryption" +"transmission" = "transmission" +"host" = "host" +"path" = "path" +"camouflage" = "camouflage" +"turnOn" = "turn on" +"closure" = "closure" +"domainName" = "domain name" +"additional" = "alter" +"monitor" = "Listen IP" +"certificate" = "certificat" +"fail" = "fail" +"success" = " success" +"getVersion" = "get version" +"install" = "install" +"used" = "used" + +[menu] +"dashboard" = "System Status" +"inbounds" = "Inbounds" +"setting" = "Panel Setting" +"logout" = "LogOut" +"link" = "Other" + +[pages.login] +"title" = "Login" +"loginAgain" = "The login time limit has expired, please log in again" + +[pages.login.toasts] +"invalidFormData" = "Input Data Format Is Invalid" +"emptyUsername" = "please Enter Username" +"emptyPassword" = "please Enter Password" +"wrongUsernameOrPassword" = "invalid username or password" +"successLogin" = "Login" + + +[pages.index] +"title" = "system status" +"memory" = "memory" +"hard" = "hard disk" +"xrayStatus" = "xray Status" +"xraySwitch" = "Switch Version" +"xraySwitchClick" = "Click on the version you want to switch" +"xraySwitchClickDesk" = "Please choose carefully, older versions may have incompatible configurations" +"operationHours" = "Operation Hours" +"operationHoursDesc" = "The running time of the system since it was started" +"systemLoad" = "System Load" +"connectionCount" = "Connection Count" +"connectionCountDesc" = "The total number of connections for all network cards" +"upSpeed" = "Total upload speed for all network cards" +"downSpeed" = "Total download speed for all network cards" +"totalSent" = "Total upload traffic of all network cards since system startup" +"totalReceive" = "Total download traffic of all network cards since system startup" +"xraySwitchVersionDialog" = "switch xray version" +"xraySwitchVersionDialogDesc" = "whether to switch the xray version to" +"dontRefreshh" = "Installation is in progress, please do not refresh this page" + + +[pages.inbounds] +"title" = "Inbounds" +"totalDownUp" = "Total uploads/downloads" +"totalUsage" = "Total usage" +"inboundCount" = "Number of inbound" +"operate" = "Actions" +"enable" = "enable" +"remark" = "remark" +"protocol" = "protocol" +"port" = "port" +"traffic" = "traffic" +"details" = "details" +"transportConfig" = "transport config" +"expireDate" = "expire date" +"resetTraffic" = "reset traffic" +"addInbound" = "addInbound" +"addTo" = "Add To" +"revise" = "Revise" +"modifyInbound" = "Modify InBound" +"deleteInbound" = "Delete Inbound" +"deleteInboundContent" = "Are you sure you want to delete inbound?" +"resetTrafficContent" = "Are you sure you want to reset traffic?" +"copyLink" = "Copy Link" +"address" = "address" +"network" = "network" +"destinationPort" = "destination port" +"targetAddress" = "target address" +"disableInsecureEncryption" = "Disable insecure encryption" +"monitorDesc" = "Leave blank by default" +"meansNoLimit" = "means no limit" +"totalFlow" = "total flow" +"leaveBlankToNeverExpire" = "Leave blank to never expire" +"noRecommendKeepDefault" = "There are no special requirements to keep the default" +"certificatePath" = "certificate file path" +"certificateContent" = "certificate file content" +"publicKeyPath" = "public key file path" +"publicKeyContent" = "public key content" +"keyPath" = "key file path" +"keyContent" = "key content" +"client" = "Client" +"uid" = "UID" + +[pages.inbounds.toasts] +"obtain" = "Obtain" + +[pages.inbounds.stream.general] +"requestHeader" = "request header" +"name" = "name" +"value" = "value" + +[pages.inbounds.stream.tcp] +"requestVersion" = "request version" +"requestMethod" = "request method" +"requestPath" = "request path" +"responseVersion" = "response version" +"responseStatus" = "response status" +"responseStatusDescription" = "response status description" +"responseHeader" = "response header" + +[pages.inbounds.stream.quic] +"encryption" = "encryption" + + +[pages.setting] +"title" = "Setting" +"save" = "Save" +"restartPanel" = "Restart Panel" +"restartPanelDesc" = "Are you sure you want to restart the panel? Click OK to restart after 3 seconds. If you cannot access the panel after restarting, please go to the server to view the panel log information" +"panelConfig" = "Panel Configuration" +"userSetting" = "User Setting" +"xrayConfiguration" = "xray Configuration" +"TGReminder" = "TG Reminder Related Settings" +"otherSetting" = "Other Setting" +"panelListeningIP" = "Panel listening IP" +"panelListeningIPDesc" = "Leave blank by default to monitor all IPs, restart the panel to take effect" +"panelPort" = "Panel Port" +"panelPortDesc" = "Restart the panel to take effect" +"publicKeyPath" = "Panel certificate public key file path" +"publicKeyPathDesc" = "Fill in an absolute path starting with '/', restart the panel to take effect" +"privateKeyPath" = "Panel certificate key file path" +"privateKeyPathDesc" = "Fill in an absolute path starting with '/', restart the panel to take effect" +"panelUrlPath" = "panel url root path" +"panelUrlPathDesc" = "Must start with '/' and end with '/', restart the panel to take effect" +"oldUsername" = "Current Username" +"currentPassword" = "Current Password" +"newUsername" = "New Username" +"newPassword" = "New Password" +"xrayConfigTemplate" = "xray Configuration Template" +"xrayConfigTemplateDesc" = "Generate the final xray configuration file based on this template, restart the panel to take effect" +"telegramBotEnable" = "Enable telegram bot" +"telegramBotEnableDesc" = "Restart the panel to take effect" +"telegramToken" = "Telegram Token" +"telegramTokenDesc" = "Restart the panel to take effect" +"telegramChatId" = "Telegram ChatId" +"telegramChatIdDesc" = "Restart the panel to take effect" +"telegramNotifyTime" = "Telegram bot notification time" +"telegramNotifyTimeDesc" = "Using Crontab timing format, restart the panel to take effect" +"timeZonee" = "Time Zone" +"timeZoneDesc" = "The scheduled task runs according to the time in the time zone, and restarts the panel to take effect" + +[pages.setting.toasts] +"modifySetting" = "modify setting" +"getSetting" = "get setting" +"modifyUser" = "modify user" +"originalUserPassIncorrect" = "The original user name or original password is incorrect" +"userPassMustBeNotEmpty" = "New username and new password cannot be empty" \ No newline at end of file diff --git a/web/translation/translate.fa_IR.toml b/web/translation/translate.fa_IR.toml new file mode 100644 index 00000000..538bcb08 --- /dev/null +++ b/web/translation/translate.fa_IR.toml @@ -0,0 +1,191 @@ +"username" = "نام کاربری" +"password" = "رمز عبور" +"login" = "ورود" +"confirm" = "تایید" +"cancel" = "انصراف" +"close" = "بستن" +"copy" = "کپی" +"copied" = "کپی شد" +"download" = "دانلود" +"remark" = "نام" +"enable" = "فعال" +"protocol" = "پروتکل" + +"loading" = "در حال بروزرسانی..." +"second" = "ثانیه" +"minute" = "دقیقه" +"hour" = "ساعت" +"day" = "روز" +"check" = "چک کردن" +"indefinitely" = "نامحدود" +"unlimited" = "نامحدود" +"none" = "هیچ" +"qrCode" = "QR کد" +"edit" = "ویرایش" +"delete" = "حذف" +"reset" = "ریست" +"copySuccess" = "با موفقیت کپی شد" +"sure" = "مطمئن" +"encryption" = "رمزگذاری" +"transmission" = "راه اتصال" +"host" = "آدرس" +"path" = "مسیر" +"camouflage" = "استتار" +"enabled" = "فعال" +"disabled" = "disabled" +"domainName" = "آدرس دامنه" +"additional" = "آی دی جایگزین" +"monitor" = "آی پی اتصال" +"certificate" = "سرتیفیکیت" +"fail" = "خطا" +"success" = " موفق" +"getVersion" = "دریافت ورژن" +"install" = "نصب" +"clients" = "کاربران" + +[menu] +"dashboard" = "وضعیت سیستم" +"inbounds" = "سروریس ها" +"setting" = "تنظیمات پنل" +"logout" = "خروج" +"link" = "دیگر" + +[pages.login] +"title" = "ورود به سیستم X-UI" +"loginAgain" = "مدت زمان استفاده به اتمام رسیده ، لطفا دوباره وارد شوید" + +[pages.login.toasts] +"invalidFormData" = "اطلاعات وارد شده به صورت درست وارد نشده است" +"emptyUsername" = "نام کاربری خالی میباشد" +"emptyPassword" = "رمز عبور خالی میباشد" +"wrongUsernameOrPassword" = "نام کاربری و رمز عبور اشتباه میباشد" +"successLogin" = "خوش آمدید" + + +[pages.index] +"title" = "وضعیت سیستم" +"memory" = "حافظه رم" +"hard" = "حافظه دیسک" +"xrayStatus" = "وضعیت Xray" +"xraySwitch" = "تغییر ورژن" +"xraySwitchClick" = "ورژن مورد نظر را انتخاب کنید" +"xraySwitchClickDesk" = "لطفا با دقت انتخاب کنید ، در صورت انتخاب اشتباه امکان قطعی سیستم وجود دارد ." +"operationHours" = "ساعت فعال" +"operationHoursDesc" = "ساعت فعال بعد از شروع سیستم" +"systemLoad" = "سرعت لود سیستم" +"connectionCount" = "تعداد کانکشن ها" +"connectionCountDesc" = "تعداد کانکشن ها برای کل شبکه" +"upSpeed" = "سرعت آپلود در حال حاضر سیستم" +"downSpeed" = "سرعت دانلود در حال حاضر سیستم" +"totalSent" = "جمع کل ترافیک آپلود مصرفی" +"totalReceive" = "جمع کل ترافیک دانلود مصرفی" +"xraySwitchVersionDialog" = "تغییر ورژن Xray" +"xraySwitchVersionDialogDesc" = "آیا از تغییر ورژن مطمئن هستین" +"dontRefreshh" = "در حال نصب ، لطفا رفرش نکنید " + + +[pages.inbounds] +"title" = "کاربران" +"totalDownUp" = "جمع آپلود/دانلود" +"totalUsage" = "جمع کل" +"inboundCount" = "تعداد سرویس ها" +"operate" = "عملیات" +"enable" = "فعال" +"remark" = "نام" +"protocol" = "پروتکل" +"port" = "پورت" +"traffic" = "ترافیک" +"details" = "توضیحات" +"transportConfig" = "نحوه اتصال" +"expireDate" = "تاریخ انقضا" +"resetTraffic" = "ریست ترافیک" +"addInbound" = "اضافه کردن سرویس" +"addTo" = "اضافه کردن" +"revise" = "ویرایش" +"modifyInbound" = "ویرایش سرویس" +"deleteInbound" = "حذف سرویس" +"deleteInboundContent" = "آیا مطمئن به حذف سرویس هستید ؟" +"resetTrafficContent" = "آیا مطمئن به ریست ترافیک هستید ؟" +"copyLink" = "کپی لینک" +"address" = "آدرس" +"network" = "شبکه" +"destinationPort" = "پورت مقصد" +"targetAddress" = "آدرس مقصد" +"disableInsecureEncryption" = "رمزگذاری ناامن را غیرفعال کنید" +"monitorDesc" = "به طور پیش فرض خالی بگذارید" +"meansNoLimit" = "یعنی بدون محدودیت" +"totalFlow" = "کل ترافیک" +"leaveBlankToNeverExpire" = "خالی بگذارید تا هرگز منقضی نشود" +"noRecommendKeepDefault" = "توصیه می شود به عنوان پیش فرض حفظ شود" +"certificatePath" = "مسیر فایل گواهی" +"certificateContent" = "محتوای فایل گواهی" +"publicKeyPath" = "مسیر فایل Certificate.crt" +"publicKeyContent" = "محتوای Certificate.crt" +"keyPath" = "مسیر فایل Private.key" +"keyContent" = "محتوای Private.key" +"clickOnQRcode" = "برای کپی بر روی کد تصویری کلیک کنید" + +[pages.inbounds.toasts] +"obtain" = "Obtain" + +[pages.inbounds.stream.general] +"requestHeader" = "درخواست سربرگ" +"name" = "نام" +"value" = "مقدار" + +[pages.inbounds.stream.tcp] +"requestVersion" = "ورژن درخواست" +"requestMethod" = "متد درخواست" +"requestPath" = "مسیر درخواست" +"responseVersion" = "ورژن پاسخ" +"responseStatus" = "وضعیت پاسخ" +"responseStatusDescription" = "توضیحات وضعیت پاسخ" +"responseHeader" = "سربرگ پاسخ" + +[pages.inbounds.stream.quic] +"encryption" = "رمزنگاری" + + +[pages.setting] +"title" = "تنظیمات" +"save" = "ذخیره" +"restartPanel" = "ریستارت پنل" +"restartPanelDesc" = "آیا مطمئن هستید که می خواهید پنل را دوباره راه اندازی کنید؟ برای راه اندازی مجدد روی OK کلیک کنید. اگر بعد از 3 ثانیه نمی توانید به پنل دسترسی پیدا کنید، لطفاً برای مشاهده اطلاعات گزارش پانل به سرور برگردید" +"panelConfig" = "تنظیمات پنل" +"userSetting" = "تنظیمات مدیر" +"xrayConfiguration" = "تنظیمات Xray" +"TGReminder" = "تنظیمات ربات تلگرام" +"otherSetting" = "دیگر تنظیمات" +"panelListeningIP" = "محدودیت آی پی پنل" +"panelListeningIPDesc" = "برای استفاده از تمام IP ها به طور پیش فرض خالی بگذارید. پنل را مجدداً راه اندازی کنید تا اعمال شود" +"panelPort" = "پورت پنل" +"panelPortDesc" = "پنل را مجدداً راه اندازی کنید تا اعمال شود" +"publicKeyPath" = "مسیر فایل پنل Certificate.crt" +"publicKeyPathDesc" = "باید یک مسیر مطلق باشد که با / شروع می شود . پنل را مجدداً راه اندازی کنید تا اعمال شود" +"privateKeyPath" = "مسیر فایل پنل private.key" +"privateKeyPathDesc" = "باید یک مسیر مطلق باشد که با / شروع می شود . پنل را مجدداً راه اندازی کنید تا اعمال شود" +"panelUrlPath" = "آدرس روت پنل" +"panelUrlPathDesc" = "باید با '/' شروع شود و با '/' تمام شود. پنل را مجدداً راه اندازی کنید تا اعمال شود" +"oldUsername" = "نام کاربری فعلی" +"currentPassword" = "رمز عبور فعلی" +"newUsername" = "نام کاربری جدید" +"newPassword" = "رمز عبور جدید" +"xrayConfigTemplate" = "تنظیمات قالب Xray" +"xrayConfigTemplateDesc" = "فایل پیکربندی xray نهایی را بر اساس این الگو ایجاد کنید. لطفاً این را تغییر ندهید مگر اینکه دقیقاً بدانید که چه کاری انجام می دهید! پنل را مجدداً راه اندازی کنید تا اعمال شود" +"telegramBotEnable" = "فعالسازی ربات تلگرام" +"telegramBotEnableDesc" = "پنل را مجدداً راه اندازی کنید تا اعمال شود" +"telegramToken" = "توکن تلگرام" +"telegramTokenDesc" = "پنل را مجدداً راه اندازی کنید تا اعمال شود" +"telegramChatId" = "آی دی تلگرام مدیریت . از ربات @getidsbot آی دی خود را دریافت کنید" +"telegramChatIdDesc" = "پنل را مجدداً راه اندازی کنید تا اعمال شود" +"telegramNotifyTime" = "مدت زمان نوتیفیکیشن ربات تلگرام" +"telegramNotifyTimeDesc" = "از فرمت زمان بندی Crontab استفاده کنید . پنل را مجدداً راه اندازی کنید تا اعمال شود" +"timeZonee" = "منظقه زمانی" +"timeZoneDesc" = "وظایف برنامه ریزی شده بر اساس این منطقه زمانی اجرا می شوند. پنل را مجدداً راه اندازی می کند تا اعمال شود" + +[pages.setting.toasts] +"modifySetting" = "ویرایش تنظیمات" +"getSetting" = "دریافت تنظیمات" +"modifyUser" = "ویرایش کاربر" +"originalUserPassIncorrect" = "نام کاربری و رمز عبور فعلی اشتباه می باشد ." +"userPassMustBeNotEmpty" = "نام کاربری و رمز عبور جدید نمیتواند خالی باشد ." \ No newline at end of file diff --git a/web/translation/translate.zh_Hans.toml b/web/translation/translate.zh_Hans.toml new file mode 100644 index 00000000..b219c8b6 --- /dev/null +++ b/web/translation/translate.zh_Hans.toml @@ -0,0 +1,191 @@ +"username" = "用户名" +"password" = "密码" +"login" = "登录" +"confirm" = "确定" +"cancel" = "取消" +"close" = "关闭" +"copy" = "复制" +"copied" = "已复制" +"download" = "下载" +"remark" = "备注" +"enable" = "启用" +"protocol" = "协议" + +"loading" = "加载中" +"second" = "秒" +"minute" = "分钟" +"hour" = "小时" +"day" = "天" +"check" = "查看" +"indefinitely" = "无限期" +"unlimited" = "无限制" +"none" = "无" +"qrCode" = "二维码" +"edit" = "编辑" +"delete" = "删除" +"reset" = "重置" +"copySuccess" = "复制成功" +"sure" = "确定" +"encryption" = "加密" +"transmission" = "传输" +"host" = "主持人" +"path" = "小路" +"camouflage" = "伪装" +"enabled" = "开启" +"disabled" = "关闭" +"domainName" = "域名" +"additional" = "额外" +"monitor" = "监听" +"certificate" = "证书" +"fail" = "失败" +"success" = "成功" +"getVersion" = "获取版本" +"install" = "安装" +"clients" = "客户端" + +[menu] +"dashboard" = "系统状态" +"inbounds" = "入站列表" +"setting" = "面板设置" +"logout" = "退出登录" +"link" = "其他" + +[pages.login] +"title" = "登录" +"loginAgain" = "登录时效已过,请重新登录" + +[pages.login.toasts] +"invalidFormData" = "数据格式错误" +"emptyUsername" = "请输入用户名" +"emptyPassword" = "请输入密码" +"wrongUsernameOrPassword" = "用户名或密码错误" +"successLogin" = "登录" + +[pages.index] +"title" = "系统状态" +"memory" = "内存" +"hard" = "硬盘" +"xrayStatus" = "xray 状态" +"xraySwitch" = "切换版本" +"xraySwitchClick" = "点击你想切换的版本" +"xraySwitchClickDesk" = "请谨慎选择,旧版本可能配置不兼容" +"operationHours" = "运行时间" +"operationHoursDesc" = "系统自启动以来的运行时间" +"systemLoad" = "系统负载" +"connectionCount" = "连接数" +"connectionCountDesc" = "所有网卡的总连接数" +"upSpeed" = "所有网卡的总上传速度" +"downSpeed" = "所有网卡的总下载速度" +"totalSent" = "系统启动以来所有网卡的总上传流量" +"totalReceive" = "系统启动以来所有网卡的总下载流量" +"xraySwitchVersionDialog" = "切换 xray 版本" +"xraySwitchVersionDialogDesc" = "是否切换 xray 版本至" +"dontRefreshh" = "安装中,请不要刷新此页面" + + +[pages.inbounds] +"title" = "入站列表" +"totalDownUp" = "总上传 / 下载" +"totalUsage" = "总用量" +"inboundCount" = "入站数量" +"operate" = "操作" +"enable" = "启用" +"remark" = "备注" +"protocol" = "协议" +"port" = "端口" +"traffic" = "流量" +"details" = "详细信息" +"transportConfig" = "传输配置" +"expireDate" = "到期时间" +"resetTraffic" = "重置流量" +"addInbound" = "添加入" +"addTo" = "添加" +"revise" = "修改" +"modifyInbound" = "修改入站" +"deleteInbound" = "删除入站" +"deleteInboundContent" = "确定要删除入站吗?" +"resetTrafficContent" = "确定要重置流量吗?" +"copyLink" = "复制链接" +"address" = "地址" +"network" = "网络" +"destinationPort" = "目标端口" +"targetAddress" = "目标地址" +"disableInsecureEncryption" = "禁用不安全加密" +"monitorDesc" = "默认留空即可" +"meansNoLimit" = "表示不限制" +"totalFlow" = "总流量" +"leaveBlankToNeverExpire" = "留空则永不到期" +"noRecommendKeepDefault" = "没有特殊需求保持默认即可" +"certificatePath" = "证书文件路径" +"certificateContent" = "证书文件内容" +"publicKeyPath" = "公钥文件路径" +"publicKeyContent" = "公钥内容" +"keyPath" = "密钥文件路径" +"keyContent" = "密钥内容" +"clickOnQRcode" = "click on QR Code to Copy" + +[pages.inbounds.toasts] +"obtain" = "获取" + +[pages.inbounds.stream.general] +"requestHeader" = "请求头" +"name" = "名称" +"value" = "值" + +[pages.inbounds.stream.tcp] +"requestVersion" = "请求版本" +"requestMethod" = "请求方法" +"requestPath" = "请求路径" +"responseVersion" = "响应版本" +"responseStatus" = "响应状态" +"responseStatusDescription" = "响应状态说明" +"responseHeader" = "响应头" + +[pages.inbounds.stream.quic] +"encryption" = "加密" + + +[pages.setting] +"title" = "设置" +"save" = "保存配置" +"restartPanel" = "重启面板" +"restartPanelDesc" = "确定要重启面板吗?点击确定将于 3 秒后重启,若重启后无法访问面板,请前往服务器查看面板日志信息" +"panelConfig" = "面板配置" +"userSetting" = "用户设置" +"xrayConfiguration" = "xray 相关设置" +"TGReminder" = "TG提醒相关设置" +"otherSetting" = "其他设置" +"panelListeningIP" = "面板监听 IP" +"panelListeningIPDesc" = "默认留空监听所有 IP,重启面板生效" +"panelPort" = "面板监听端口" +"panelPortDesc" = "重启面板生效" +"publicKeyPath" = "面板证书公钥文件路径" +"publicKeyPathDesc" = "填写一个 '/' 开头的绝对路径,重启面板生效" +"privateKeyPath" = "面板证书密钥文件路径" +"privateKeyPathDesc" = "填写一个 '/' 开头的绝对路径,重启面板生效" +"panelUrlPath" = "面板 url 根路径" +"panelUrlPathDesc" = "必须以 '/' 开头,以 '/' 结尾,重启面板生效" +"oldUsername" = "原用户名" +"currentPassword" = "原密码" +"newUsername" = "新用户名" +"newPassword" = "新密码" +"xrayConfigTemplate" = "xray 配置模版" +"xrayConfigTemplateDesc" = "以该模版为基础生成最终的 xray 配置文件,重启面板生效" +"telegramBotEnable" = "启用电报机器人" +"telegramBotEnableDesc" = "重启面板生效" +"telegramToken" = "电报机器人TOKEN" +"telegramTokenDesc" = "重启面板生效" +"telegramChatId" = "电报机器人ChatId" +"telegramChatIdDesc" = "重启面板生效" +"telegramNotifyTime" = "电报机器人通知时间" +"telegramNotifyTimeDesc" = "采用Crontab定时格式,重启面板生效" +"timeZonee" = "时区" +"timeZoneDesc" = "定时任务按照该时区的时间运行,重启面板生效" + +[pages.setting.toasts] +"modifySetting" = "修改设置" +"getSetting" = "获取设置" +"modifyUser" = "修改用户" +"originalUserPassIncorrect" = "原用户名或原密码错误" +"userPassMustBeNotEmpty" = "新用户名和新密码不能为空" + diff --git a/web/web.go b/web/web.go new file mode 100644 index 00000000..383203b6 --- /dev/null +++ b/web/web.go @@ -0,0 +1,432 @@ +package web + +import ( + "context" + "crypto/tls" + "embed" + "html/template" + "io" + "io/fs" + "net" + "net/http" + "os" + "strconv" + "strings" + "time" + "x-ui/config" + "x-ui/logger" + "x-ui/util/common" + "x-ui/web/controller" + "x-ui/web/job" + "x-ui/web/network" + "x-ui/web/service" + + "github.com/BurntSushi/toml" + "github.com/gin-contrib/sessions" + "github.com/gin-contrib/sessions/cookie" + "github.com/gin-gonic/gin" + "github.com/nicksnyder/go-i18n/v2/i18n" + "github.com/robfig/cron/v3" + "golang.org/x/text/language" +) + +//go:embed assets/* +var assetsFS embed.FS + +//go:embed html/* +var htmlFS embed.FS + +//go:embed translation/* +var i18nFS embed.FS + +var startTime = time.Now() + +type wrapAssetsFS struct { + embed.FS +} + +func (f *wrapAssetsFS) Open(name string) (fs.File, error) { + file, err := f.FS.Open("assets/" + name) + if err != nil { + return nil, err + } + return &wrapAssetsFile{ + File: file, + }, nil +} + +type wrapAssetsFile struct { + fs.File +} + +func (f *wrapAssetsFile) Stat() (fs.FileInfo, error) { + info, err := f.File.Stat() + if err != nil { + return nil, err + } + return &wrapAssetsFileInfo{ + FileInfo: info, + }, nil +} + +type wrapAssetsFileInfo struct { + fs.FileInfo +} + +func (f *wrapAssetsFileInfo) ModTime() time.Time { + return startTime +} + +type Server struct { + httpServer *http.Server + listener net.Listener + + index *controller.IndexController + server *controller.ServerController + xui *controller.XUIController + api *controller.APIController + + xrayService service.XrayService + settingService service.SettingService + inboundService service.InboundService + + cron *cron.Cron + + ctx context.Context + cancel context.CancelFunc +} + +func NewServer() *Server { + ctx, cancel := context.WithCancel(context.Background()) + return &Server{ + ctx: ctx, + cancel: cancel, + } +} + +func (s *Server) getHtmlFiles() ([]string, error) { + files := make([]string, 0) + dir, _ := os.Getwd() + err := fs.WalkDir(os.DirFS(dir), "web/html", func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + return nil + } + files = append(files, path) + return nil + }) + if err != nil { + return nil, err + } + return files, nil +} + +func (s *Server) getHtmlTemplate(funcMap template.FuncMap) (*template.Template, error) { + t := template.New("").Funcs(funcMap) + err := fs.WalkDir(htmlFS, "html", func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + + if d.IsDir() { + newT, err := t.ParseFS(htmlFS, path+"/*.html") + if err != nil { + // ignore + return nil + } + t = newT + } + return nil + }) + if err != nil { + return nil, err + } + return t, nil +} + +func (s *Server) initRouter() (*gin.Engine, error) { + if config.IsDebug() { + gin.SetMode(gin.DebugMode) + } else { + gin.DefaultWriter = io.Discard + gin.DefaultErrorWriter = io.Discard + gin.SetMode(gin.ReleaseMode) + } + + engine := gin.Default() + + secret, err := s.settingService.GetSecret() + if err != nil { + return nil, err + } + + basePath, err := s.settingService.GetBasePath() + if err != nil { + return nil, err + } + assetsBasePath := basePath + "assets/" + + store := cookie.NewStore(secret) + engine.Use(sessions.Sessions("session", store)) + engine.Use(func(c *gin.Context) { + c.Set("base_path", basePath) + }) + engine.Use(func(c *gin.Context) { + uri := c.Request.RequestURI + if strings.HasPrefix(uri, assetsBasePath) { + c.Header("Cache-Control", "max-age=31536000") + } + }) + err = s.initI18n(engine) + if err != nil { + return nil, err + } + + if config.IsDebug() { + // for develop + files, err := s.getHtmlFiles() + if err != nil { + return nil, err + } + engine.LoadHTMLFiles(files...) + engine.StaticFS(basePath+"assets", http.FS(os.DirFS("web/assets"))) + } else { + // for prod + t, err := s.getHtmlTemplate(engine.FuncMap) + if err != nil { + return nil, err + } + engine.SetHTMLTemplate(t) + engine.StaticFS(basePath+"assets", http.FS(&wrapAssetsFS{FS: assetsFS})) + } + + g := engine.Group(basePath) + + s.index = controller.NewIndexController(g) + s.server = controller.NewServerController(g) + s.xui = controller.NewXUIController(g) + s.api = controller.NewAPIController(g) + + return engine, nil +} + +func (s *Server) initI18n(engine *gin.Engine) error { + bundle := i18n.NewBundle(language.SimplifiedChinese) + bundle.RegisterUnmarshalFunc("toml", toml.Unmarshal) + err := fs.WalkDir(i18nFS, "translation", func(path string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + return nil + } + data, err := i18nFS.ReadFile(path) + if err != nil { + return err + } + _, err = bundle.ParseMessageFileBytes(data, path) + return err + }) + if err != nil { + return err + } + + findI18nParamNames := func(key string) []string { + names := make([]string, 0) + keyLen := len(key) + for i := 0; i < keyLen-1; i++ { + if key[i:i+2] == "{{" { // 判断开头 "{{" + j := i + 2 + isFind := false + for ; j < keyLen-1; j++ { + if key[j:j+2] == "}}" { // 结尾 "}}" + isFind = true + break + } + } + if isFind { + names = append(names, key[i+3:j]) + } + } + } + return names + } + + var localizer *i18n.Localizer + + I18n := func(key string, params ...string) (string, error) { + names := findI18nParamNames(key) + if len(names) != len(params) { + return "", common.NewError("find names:", names, "---------- params:", params, "---------- num not equal") + } + templateData := map[string]interface{}{} + for i := range names { + templateData[names[i]] = params[i] + } + return localizer.Localize(&i18n.LocalizeConfig{ + MessageID: key, + TemplateData: templateData, + }) + } + + engine.FuncMap["i18n"] = I18n; + + engine.Use(func(c *gin.Context) { + //accept := c.GetHeader("Accept-Language") + + var lang string + + if cookie, err := c.Request.Cookie("lang"); err == nil { + lang = cookie.Value + } else { + lang = c.GetHeader("Accept-Language") + } + + localizer = i18n.NewLocalizer(bundle, lang) + c.Set("localizer", localizer) + c.Set("I18n" , I18n) + c.Next() + }) + + return nil +} + +func (s *Server) startTask() { + err := s.xrayService.RestartXray(true) + if err != nil { + logger.Warning("start xray failed:", err) + } + // 每 30 秒检查一次 xray 是否在运行 + s.cron.AddJob("@every 30s", job.NewCheckXrayRunningJob()) + + go func() { + time.Sleep(time.Second * 5) + // 每 10 秒统计一次流量,首次启动延迟 5 秒,与重启 xray 的时间错开 + s.cron.AddJob("@every 10s", job.NewXrayTrafficJob()) + }() + + // 每 30 秒检查一次 inbound 流量超出和到期的情况 + s.cron.AddJob("@every 30s", job.NewCheckInboundJob()) + + // 每一天提示一次流量情况,上海时间8点30 + var entry cron.EntryID + isTgbotenabled, err := s.settingService.GetTgbotenabled() + if (err == nil) && (isTgbotenabled) { + runtime, err := s.settingService.GetTgbotRuntime() + if err != nil || runtime == "" { + logger.Errorf("Add NewStatsNotifyJob error[%s],Runtime[%s] invalid,wil run default", err, runtime) + runtime = "@daily" + } + logger.Infof("Tg notify enabled,run at %s", runtime) + entry, err = s.cron.AddJob(runtime, job.NewStatsNotifyJob()) + if err != nil { + logger.Warning("Add NewStatsNotifyJob error", err) + return + } + // listen for TG bot income messages + go job.NewStatsNotifyJob().OnReceive() + } else { + s.cron.Remove(entry) + } +} + +func (s *Server) Start() (err error) { + //这是一个匿名函数,没没有函数名 + defer func() { + if err != nil { + s.Stop() + } + }() + + loc, err := s.settingService.GetTimeLocation() + if err != nil { + return err + } + s.cron = cron.New(cron.WithLocation(loc), cron.WithSeconds()) + s.cron.Start() + + engine, err := s.initRouter() + if err != nil { + return err + } + + certFile, err := s.settingService.GetCertFile() + if err != nil { + return err + } + keyFile, err := s.settingService.GetKeyFile() + if err != nil { + return err + } + listen, err := s.settingService.GetListen() + if err != nil { + return err + } + port, err := s.settingService.GetPort() + if err != nil { + return err + } + listenAddr := net.JoinHostPort(listen, strconv.Itoa(port)) + listener, err := net.Listen("tcp", listenAddr) + if err != nil { + return err + } + if certFile != "" || keyFile != "" { + cert, err := tls.LoadX509KeyPair(certFile, keyFile) + if err != nil { + listener.Close() + return err + } + c := &tls.Config{ + Certificates: []tls.Certificate{cert}, + } + listener = network.NewAutoHttpsListener(listener) + listener = tls.NewListener(listener, c) + } + + if certFile != "" || keyFile != "" { + logger.Info("web server run https on", listener.Addr()) + } else { + logger.Info("web server run http on", listener.Addr()) + } + s.listener = listener + + s.startTask() + + s.httpServer = &http.Server{ + Handler: engine, + } + + go func() { + s.httpServer.Serve(listener) + }() + + return nil +} + +func (s *Server) Stop() error { + s.cancel() + s.xrayService.StopXray() + if s.cron != nil { + s.cron.Stop() + } + var err1 error + var err2 error + if s.httpServer != nil { + err1 = s.httpServer.Shutdown(s.ctx) + } + if s.listener != nil { + err2 = s.listener.Close() + } + return common.Combine(err1, err2) +} + +func (s *Server) GetCtx() context.Context { + return s.ctx +} + +func (s *Server) GetCron() *cron.Cron { + return s.cron +} diff --git a/x-ui.service b/x-ui.service new file mode 100644 index 00000000..29d2a63a --- /dev/null +++ b/x-ui.service @@ -0,0 +1,15 @@ +[Unit] +Description=x-ui Service +After=network.target +Wants=network.target + +[Service] +Environment="XRAY_VMESS_AEAD_FORCED=false" +Type=simple +WorkingDirectory=/usr/local/x-ui/ +ExecStart=/usr/local/x-ui/x-ui +Restart=on-failure +RestartSec=5s + +[Install] +WantedBy=multi-user.target \ No newline at end of file diff --git a/x-ui.sh b/x-ui.sh new file mode 100644 index 00000000..3d43cad4 --- /dev/null +++ b/x-ui.sh @@ -0,0 +1,630 @@ +#!/bin/bash + +red='\033[0;31m' +green='\033[0;32m' +yellow='\033[0;33m' +plain='\033[0m' + +#Add some basic function here +function LOGD() { + echo -e "${yellow}[DEG] $* ${plain}" +} + +function LOGE() { + echo -e "${red}[ERR] $* ${plain}" +} + +function LOGI() { + echo -e "${green}[INF] $* ${plain}" +} +# check root +[[ $EUID -ne 0 ]] && LOGE "ERROR: You must be root to run this script! \n" && exit 1 + +# check os +if [[ -f /etc/redhat-release ]]; then + release="centos" +elif cat /etc/issue | grep -Eqi "debian"; then + release="debian" +elif cat /etc/issue | grep -Eqi "ubuntu"; then + release="ubuntu" +elif cat /etc/issue | grep -Eqi "centos|red hat|redhat"; then + release="centos" +elif cat /proc/version | grep -Eqi "debian"; then + release="debian" +elif cat /proc/version | grep -Eqi "ubuntu"; then + release="ubuntu" +elif cat /proc/version | grep -Eqi "centos|red hat|redhat"; then + release="centos" +else + LOGE "check system OS failed,please contact with author! \n" && exit 1 +fi + +os_version="" + +# os version +if [[ -f /etc/os-release ]]; then + os_version=$(awk -F'[= ."]' '/VERSION_ID/{print $3}' /etc/os-release) +fi +if [[ -z "$os_version" && -f /etc/lsb-release ]]; then + os_version=$(awk -F'[= ."]+' '/DISTRIB_RELEASE/{print $2}' /etc/lsb-release) +fi + +if [[ x"${release}" == x"centos" ]]; then + if [[ ${os_version} -le 6 ]]; then + LOGE "please use CentOS 7 or higher version! \n" && exit 1 + fi +elif [[ x"${release}" == x"ubuntu" ]]; then + if [[ ${os_version} -lt 16 ]]; then + LOGE "please use Ubuntu 16 or higher version!\n" && exit 1 + fi +elif [[ x"${release}" == x"debian" ]]; then + if [[ ${os_version} -lt 8 ]]; then + LOGE "please use Debian 8 or higher version!\n" && exit 1 + fi +fi + +confirm() { + if [[ $# > 1 ]]; then + echo && read -p "$1 [Default$2]: " temp + if [[ x"${temp}" == x"" ]]; then + temp=$2 + fi + else + read -p "$1 [y/n]: " temp + fi + if [[ x"${temp}" == x"y" || x"${temp}" == x"Y" ]]; then + return 0 + else + return 1 + fi +} + +confirm_restart() { + confirm "Restart the panel, Attention: Restarting the panel will also restart xray" "y" + if [[ $? == 0 ]]; then + restart + else + show_menu + fi +} + +before_show_menu() { + echo && echo -n -e "${yellow}Press enter to return to the main menu: ${plain}" && read temp + show_menu +} + +install() { + bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/main/install.sh) + if [[ $? == 0 ]]; then + if [[ $# == 0 ]]; then + start + else + start 0 + fi + fi +} + +update() { + confirm "This function will forcefully reinstall the latest version, and the data will not be lost. Do you want to continue?" "n" + if [[ $? != 0 ]]; then + LOGE "Cancelled" + if [[ $# == 0 ]]; then + before_show_menu + fi + return 0 + fi + bash <(curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/main/install.sh) + if [[ $? == 0 ]]; then + LOGI "Update is complete, Panel has automatically restarted " + exit 0 + fi +} + +uninstall() { + confirm "Are you sure you want to uninstall the panel? xray will also uninstalled!" "n" + if [[ $? != 0 ]]; then + if [[ $# == 0 ]]; then + show_menu + fi + return 0 + fi + systemctl stop x-ui + systemctl disable x-ui + rm /etc/systemd/system/x-ui.service -f + systemctl daemon-reload + systemctl reset-failed + rm /etc/x-ui/ -rf + rm /usr/local/x-ui/ -rf + + echo "" + echo -e "Uninstalled Successfully,If you want to remove this script,then after exiting the script run ${green}rm /usr/bin/x-ui -f${plain} to delete it." + echo "" + + if [[ $# == 0 ]]; then + before_show_menu + fi +} + +reset_user() { + confirm "Reset your username and password to admin?" "n" + if [[ $? != 0 ]]; then + if [[ $# == 0 ]]; then + show_menu + fi + return 0 + fi + /usr/local/x-ui/x-ui setting -username admin -password admin + echo -e "Username and password have been reset to ${green}admin${plain},Please restart the panel now." + confirm_restart +} + +reset_config() { + confirm "Are you sure you want to reset all panel settings,Account data will not be lost,Username and password will not change" "n" + if [[ $? != 0 ]]; then + if [[ $# == 0 ]]; then + show_menu + fi + return 0 + fi + /usr/local/x-ui/x-ui setting -reset + echo -e "All panel settings have been reset to default,Please restart the panel now,and use the default ${green}2053${plain} Port to Access the web Panel" + confirm_restart +} + +check_config() { + info=$(/usr/local/x-ui/x-ui setting -show true) + if [[ $? != 0 ]]; then + LOGE "get current settings error,please check logs" + show_menu + fi + LOGI "${info}" +} + +set_port() { + echo && echo -n -e "Enter port number[1-65535]: " && read port + if [[ -z "${port}" ]]; then + LOGD "Cancelled" + before_show_menu + else + /usr/local/x-ui/x-ui setting -port ${port} + echo -e "The port is set,Please restart the panel now,and use the new port ${green}${port}${plain} to access web panel" + confirm_restart + fi +} + +start() { + check_status + if [[ $? == 0 ]]; then + echo "" + LOGI "Panel is running,No need to start again,If you need to restart, please select restart" + else + systemctl start x-ui + sleep 2 + check_status + if [[ $? == 0 ]]; then + LOGI "x-ui Started Successfully" + else + LOGE "panel Failed to start,Probably because it takes longer than two seconds to start,Please check the log information later" + fi + fi + + if [[ $# == 0 ]]; then + before_show_menu + fi +} + +stop() { + check_status + if [[ $? == 1 ]]; then + echo "" + LOGI "Panel stopped,No need to stop again!" + else + systemctl stop x-ui + sleep 2 + check_status + if [[ $? == 1 ]]; then + LOGI "x-ui and xray stopped successfully" + else + LOGE "Panel stop failed,Probably because the stop time exceeds two seconds,Please check the log information later" + fi + fi + + if [[ $# == 0 ]]; then + before_show_menu + fi +} + +restart() { + systemctl restart x-ui + sleep 2 + check_status + if [[ $? == 0 ]]; then + LOGI "x-ui and xray Restarted successfully" + else + LOGE "Panel restart failed,Probably because it takes longer than two seconds to start,Please check the log information later" + fi + if [[ $# == 0 ]]; then + before_show_menu + fi +} + +status() { + systemctl status x-ui -l + if [[ $# == 0 ]]; then + before_show_menu + fi +} + +enable() { + systemctl enable x-ui + if [[ $? == 0 ]]; then + LOGI "x-ui Set to boot automatically on startup successfully" + else + LOGE "x-ui Failed to set Autostart" + fi + + if [[ $# == 0 ]]; then + before_show_menu + fi +} + +disable() { + systemctl disable x-ui + if [[ $? == 0 ]]; then + LOGI "x-ui Autostart Cancelled successfully" + else + LOGE "x-ui Failed to cancel autostart" + fi + + if [[ $# == 0 ]]; then + before_show_menu + fi +} + +show_log() { + journalctl -u x-ui.service -e --no-pager -f + if [[ $# == 0 ]]; then + before_show_menu + fi +} + +migrate_v2_ui() { + /usr/local/x-ui/x-ui v2-ui + + before_show_menu +} + +install_bbr() { + # temporary workaround for installing bbr + bash <(curl -L -s https://raw.githubusercontent.com/teddysun/across/master/bbr.sh) + echo "" + before_show_menu +} + +update_shell() { + wget -O /usr/bin/x-ui -N --no-check-certificate https://github.com/mhsanaei/3x-ui/raw/main/x-ui.sh + if [[ $? != 0 ]]; then + echo "" + LOGE "Failed to download script,Please check whether the machine can connect Github" + before_show_menu + else + chmod +x /usr/bin/x-ui + LOGI "Upgrade script succeeded,Please rerun the script" && exit 0 + fi +} + +# 0: running, 1: not running, 2: not installed +check_status() { + if [[ ! -f /etc/systemd/system/x-ui.service ]]; then + return 2 + fi + temp=$(systemctl status x-ui | grep Active | awk '{print $3}' | cut -d "(" -f2 | cut -d ")" -f1) + if [[ x"${temp}" == x"running" ]]; then + return 0 + else + return 1 + fi +} + +check_enabled() { + temp=$(systemctl is-enabled x-ui) + if [[ x"${temp}" == x"enabled" ]]; then + return 0 + else + return 1 + fi +} + +check_uninstall() { + check_status + if [[ $? != 2 ]]; then + echo "" + LOGE "Panel installed,Please do not reinstall" + if [[ $# == 0 ]]; then + before_show_menu + fi + return 1 + else + return 0 + fi +} + +check_install() { + check_status + if [[ $? == 2 ]]; then + echo "" + LOGE "Please install the panel first" + if [[ $# == 0 ]]; then + before_show_menu + fi + return 1 + else + return 0 + fi +} + +show_status() { + check_status + case $? in + 0) + echo -e "Panel state: ${green}Runing${plain}" + show_enable_status + ;; + 1) + echo -e "Panel state: ${yellow}Not Running${plain}" + show_enable_status + ;; + 2) + echo -e "Panel state: ${red}Not Installed${plain}" + ;; + esac + show_xray_status +} + +show_enable_status() { + check_enabled + if [[ $? == 0 ]]; then + echo -e "Start automatically: ${green}Yes${plain}" + else + echo -e "Start automatically: ${red}No${plain}" + fi +} + +check_xray_status() { + count=$(ps -ef | grep "xray-linux" | grep -v "grep" | wc -l) + if [[ count -ne 0 ]]; then + return 0 + else + return 1 + fi +} + +show_xray_status() { + check_xray_status + if [[ $? == 0 ]]; then + echo -e "xray state: ${green}Runing${plain}" + else + echo -e "xray state: ${red}Not Running${plain}" + fi +} + +ssl_cert_issue() { + echo -E "" + LOGD "******Instructions for use******" + LOGI "This Acme script requires the following data:" + LOGI "1.Cloudflare Registered e-mail" + LOGI "2.Cloudflare Global API Key" + LOGI "3.The domain name that has been resolved dns to the current server by Cloudflare" + LOGI "4.The script applies for a certificate. The default installation path is /root/cert " + confirm "Confirmed?[y/n]" "y" + if [ $? -eq 0 ]; then + cd ~ + LOGI "Install Acme-Script" + curl https://get.acme.sh | sh + if [ $? -ne 0 ]; then + LOGE "Failed to install acme script" + exit 1 + fi + CF_Domain="" + CF_GlobalKey="" + CF_AccountEmail="" + certPath=/root/cert + if [ ! -d "$certPath" ]; then + mkdir $certPath + else + rm -rf $certPath + mkdir $certPath + fi + LOGD "Please set a domain name:" + read -p "Input your domain here:" CF_Domain + LOGD "Your domain name is set to:${CF_Domain}" + LOGD "Please set the API key:" + read -p "Input your key here:" CF_GlobalKey + LOGD "Your API key is:${CF_GlobalKey}" + LOGD "Please set up registered email:" + read -p "Input your email here:" CF_AccountEmail + LOGD "Your registered email address is:${CF_AccountEmail}" + ~/.acme.sh/acme.sh --set-default-ca --server letsencrypt + if [ $? -ne 0 ]; then + LOGE "Default CA, Lets'Encrypt fail, script exiting..." + exit 1 + fi + export CF_Key="${CF_GlobalKey}" + export CF_Email=${CF_AccountEmail} + ~/.acme.sh/acme.sh --issue --dns dns_cf -d ${CF_Domain} -d *.${CF_Domain} --log + if [ $? -ne 0 ]; then + LOGE "Certificate issuance failed, script exiting..." + exit 1 + else + LOGI "Certificate issued Successfully, Installing..." + fi + ~/.acme.sh/acme.sh --installcert -d ${CF_Domain} -d *.${CF_Domain} --ca-file /root/cert/ca.cer \ + --cert-file /root/cert/${CF_Domain}.cer --key-file /root/cert/${CF_Domain}.key \ + --fullchain-file /root/cert/fullchain.cer + if [ $? -ne 0 ]; then + LOGE "Certificate installation failed, script exiting..." + exit 1 + else + LOGI "Certificate installed Successfully,Turning on automatic updates..." + fi + ~/.acme.sh/acme.sh --upgrade --auto-upgrade + if [ $? -ne 0 ]; then + LOGE "Auto update setup Failed, script exiting..." + ls -lah cert + chmod 755 $certPath + exit 1 + else + LOGI "The certificate is installed and auto-renewal is turned on, Specific information is as follows" + ls -lah cert + chmod 755 $certPath + fi + else + show_menu + fi +} + +show_usage() { + echo "x-ui control menu usages: " + echo "------------------------------------------" + echo "x-ui - Enter Admin menu" + echo "x-ui start - Start x-ui" + echo "x-ui stop - Stop x-ui" + echo "x-ui restart - Restart x-ui" + echo "x-ui status - Show x-ui status" + echo "x-ui enable - Enable x-ui on system startup" + echo "x-ui disable - Disable x-ui on system startup" + echo "x-ui log - Check x-ui logs" + echo "x-ui v2-ui - Migrate v2-ui Account data to x-ui" + echo "x-ui update - Update x-ui" + echo "x-ui install - Install x-ui" + echo "x-ui uninstall - Uninstall x-ui" + echo "------------------------------------------" +} + +show_menu() { + echo -e " + ${green}x-ui Panel Management Script${plain} + ${green}0.${plain} exit script +———————————————— + ${green}1.${plain} Install x-ui + ${green}2.${plain} Update x-ui + ${green}3.${plain} Uninstall x-ui +———————————————— + ${green}4.${plain} Reset username and password + ${green}5.${plain} Reset panel settings + ${green}6.${plain} Set panel port + ${green}7.${plain} View current panel settings +———————————————— + ${green}8.${plain} Start x-ui + ${green}9.${plain} stop x-ui + ${green}10.${plain} Reboot x-ui + ${green}11.${plain} Check x-ui state + ${green}12.${plain} Check x-ui logs +———————————————— + ${green}13.${plain} set x-ui Autostart + ${green}14.${plain} Cancel x-ui Autostart +———————————————— + ${green}15.${plain} 一A key installation bbr (latest kernel) + ${green}16.${plain} 一Apply for an SSL certificate with one click(acme script) + " + show_status + echo && read -p "Please enter your selection [0-16]: " num + + case "${num}" in + 0) + exit 0 + ;; + 1) + check_uninstall && install + ;; + 2) + check_install && update + ;; + 3) + check_install && uninstall + ;; + 4) + check_install && reset_user + ;; + 5) + check_install && reset_config + ;; + 6) + check_install && set_port + ;; + 7) + check_install && check_config + ;; + 8) + check_install && start + ;; + 9) + check_install && stop + ;; + 10) + check_install && restart + ;; + 11) + check_install && status + ;; + 12) + check_install && show_log + ;; + 13) + check_install && enable + ;; + 14) + check_install && disable + ;; + 15) + install_bbr + ;; + 16) + ssl_cert_issue + ;; + *) + LOGE "Please enter the correct number [0-16]" + ;; + esac +} + +if [[ $# > 0 ]]; then + case $1 in + "start") + check_install 0 && start 0 + ;; + "stop") + check_install 0 && stop 0 + ;; + "restart") + check_install 0 && restart 0 + ;; + "status") + check_install 0 && status 0 + ;; + "enable") + check_install 0 && enable 0 + ;; + "disable") + check_install 0 && disable 0 + ;; + "log") + check_install 0 && show_log 0 + ;; + "v2-ui") + check_install 0 && migrate_v2_ui 0 + ;; + "update") + check_install 0 && update 0 + ;; + "install") + check_uninstall 0 && install 0 + ;; + "uninstall") + check_install 0 && uninstall 0 + ;; + *) show_usage ;; + esac +else + show_menu +fi diff --git a/xray/client_traffic.go b/xray/client_traffic.go new file mode 100644 index 00000000..4df6a502 --- /dev/null +++ b/xray/client_traffic.go @@ -0,0 +1,12 @@ +package xray + +type ClientTraffic struct { + Id int `json:"id" form:"id" gorm:"primaryKey;autoIncrement"` + InboundId int `json:"inboundId" form:"inboundId"` + Enable bool `json:"enable" form:"enable"` + Email string `json:"email" form:"email" gorm:"unique"` + Up int64 `json:"up" form:"up"` + Down int64 `json:"down" form:"down"` + ExpiryTime int64 `json:"expiryTime" form:"expiryTime"` + Total int64 `json:"total" form:"total"` +} diff --git a/xray/config.go b/xray/config.go new file mode 100644 index 00000000..cc63ca40 --- /dev/null +++ b/xray/config.go @@ -0,0 +1,62 @@ +package xray + +import ( + "bytes" + "x-ui/util/json_util" +) + +type Config struct { + LogConfig json_util.RawMessage `json:"log"` + RouterConfig json_util.RawMessage `json:"routing"` + DNSConfig json_util.RawMessage `json:"dns"` + InboundConfigs []InboundConfig `json:"inbounds"` + OutboundConfigs json_util.RawMessage `json:"outbounds"` + Transport json_util.RawMessage `json:"transport"` + Policy json_util.RawMessage `json:"policy"` + API json_util.RawMessage `json:"api"` + Stats json_util.RawMessage `json:"stats"` + Reverse json_util.RawMessage `json:"reverse"` + FakeDNS json_util.RawMessage `json:"fakeDns"` +} + +func (c *Config) Equals(other *Config) bool { + if len(c.InboundConfigs) != len(other.InboundConfigs) { + return false + } + for i, inbound := range c.InboundConfigs { + if !inbound.Equals(&other.InboundConfigs[i]) { + return false + } + } + if !bytes.Equal(c.LogConfig, other.LogConfig) { + return false + } + if !bytes.Equal(c.RouterConfig, other.RouterConfig) { + return false + } + if !bytes.Equal(c.DNSConfig, other.DNSConfig) { + return false + } + if !bytes.Equal(c.OutboundConfigs, other.OutboundConfigs) { + return false + } + if !bytes.Equal(c.Transport, other.Transport) { + return false + } + if !bytes.Equal(c.Policy, other.Policy) { + return false + } + if !bytes.Equal(c.API, other.API) { + return false + } + if !bytes.Equal(c.Stats, other.Stats) { + return false + } + if !bytes.Equal(c.Reverse, other.Reverse) { + return false + } + if !bytes.Equal(c.FakeDNS, other.FakeDNS) { + return false + } + return true +} diff --git a/xray/inbound.go b/xray/inbound.go new file mode 100644 index 00000000..461c2ee7 --- /dev/null +++ b/xray/inbound.go @@ -0,0 +1,41 @@ +package xray + +import ( + "bytes" + "x-ui/util/json_util" +) + +type InboundConfig struct { + Listen json_util.RawMessage `json:"listen"` // listen 不能为空字符串 + Port int `json:"port"` + Protocol string `json:"protocol"` + Settings json_util.RawMessage `json:"settings"` + StreamSettings json_util.RawMessage `json:"streamSettings"` + Tag string `json:"tag"` + Sniffing json_util.RawMessage `json:"sniffing"` +} + +func (c *InboundConfig) Equals(other *InboundConfig) bool { + if !bytes.Equal(c.Listen, other.Listen) { + return false + } + if c.Port != other.Port { + return false + } + if c.Protocol != other.Protocol { + return false + } + if !bytes.Equal(c.Settings, other.Settings) { + return false + } + if !bytes.Equal(c.StreamSettings, other.StreamSettings) { + return false + } + if c.Tag != other.Tag { + return false + } + if !bytes.Equal(c.Sniffing, other.Sniffing) { + return false + } + return true +} diff --git a/xray/process.go b/xray/process.go new file mode 100644 index 00000000..ffa933ca --- /dev/null +++ b/xray/process.go @@ -0,0 +1,313 @@ +package xray + +import ( + "bufio" + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io/fs" + "os" + "os/exec" + "regexp" + "runtime" + "strings" + "time" + "x-ui/util/common" + + "github.com/Workiva/go-datastructures/queue" + statsservice "github.com/xtls/xray-core/app/stats/command" + "google.golang.org/grpc" +) + +var trafficRegex = regexp.MustCompile("(inbound|outbound)>>>([^>]+)>>>traffic>>>(downlink|uplink)") +var ClientTrafficRegex = regexp.MustCompile("(user)>>>([^>]+)>>>traffic>>>(downlink|uplink)") + +func GetBinaryName() string { + return fmt.Sprintf("xray-%s-%s", runtime.GOOS, runtime.GOARCH) +} + +func GetBinaryPath() string { + return "bin/" + GetBinaryName() +} + +func GetConfigPath() string { + return "bin/config.json" +} + +func GetGeositePath() string { + return "bin/geosite.dat" +} + +func GetGeoipPath() string { + return "bin/geoip.dat" +} + +func stopProcess(p *Process) { + p.Stop() +} + +type Process struct { + *process +} + +func NewProcess(xrayConfig *Config) *Process { + p := &Process{newProcess(xrayConfig)} + runtime.SetFinalizer(p, stopProcess) + return p +} + +type process struct { + cmd *exec.Cmd + + version string + apiPort int + + config *Config + lines *queue.Queue + exitErr error +} + +func newProcess(config *Config) *process { + return &process{ + version: "Unknown", + config: config, + lines: queue.New(100), + } +} + +func (p *process) IsRunning() bool { + if p.cmd == nil || p.cmd.Process == nil { + return false + } + if p.cmd.ProcessState == nil { + return true + } + return false +} + +func (p *process) GetErr() error { + return p.exitErr +} + +func (p *process) GetResult() string { + if p.lines.Empty() && p.exitErr != nil { + return p.exitErr.Error() + } + items, _ := p.lines.TakeUntil(func(item interface{}) bool { + return true + }) + lines := make([]string, 0, len(items)) + for _, item := range items { + lines = append(lines, item.(string)) + } + return strings.Join(lines, "\n") +} + +func (p *process) GetVersion() string { + return p.version +} + +func (p *Process) GetAPIPort() int { + return p.apiPort +} + +func (p *Process) GetConfig() *Config { + return p.config +} + +func (p *process) refreshAPIPort() { + for _, inbound := range p.config.InboundConfigs { + if inbound.Tag == "api" { + p.apiPort = inbound.Port + break + } + } +} + +func (p *process) refreshVersion() { + cmd := exec.Command(GetBinaryPath(), "-version") + data, err := cmd.Output() + if err != nil { + p.version = "Unknown" + } else { + datas := bytes.Split(data, []byte(" ")) + if len(datas) <= 1 { + p.version = "Unknown" + } else { + p.version = string(datas[1]) + } + } +} + +func (p *process) Start() (err error) { + if p.IsRunning() { + return errors.New("xray is already running") + } + + defer func() { + if err != nil { + p.exitErr = err + } + }() + + data, err := json.MarshalIndent(p.config, "", " ") + if err != nil { + return common.NewErrorf("生成 xray 配置文件失败: %v", err) + } + configPath := GetConfigPath() + err = os.WriteFile(configPath, data, fs.ModePerm) + if err != nil { + return common.NewErrorf("写入配置文件失败: %v", err) + } + + cmd := exec.Command(GetBinaryPath(), "-c", configPath) + p.cmd = cmd + + stdReader, err := cmd.StdoutPipe() + if err != nil { + return err + } + errReader, err := cmd.StderrPipe() + if err != nil { + return err + } + + go func() { + defer func() { + common.Recover("") + stdReader.Close() + }() + reader := bufio.NewReaderSize(stdReader, 8192) + for { + line, _, err := reader.ReadLine() + if err != nil { + return + } + if p.lines.Len() >= 100 { + p.lines.Get(1) + } + p.lines.Put(string(line)) + } + }() + + go func() { + defer func() { + common.Recover("") + errReader.Close() + }() + reader := bufio.NewReaderSize(errReader, 8192) + for { + line, _, err := reader.ReadLine() + if err != nil { + return + } + if p.lines.Len() >= 100 { + p.lines.Get(1) + } + p.lines.Put(string(line)) + } + }() + + go func() { + err := cmd.Run() + if err != nil { + p.exitErr = err + } + }() + + p.refreshVersion() + p.refreshAPIPort() + + return nil +} + +func (p *process) Stop() error { + if !p.IsRunning() { + return errors.New("xray is not running") + } + return p.cmd.Process.Kill() +} + +func (p *process) GetTraffic(reset bool) ([]*Traffic, []*ClientTraffic, error) { + if p.apiPort == 0 { + return nil, nil, common.NewError("xray api port wrong:", p.apiPort) + } + conn, err := grpc.Dial(fmt.Sprintf("127.0.0.1:%v", p.apiPort), grpc.WithInsecure()) + if err != nil { + return nil, nil, err + } + defer conn.Close() + + client := statsservice.NewStatsServiceClient(conn) + ctx, cancel := context.WithTimeout(context.Background(), time.Second*10) + defer cancel() + request := &statsservice.QueryStatsRequest{ + Reset_: reset, + } + resp, err := client.QueryStats(ctx, request) + if err != nil { + return nil, nil, err + } + tagTrafficMap := map[string]*Traffic{} + emailTrafficMap := map[string]*ClientTraffic{} + + clientTraffics := make([]*ClientTraffic, 0) + traffics := make([]*Traffic, 0) + for _, stat := range resp.GetStat() { + matchs := trafficRegex.FindStringSubmatch(stat.Name) + if len(matchs) < 3 { + + matchs := ClientTrafficRegex.FindStringSubmatch(stat.Name) + if len(matchs) < 3 { + continue + } else { + + isUser := matchs[1] == "user" + email := matchs[2] + isDown := matchs[3] == "downlink" + if !isUser { + continue + } + traffic, ok := emailTrafficMap[email] + if !ok { + traffic = &ClientTraffic{ + Email: email, + } + emailTrafficMap[email] = traffic + clientTraffics = append(clientTraffics, traffic) + } + if isDown { + traffic.Down = stat.Value + } else { + traffic.Up = stat.Value + } + + } + continue + } + isInbound := matchs[1] == "inbound" + tag := matchs[2] + isDown := matchs[3] == "downlink" + if tag == "api" { + continue + } + traffic, ok := tagTrafficMap[tag] + if !ok { + traffic = &Traffic{ + IsInbound: isInbound, + Tag: tag, + } + tagTrafficMap[tag] = traffic + traffics = append(traffics, traffic) + } + if isDown { + traffic.Down = stat.Value + } else { + traffic.Up = stat.Value + } + } + + return traffics, clientTraffics, nil +} diff --git a/xray/traffic.go b/xray/traffic.go new file mode 100644 index 00000000..a1ef5186 --- /dev/null +++ b/xray/traffic.go @@ -0,0 +1,8 @@ +package xray + +type Traffic struct { + IsInbound bool + Tag string + Up int64 + Down int64 +}