commit 17a0fd93672bf5c01b135c6dbebdc015cc38a1ce Author: LZX <1820455493@qq.com> Date: Sun Nov 8 14:41:08 2026 +0800 feat: Initial release of Tailscale Manager diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c8d0594 --- /dev/null +++ b/.gitignore @@ -0,0 +1,71 @@ +# Built application files +*.apk +*.ap_ +*.aab + +# Files for the ART/Dalvik VM +*.dex + +# Java class files +*.class + +# Generated files +bin/ +gen/ +out/ +build/ +/build +*/build + +# Gradle files +.gradle/ + +# Local configuration file (sdk path, etc) +local.properties + +# Proguard / R8 folder +proguard/ + +# Log Files +*.log + +# Android Studio captures folder +captures/ + +# IntelliJ IDEA / Android Studio +*.iml +.idea/ +.navigation/ + +# Kotlin +.kotlin/ + +# Keystore & Signing files +*.jks +*.keystore +*.p12 +*.key +*.pem +*.cer + +# Google Services (Firebase) +google-services.json + +# External native build folder +.externalNativeBuild +.cxx/ + +# OS specific files +.DS_Store +Thumbs.db +ehthumbs.db +Desktop.ini + +# Profiler & memory dumps +*.hprof +*.stackdump + +# Editor backup / swap files +*~ +*.swp +*.swo diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e0b78e2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,621 @@ + 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 fee), 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 diff --git a/README.md b/README.md new file mode 100644 index 0000000..5bdb010 --- /dev/null +++ b/README.md @@ -0,0 +1,54 @@ +

+ Tailscale Manager Logo +

+ +

Tailscale Manager

+ +

+ 专为 Android (Root) 平台设计的原生 Tailscale 守护进程与状态管理工具 +

+ +

+ Platform + Language + UI +
+ Privacy + License +

+ +

+ 简体中文 | English +

+ +--- + +## 核心实现架构 + +### 1. 原生底层守护进程与路由自愈 +- **纯原生 Linux 隧道**:将官方编译的 `tailscaled` 守护程序部署于系统模块目录,直接调用 Linux 内核 `tun` 驱动与系统路由表,不依赖 Android `VpnService`,保留系统自带 VPN 槽位给其他工具使用。 +- **切网自愈机制**:后台监听网络接口事件(Wi-Fi、蜂窝网络及代理环境切换),动态更新路由规则,防止网络死锁与链路中断。 +- **全局终端 CLI 支持**:自动注册全局系统软链接至 `/data/adb/ksu/bin/tailscale`,支持在 Termux 或任意终端中直接使用官方原生 CLI 命令行进行高级网络调试。 + +### 2. Root 交互与 IPC 通信控制 +- **Unix Domain Socket 桥接**:通过 Root 调度桥接层与后台 `tailscaled.sock` 守护套接字进行通信,实时同步设备在线状态、Tailscale IP 及当前出口节点配置。 +- **完整功能闭环**: + - 浏览器引导式 OAuth 设备授权与多账号平滑切换。 + - 出口节点(Exit Node)选择、局域网访问(LAN Access)与出口节点广播配置。 + - 节点列表延迟与 DERP 中继路径连通性实时探测(Ping)。 + - 设备主机名(Hostname)修改与实时双向同步。 + - Tailscale DNS、入站连接(Shields Up)及子网路由偏好管理。 + +### 3. 现代化界面与国际化设计 +- **Jetpack Compose & Material 3**:采用声明式 UI 架构,深度适配 Material You 动态色彩壁纸取色系统,并提供精选主题色与明暗模式自由切换。 +- **全站国际化(i18n)规范**:严格分离字符串资源,无任何写死文本,原生支持简体中文与英文多语言环境。 + +### 4. 自动化检测与更新流 +- **生命周期检测序列**:启动时按序流式执行「Root 授权检测」→「应用版本更新」→「模块组件同步检测」。 +- **版本静默与抑制机制**:支持针对特定更新版本进行抑制设置(不再提醒),并在仪表盘模块卡片和关于页面保留手动即时检测入口。 + +--- + +## 开源协议 + +本项目基于 **GNU General Public License v3.0 (GPL-3.0)** 协议开源。详细条款请参阅 [LICENSE](LICENSE) 文件。 diff --git a/README_EN.md b/README_EN.md new file mode 100644 index 0000000..a76c003 --- /dev/null +++ b/README_EN.md @@ -0,0 +1,58 @@ +

+ Tailscale Manager Logo +

+ +

Tailscale Manager

+ +

+ A native Tailscale daemon & state manager designed specifically for Android (Root) environments +

+ +

+ Platform + Language + UI +
+ Privacy + License +

+ +

+ 简体中文 | English +

+ +--- + +Tailscale Manager is an Android client and module manager built for rooted devices (KernelSU / APatch / Magisk). By deploying the official Tailscale daemon directly as a native Linux process, it bypasses Android's `VpnService` overhead and single-VPN slot limitations, delivering line-rate wireguard throughput and a true native mesh network experience. + +--- + +## Core Architecture & Implementation + +### 1. Native Linux Daemon & Network Auto-Healing +- **Pure Linux Tunneling**: Deploys the official `tailscaled` daemon binary directly into the system module directory. It interacts with the Linux kernel `tun` driver and kernel routing tables without touching Android `VpnService`, reserving the system VPN slot for other tools. +- **Dynamic Network Auto-Healing**: Actively listens to network interface changes (Wi-Fi, cellular, and proxy routing transitions) to dynamically refresh routing rules, eliminating network deadlocks and dropped connections. +- **System-Wide CLI Integration**: Automatically registers global symlinks at `/data/adb/ksu/bin/tailscale`, allowing direct access to the official Tailscale CLI from Termux or any root shell. + +### 2. Root IPC Bridge & Control Dispatch +- **Unix Domain Socket Bridge**: Communicates with the background `tailscaled.sock` via a high-performance Root bridge layer to sync device status, Tailscale IP, and active exit nodes in real time. +- **Comprehensive Feature Set**: + - Browser-guided OAuth device authentication and seamless multi-account profile switching. + - Exit node selection, local network access (LAN access) toggle, and run-as-exit-node advertisement. + - Live route diagnostics and latency ping probing across tailnet devices and DERP relays. + - Real-time device hostname modification with instant UI reflection. + - Full control over Tailscale MagicDNS, inbound connection rules (Shields Up), and subnet routing preferences. + +### 3. Modern Jetpack Compose UI & Internationalization +- **Jetpack Compose & Material 3**: Built entirely with declarative UI architecture, deeply integrated with Android Material You dynamic wallpaper theming, custom color palettes, and seamless dark/light mode switching. +- **Strict i18n Standard**: All UI strings are extracted into localization resources with zero hardcoded text, offering complete native support for Simplified Chinese and English. + +### 4. Lifecycle Verification & Update Pipeline +- **Sequential Startup Flow**: Performs a fluid startup check sequence: `Root Permission Check` → `App Update Check` → `Module Component Sync Check`. +- **Suppression & Manual Triggers**: Supports version-specific suppression ("Don't show again") during startup, while retaining instant manual update check actions on the Dashboard module card and the About screen. + +--- + +## License + +This project is licensed under the **GNU General Public License v3.0 (GPL-3.0)**. See the [LICENSE](LICENSE) file for details. diff --git a/app/.gitignore b/app/.gitignore new file mode 100644 index 0000000..42afabf --- /dev/null +++ b/app/.gitignore @@ -0,0 +1 @@ +/build \ No newline at end of file diff --git a/app/build.gradle.kts b/app/build.gradle.kts new file mode 100644 index 0000000..5099cc3 --- /dev/null +++ b/app/build.gradle.kts @@ -0,0 +1,77 @@ +plugins { + alias(libs.plugins.android.application) + alias(libs.plugins.kotlin.compose) +} + +android { + namespace = "com.lzxnone.tailscalemanager" + compileSdk = 37 + + defaultConfig { + applicationId = "com.lzxnone.tailscalemanager" + minSdk = 28 + targetSdk = 36 + versionCode = 100 + versionName = "1.0.0" + + testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" + } + + val keystoreFile = file("tailscale_manager.jks") + if (keystoreFile.exists()) { + signingConfigs { + create("release") { + storeFile = keystoreFile + storePassword = "tailscalemanager" + keyAlias = "tailscale" + keyPassword = "tailscalemanager" + } + } + } + + buildTypes { + release { + isMinifyEnabled = false + if (keystoreFile.exists()) { + signingConfig = signingConfigs.getByName("release") + } + proguardFiles( + getDefaultProguardFile("proguard-android-optimize.txt"), + "proguard-rules.pro" + ) + } + debug { + if (keystoreFile.exists()) { + signingConfig = signingConfigs.getByName("release") + } + } + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_11 + targetCompatibility = JavaVersion.VERSION_11 + } + buildFeatures { + compose = true + buildConfig = true + } +} + +dependencies { + implementation(platform(libs.androidx.compose.bom)) + implementation(libs.androidx.activity.compose) + implementation(libs.androidx.compose.material3) + implementation(libs.androidx.compose.material.icons.extended) + implementation(libs.androidx.lifecycle.viewmodel.compose) + implementation(libs.androidx.compose.ui) + implementation(libs.androidx.compose.ui.graphics) + implementation(libs.androidx.compose.ui.tooling.preview) + implementation(libs.androidx.core.ktx) + implementation(libs.androidx.lifecycle.runtime.ktx) + testImplementation(libs.junit) + androidTestImplementation(platform(libs.androidx.compose.bom)) + androidTestImplementation(libs.androidx.compose.ui.test.junit4) + androidTestImplementation(libs.androidx.espresso.core) + androidTestImplementation(libs.androidx.junit) + debugImplementation(libs.androidx.compose.ui.test.manifest) + debugImplementation(libs.androidx.compose.ui.tooling) +} \ No newline at end of file diff --git a/app/proguard-rules.pro b/app/proguard-rules.pro new file mode 100644 index 0000000..481bb43 --- /dev/null +++ b/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile \ No newline at end of file diff --git a/app/src/androidTest/java/com/lzxnone/tailscalemanager/ExampleInstrumentedTest.kt b/app/src/androidTest/java/com/lzxnone/tailscalemanager/ExampleInstrumentedTest.kt new file mode 100644 index 0000000..2f544b6 --- /dev/null +++ b/app/src/androidTest/java/com/lzxnone/tailscalemanager/ExampleInstrumentedTest.kt @@ -0,0 +1,24 @@ +package com.lzxnone.tailscalemanager + +import androidx.test.platform.app.InstrumentationRegistry +import androidx.test.ext.junit.runners.AndroidJUnit4 + +import org.junit.Test +import org.junit.runner.RunWith + +import org.junit.Assert.* + +/** + * Instrumented test, which will execute on an Android device. + * + * See [testing documentation](http://d.android.com/tools/testing). + */ +@RunWith(AndroidJUnit4::class) +class ExampleInstrumentedTest { + @Test + fun useAppContext() { + // Context of the app under test. + val appContext = InstrumentationRegistry.getInstrumentation().targetContext + assertEquals("com.lzxnone.tailscalemanager", appContext.packageName) + } +} \ No newline at end of file diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml new file mode 100644 index 0000000..22a33e7 --- /dev/null +++ b/app/src/main/AndroidManifest.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/MainActivity.kt b/app/src/main/java/com/lzxnone/tailscalemanager/MainActivity.kt new file mode 100644 index 0000000..16329eb --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/MainActivity.kt @@ -0,0 +1,91 @@ +package com.lzxnone.tailscalemanager + +import android.content.Context +import android.content.res.Configuration +import android.content.res.Resources +import android.os.Bundle +import androidx.activity.ComponentActivity +import androidx.activity.compose.setContent +import androidx.activity.enableEdgeToEdge +import androidx.compose.runtime.CompositionLocalProvider +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.remember +import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.platform.LocalContext +import com.lzxnone.tailscalemanager.core.settings.AppPreferences +import com.lzxnone.tailscalemanager.ui.screens.MainScreen +import com.lzxnone.tailscalemanager.ui.theme.TailscaleManagerTheme +import java.util.Locale + +class MainActivity : ComponentActivity() { + + override fun attachBaseContext(newBase: Context) { + val prefs = newBase.getSharedPreferences("tailscale_manager_prefs", Context.MODE_PRIVATE) + val lang = prefs.getString("language", "system") ?: "system" + val activeLocale = when (lang) { + "zh" -> Locale.SIMPLIFIED_CHINESE + "en" -> Locale.ENGLISH + else -> null + } + if (activeLocale != null) { + val config = Configuration(newBase.resources.configuration) + config.setLocale(activeLocale) + super.attachBaseContext(newBase.createConfigurationContext(config)) + } else { + super.attachBaseContext(newBase) + } + } + + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + AppPreferences.init(this) + enableEdgeToEdge() + setContent { + val language by AppPreferences.language.collectAsState() + val themeMode by AppPreferences.themeMode.collectAsState() + val dynamicColor by AppPreferences.dynamicColor.collectAsState() + val customColorKey by AppPreferences.customColorKey.collectAsState() + + // Resolve true system locale from immutable system-level configuration + val systemLocale = remember { + val sysLocales = Resources.getSystem().configuration.locales + if (!sysLocales.isEmpty) sysLocales[0] else Locale.getDefault() + } + val activeLocale = when (language) { + "zh" -> Locale.SIMPLIFIED_CHINESE + "en" -> Locale.ENGLISH + else -> systemLocale + } + + val baseContext = LocalContext.current + val localizedContext = remember(baseContext, activeLocale) { + val config = Configuration(baseContext.resources.configuration) + config.setLocale(activeLocale) + baseContext.createConfigurationContext(config) + } + val localizedConfiguration = remember(activeLocale) { + val config = Configuration(Resources.getSystem().configuration) + config.setLocale(activeLocale) + config + } + + CompositionLocalProvider( + LocalContext provides localizedContext, + LocalConfiguration provides localizedConfiguration + ) { + TailscaleManagerTheme( + themeMode = themeMode, + dynamicColor = dynamicColor, + customColorKey = customColorKey + ) { + MainScreen( + onExitApp = { + finishAffinity() + } + ) + } + } + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleConfig.kt b/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleConfig.kt new file mode 100644 index 0000000..42f0410 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleConfig.kt @@ -0,0 +1,19 @@ +package com.lzxnone.tailscalemanager.core.module + +object ModuleConfig { + const val MODULE_ID = "tailscale_native" + const val MODULE_NAME = "Tailscale Native Service" + const val BUNDLED_VERSION_CODE = 10000L + const val BUNDLED_VERSION_NAME = "v1.0" + const val MODULE_AUTHOR = "lzxnone" + const val MODULE_DESCRIPTION = "原生运行的 Tailscale 守护进程。包含开机自启、事件驱动的动态切网自愈,以及代理防死锁路由策略。" + + const val MODULE_PATH = "/data/adb/modules/$MODULE_ID" + const val MODULE_PROP_PATH = "$MODULE_PATH/module.prop" + const val MODULE_SERVICE_SCRIPT = "$MODULE_PATH/service.sh" + const val MODULE_SOCKET_PATH = "$MODULE_PATH/state/tailscaled.sock" + const val MODULE_BIN_DIR = "$MODULE_PATH/bin" + const val MODULE_SYSTEM_BIN_WRAPPER = "$MODULE_PATH/system/bin/tailscale" + const val KSU_GLOBAL_BIN_LINK = "/data/adb/ksu/bin/tailscale" + const val ASSET_MODULE_ZIP = "tailscale_module.zip" +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleManager.kt b/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleManager.kt new file mode 100644 index 0000000..4e033da --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleManager.kt @@ -0,0 +1,198 @@ +package com.lzxnone.tailscalemanager.core.module + +import android.content.Context +import com.lzxnone.tailscalemanager.core.root.RootBridge +import com.lzxnone.tailscalemanager.model.ModuleInfo +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.File +import java.io.FileOutputStream + +object ModuleManager { + + suspend fun getModuleState(): ModuleState = withContext(Dispatchers.IO) { + val checkProp = RootBridge.execute("[ -f \"${ModuleConfig.MODULE_PROP_PATH}\" ] && echo 1 || echo 0") + if (checkProp.stdout.trim() != "1") { + return@withContext ModuleState.NOT_INSTALLED + } + + val checkDisable = RootBridge.execute("[ -f \"${ModuleConfig.MODULE_PATH}/disable\" ] && echo 1 || echo 0") + if (checkDisable.stdout.trim() == "1") { + ModuleState.DISABLED + } else { + ModuleState.ENABLED + } + } + + suspend fun getInstalledModule(): ModuleInfo? = withContext(Dispatchers.IO) { + val checkProp = RootBridge.execute("[ -f \"${ModuleConfig.MODULE_PROP_PATH}\" ] && echo 1 || echo 0") + if (checkProp.stdout.trim() != "1") { + return@withContext null + } + + val readProp = RootBridge.execute("cat \"${ModuleConfig.MODULE_PROP_PATH}\"") + if (!readProp.isSuccess) { + return@withContext null + } + + val props = mutableMapOf() + readProp.stdout.lineSequence().forEach { line -> + val trimmed = line.trim() + if (trimmed.isNotEmpty() && !trimmed.startsWith("#") && trimmed.contains("=")) { + val parts = trimmed.split("=", limit = 2) + props[parts[0].trim()] = parts[1].trim() + } + } + + val id = props["id"] ?: ModuleConfig.MODULE_ID + val name = props["name"] ?: ModuleConfig.MODULE_NAME + val version = props["version"] ?: "unknown" + val versionCode = props["versionCode"]?.toLongOrNull() ?: 0L + val author = props["author"] ?: "Unknown" + val description = props["description"] ?: "" + + val isEnabled = RootBridge.execute("[ ! -f \"${ModuleConfig.MODULE_PATH}/disable\" ] && echo 1 || echo 0") + .stdout.trim() == "1" + + ModuleInfo( + id = id, + name = name, + version = version, + versionCode = versionCode, + author = author, + description = description, + isInstalled = true, + isEnabled = isEnabled + ) + } + + suspend fun enableModule(): Result = withContext(Dispatchers.IO) { + try { + RootBridge.execute("rm -f \"${ModuleConfig.MODULE_PATH}/disable\"") + // Ensure global symlink is registered + RootBridge.execute("mkdir -p /data/adb/ksu/bin && ln -sf \"${ModuleConfig.MODULE_SYSTEM_BIN_WRAPPER}\" \"${ModuleConfig.KSU_GLOBAL_BIN_LINK}\" && chmod 755 \"${ModuleConfig.KSU_GLOBAL_BIN_LINK}\"") + + // Launch service if not running + val pidCheck = RootBridge.execute("pgrep -f tailscaled") + if (!pidCheck.isSuccess || pidCheck.stdout.trim().isEmpty()) { + RootBridge.execute("nohup sh \"${ModuleConfig.MODULE_SERVICE_SCRIPT}\" >/dev/null 2>&1 &") + } + Result.success(Unit) + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun disableModule(): Result = withContext(Dispatchers.IO) { + try { + RootBridge.execute("touch \"${ModuleConfig.MODULE_PATH}/disable\"") + // Shut down service and active connection + RootBridge.execute("${ModuleConfig.MODULE_SYSTEM_BIN_WRAPPER} down 2>/dev/null") + RootBridge.execute("killall tailscaled 2>/dev/null") + Result.success(Unit) + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun deleteModule(): Result = withContext(Dispatchers.IO) { + try { + // Stop network connection and kill background daemon + RootBridge.execute("${ModuleConfig.MODULE_SYSTEM_BIN_WRAPPER} down 2>/dev/null") + RootBridge.execute("killall tailscaled 2>/dev/null") + + // Remove global symlink + RootBridge.execute("rm -f \"${ModuleConfig.KSU_GLOBAL_BIN_LINK}\"") + + // Remove module directory completely + RootBridge.execute("rm -rf \"${ModuleConfig.MODULE_PATH}\"") + Result.success(Unit) + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun checkSyncStatus(): ModuleSyncState = withContext(Dispatchers.IO) { + val installed = getInstalledModule() + if (installed == null) { + ModuleSyncState.NeedsInstall( + bundledVersion = ModuleConfig.BUNDLED_VERSION_NAME, + bundledVersionCode = ModuleConfig.BUNDLED_VERSION_CODE + ) + } else if (installed.versionCode < ModuleConfig.BUNDLED_VERSION_CODE) { + ModuleSyncState.NeedsUpdate( + currentVersion = installed.version, + currentVersionCode = installed.versionCode, + bundledVersion = ModuleConfig.BUNDLED_VERSION_NAME, + bundledVersionCode = ModuleConfig.BUNDLED_VERSION_CODE + ) + } else { + ModuleSyncState.Idle + } + } + + suspend fun syncModule( + context: Context, + onProgress: suspend (SyncStep, Float) -> Unit + ): Result = withContext(Dispatchers.IO) { + try { + onProgress(SyncStep.PREPARING, 0.1f) + val cacheZip = File(context.cacheDir, ModuleConfig.ASSET_MODULE_ZIP) + + var hasZipInAssets = false + try { + context.assets.open(ModuleConfig.ASSET_MODULE_ZIP).use { input -> + FileOutputStream(cacheZip).use { output -> + input.copyTo(output) + } + } + hasZipInAssets = true + } catch (_: Exception) { + hasZipInAssets = false + } + + onProgress(SyncStep.EXTRACTING, 0.35f) + val modDir = ModuleConfig.MODULE_PATH + + if (hasZipInAssets && cacheZip.exists()) { + onProgress(SyncStep.INSTALLING, 0.6f) + val destTmp = "/data/local/tmp/${ModuleConfig.ASSET_MODULE_ZIP}" + RootBridge.execute("cp \"${cacheZip.absolutePath}\" \"$destTmp\"") + RootBridge.execute("mkdir -p \"$modDir\" && unzip -o \"$destTmp\" -d \"$modDir\"") + RootBridge.execute("rm -f \"$destTmp\"") + } else { + onProgress(SyncStep.INSTALLING, 0.6f) + RootBridge.execute("mkdir -p \"$modDir/state\" \"$modDir/system/bin\" \"$modDir/bin\" /data/adb/ksu/bin") + + val propContent = """ + id=${ModuleConfig.MODULE_ID} + name=${ModuleConfig.MODULE_NAME} + version=${ModuleConfig.BUNDLED_VERSION_NAME} + versionCode=${ModuleConfig.BUNDLED_VERSION_CODE} + author=${ModuleConfig.MODULE_AUTHOR} + description=${ModuleConfig.MODULE_DESCRIPTION} + """.trimIndent() + val tmpProp = File(context.cacheDir, "module.prop") + tmpProp.writeText(propContent + "\n") + RootBridge.execute("cp \"${tmpProp.absolutePath}\" \"${ModuleConfig.MODULE_PROP_PATH}\" && chmod 644 \"${ModuleConfig.MODULE_PROP_PATH}\"") + tmpProp.delete() + } + + onProgress(SyncStep.CONFIGURING_PERMISSIONS, 0.85f) + RootBridge.execute("rm -f \"$modDir/disable\"") + RootBridge.execute("chmod -R 755 \"$modDir\"") + RootBridge.execute("chmod -R 755 \"$modDir/bin\" 2>/dev/null") + RootBridge.execute("chmod 755 \"${ModuleConfig.MODULE_SYSTEM_BIN_WRAPPER}\" 2>/dev/null") + RootBridge.execute("ln -sf \"${ModuleConfig.MODULE_SYSTEM_BIN_WRAPPER}\" \"${ModuleConfig.KSU_GLOBAL_BIN_LINK}\" 2>/dev/null") + RootBridge.execute("chmod 755 \"${ModuleConfig.KSU_GLOBAL_BIN_LINK}\" 2>/dev/null") + + // Auto start daemon + RootBridge.execute("nohup sh \"${ModuleConfig.MODULE_SERVICE_SCRIPT}\" >/dev/null 2>&1 &") + + onProgress(SyncStep.COMPLETED, 1.0f) + Result.success(Unit) + } catch (e: Exception) { + Result.failure(e) + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleState.kt b/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleState.kt new file mode 100644 index 0000000..95d2272 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleState.kt @@ -0,0 +1,7 @@ +package com.lzxnone.tailscalemanager.core.module + +enum class ModuleState { + NOT_INSTALLED, + ENABLED, + DISABLED +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleSyncState.kt b/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleSyncState.kt new file mode 100644 index 0000000..33980be --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/core/module/ModuleSyncState.kt @@ -0,0 +1,24 @@ +package com.lzxnone.tailscalemanager.core.module + +enum class SyncStep { + PREPARING, + EXTRACTING, + INSTALLING, + CONFIGURING_PERMISSIONS, + COMPLETED +} + +sealed class ModuleSyncState { + data object Idle : ModuleSyncState() + data object Checking : ModuleSyncState() + data class NeedsInstall(val bundledVersion: String, val bundledVersionCode: Long) : ModuleSyncState() + data class NeedsUpdate( + val currentVersion: String, + val currentVersionCode: Long, + val bundledVersion: String, + val bundledVersionCode: Long + ) : ModuleSyncState() + data class Syncing(val step: SyncStep, val progress: Float) : ModuleSyncState() + data object Success : ModuleSyncState() + data class Error(val errorMessage: String) : ModuleSyncState() +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/core/root/RootBridge.kt b/app/src/main/java/com/lzxnone/tailscalemanager/core/root/RootBridge.kt new file mode 100644 index 0000000..6f9c7f6 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/core/root/RootBridge.kt @@ -0,0 +1,53 @@ +package com.lzxnone.tailscalemanager.core.root + +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import java.io.BufferedReader +import java.io.InputStreamReader + +object RootBridge { + + suspend fun checkRootAccess(): Boolean = withContext(Dispatchers.IO) { + try { + val result = execute("id") + result.isSuccess && result.stdout.contains("uid=0") + } catch (_: Exception) { + false + } + } + + suspend fun execute(command: String): ShellResult = withContext(Dispatchers.IO) { + try { + val process = ProcessBuilder("su", "-c", command).start() + val stdoutReader = BufferedReader(InputStreamReader(process.inputStream)) + val stderrReader = BufferedReader(InputStreamReader(process.errorStream)) + + val stdoutBuilder = StringBuilder() + val stderrBuilder = StringBuilder() + + var line: String? + while (stdoutReader.readLine().also { line = it } != null) { + if (stdoutBuilder.isNotEmpty()) stdoutBuilder.append("\n") + stdoutBuilder.append(line) + } + + while (stderrReader.readLine().also { line = it } != null) { + if (stderrBuilder.isNotEmpty()) stderrBuilder.append("\n") + stderrBuilder.append(line) + } + + val exitCode = process.waitFor() + ShellResult( + exitCode = exitCode, + stdout = stdoutBuilder.toString(), + stderr = stderrBuilder.toString() + ) + } catch (e: Exception) { + ShellResult( + exitCode = -1, + stdout = "", + stderr = e.message ?: "Unknown process execution error" + ) + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/core/root/RootState.kt b/app/src/main/java/com/lzxnone/tailscalemanager/core/root/RootState.kt new file mode 100644 index 0000000..18f1e59 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/core/root/RootState.kt @@ -0,0 +1,16 @@ +package com.lzxnone.tailscalemanager.core.root + +enum class RootState { + CHECKING, + GRANTED, + DENIED +} + +data class ShellResult( + val exitCode: Int, + val stdout: String, + val stderr: String +) { + val isSuccess: Boolean + get() = exitCode == 0 +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/core/service/ServiceState.kt b/app/src/main/java/com/lzxnone/tailscalemanager/core/service/ServiceState.kt new file mode 100644 index 0000000..4476193 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/core/service/ServiceState.kt @@ -0,0 +1,9 @@ +package com.lzxnone.tailscalemanager.core.service + +enum class ServiceState { + RUNNING, + STOPPED, + STARTING, + STOPPING, + UNKNOWN +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/core/service/TailscaleController.kt b/app/src/main/java/com/lzxnone/tailscalemanager/core/service/TailscaleController.kt new file mode 100644 index 0000000..9a45797 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/core/service/TailscaleController.kt @@ -0,0 +1,564 @@ +package com.lzxnone.tailscalemanager.core.service + +import com.lzxnone.tailscalemanager.core.module.ModuleConfig +import com.lzxnone.tailscalemanager.core.root.RootBridge +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.delay +import kotlinx.coroutines.withContext + +object TailscaleController { + + private val tailscaleBin: String + get() = if (isWrapperAvailable()) { + ModuleConfig.MODULE_SYSTEM_BIN_WRAPPER + } else { + "${ModuleConfig.MODULE_PATH}/bin/tailscale_bin --socket=\"${ModuleConfig.MODULE_SOCKET_PATH}\"" + } + + private fun isWrapperAvailable(): Boolean { + return true + } + + suspend fun getServiceState(): ServiceState = withContext(Dispatchers.IO) { + val pidCheck = RootBridge.execute("pgrep -f tailscaled") + if (!pidCheck.isSuccess || pidCheck.stdout.trim().isEmpty()) { + return@withContext ServiceState.STOPPED + } + + // Tailscaled is running, check if Tailscale backend is active + val statusCheck = RootBridge.execute("$tailscaleBin status") + if (statusCheck.isSuccess) { + val output = statusCheck.stdout + if (output.contains("Tailscale is stopped") || output.contains("Logged out")) { + ServiceState.STOPPED + } else { + ServiceState.RUNNING + } + } else { + // Process exists but status returns non-zero, check socket + val socketCheck = RootBridge.execute("[ -S \"${ModuleConfig.MODULE_SOCKET_PATH}\" ] && echo 1 || echo 0") + if (socketCheck.stdout.trim() == "1") { + ServiceState.RUNNING + } else { + ServiceState.STOPPED + } + } + } + + suspend fun startService(): Result = withContext(Dispatchers.IO) { + try { + val pidCheck = RootBridge.execute("pgrep -f tailscaled") + if (!pidCheck.isSuccess || pidCheck.stdout.trim().isEmpty()) { + // Launch daemon service + RootBridge.execute("nohup sh \"${ModuleConfig.MODULE_SERVICE_SCRIPT}\" >/dev/null 2>&1 &") + + // Wait for socket to become ready (max 5s) + var retries = 10 + while (retries > 0) { + delay(500) + val socketCheck = RootBridge.execute("[ -S \"${ModuleConfig.MODULE_SOCKET_PATH}\" ] && echo 1 || echo 0") + if (socketCheck.stdout.trim() == "1") break + retries-- + } + } + + // Bring up connection + val upResult = RootBridge.execute("$tailscaleBin up --accept-routes --accept-dns=false") + if (upResult.isSuccess || upResult.stdout.contains("Success") || upResult.stderr.isEmpty()) { + Result.success(Unit) + } else { + Result.failure(Exception(upResult.stderr.ifEmpty { upResult.stdout })) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun stopService(): Result = withContext(Dispatchers.IO) { + try { + val downResult = RootBridge.execute("$tailscaleBin down") + if (downResult.isSuccess) { + Result.success(Unit) + } else { + // If down failed, terminate daemon process gracefully + RootBridge.execute("killall tailscaled 2>/dev/null") + Result.success(Unit) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun getDeviceStatus(): com.lzxnone.tailscalemanager.model.DeviceStatus = withContext(Dispatchers.IO) { + try { + val result = RootBridge.execute("$tailscaleBin status --json") + if (!result.isSuccess || result.stdout.trim().isEmpty()) { + return@withContext com.lzxnone.tailscalemanager.model.DeviceStatus() + } + + val json = org.json.JSONObject(result.stdout) + val self = json.optJSONObject("Self") + val hostName = self?.optString("HostName")?.ifEmpty { "--" } ?: "--" + + val ips = self?.optJSONArray("TailscaleIPs") ?: json.optJSONArray("TailscaleIPs") + val ip = ips?.optString(0)?.ifEmpty { "--" } ?: "--" + + val backendState = json.optString("BackendState", "Stopped") + val authUrl = json.optString("AuthURL", "") + + var account = "" + var display = "" + val userObj = json.optJSONObject("User") + if (userObj != null && userObj.length() > 0) { + val firstKey = userObj.keys().next() + val targetUser = userObj.optJSONObject(firstKey) + account = targetUser?.optString("LoginName", "") ?: "" + display = targetUser?.optString("DisplayName", "") ?: "" + } + + com.lzxnone.tailscalemanager.model.DeviceStatus( + hostName = hostName, + ipAddress = ip, + accountName = account, + displayName = display, + backendState = backendState, + authUrl = authUrl + ) + } catch (_: Exception) { + com.lzxnone.tailscalemanager.model.DeviceStatus() + } + } + + suspend fun updateHostname(newHostname: String): Result = withContext(Dispatchers.IO) { + try { + val sanitized = newHostname.trim().replace(" ", "-").filter { it.isLetterOrDigit() || it == '-' } + if (sanitized.isEmpty()) { + return@withContext Result.failure(Exception("Hostname cannot be empty")) + } + + val setResult = RootBridge.execute("$tailscaleBin set --hostname=$sanitized") + if (setResult.isSuccess || setResult.stderr.isEmpty()) { + Result.success(Unit) + } else { + val upResult = RootBridge.execute("$tailscaleBin up --hostname=$sanitized --accept-routes --accept-dns=false") + if (upResult.isSuccess || upResult.stderr.isEmpty()) { + Result.success(Unit) + } else { + Result.failure(Exception(setResult.stderr.ifEmpty { upResult.stderr })) + } + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun getAccountProfiles(): List = withContext(Dispatchers.IO) { + try { + val result = RootBridge.execute("$tailscaleBin switch --list --json") + if (!result.isSuccess || result.stdout.trim().isEmpty()) { + return@withContext emptyList() + } + val array = org.json.JSONArray(result.stdout) + val list = mutableListOf() + for (i in 0 until array.length()) { + val item = array.getJSONObject(i) + list.add( + com.lzxnone.tailscalemanager.model.AccountProfile( + id = item.optString("id", ""), + nickname = item.optString("nickname", ""), + tailnet = item.optString("tailnet", ""), + account = item.optString("account", ""), + isSelected = item.optBoolean("selected", false) + ) + ) + } + list + } catch (_: Exception) { + emptyList() + } + } + + suspend fun switchAccount(idOrName: String): Result = withContext(Dispatchers.IO) { + try { + val result = RootBridge.execute("$tailscaleBin switch \"$idOrName\"") + if (result.isSuccess) { + Result.success(Unit) + } else { + Result.failure(Exception(result.stderr.ifEmpty { result.stdout })) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun generateLoginUrl(): Result = withContext(Dispatchers.IO) { + try { + // First check status json if AuthURL is already present + val statusResult = RootBridge.execute("$tailscaleBin status --json") + if (statusResult.isSuccess) { + val json = org.json.JSONObject(statusResult.stdout) + val url = json.optString("AuthURL", "") + if (url.isNotEmpty() && url.startsWith("http")) { + return@withContext Result.success(url) + } + } + + // Otherwise, invoke login command and capture the URL + val loginCmd = "$tailscaleBin login --qr=false 2>&1" + val process = ProcessBuilder("su", "-c", loginCmd).start() + val reader = java.io.BufferedReader(java.io.InputStreamReader(process.inputStream)) + var targetUrl = "" + val startTime = System.currentTimeMillis() + while (System.currentTimeMillis() - startTime < 6000) { + if (reader.ready()) { + val line = reader.readLine() + if (line != null) { + val trimmed = line.trim() + if (trimmed.startsWith("https://login.tailscale.com/a/")) { + targetUrl = trimmed + break + } + } + } else { + delay(100) + } + } + + if (targetUrl.isNotEmpty()) { + Result.success(targetUrl) + } else { + Result.failure(Exception("Timeout waiting for login URL")) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun logout(): Result = withContext(Dispatchers.IO) { + try { + val result = RootBridge.execute("$tailscaleBin logout") + if (result.isSuccess) { + Result.success(Unit) + } else { + Result.failure(Exception(result.stderr.ifEmpty { result.stdout })) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun getExitNodeState(): com.lzxnone.tailscalemanager.model.ExitNodeState = withContext(Dispatchers.IO) { + try { + val result = RootBridge.execute("$tailscaleBin status --json") + if (!result.isSuccess || result.stdout.trim().isEmpty()) { + return@withContext com.lzxnone.tailscalemanager.model.ExitNodeState() + } + + var allowLanAccess = false + var isAdvertising = false + var hasPrefs = false + + // Query preferences for accurate local runtime settings + val prefsResult = RootBridge.execute("$tailscaleBin debug prefs") + if (prefsResult.isSuccess && prefsResult.stdout.trim().isNotEmpty()) { + try { + val prefsJson = org.json.JSONObject(prefsResult.stdout) + allowLanAccess = prefsJson.optBoolean("ExitNodeAllowLANAccess", false) + val advRoutes = prefsJson.optJSONArray("AdvertiseRoutes") + if (advRoutes != null) { + for (i in 0 until advRoutes.length()) { + val r = advRoutes.optString(i) + if (r == "0.0.0.0/0" || r == "::/0") { + isAdvertising = true + break + } + } + } + hasPrefs = true + } catch (_: Exception) {} + } + + val json = org.json.JSONObject(result.stdout) + val self = json.optJSONObject("Self") + // Only fall back to cloud map Self.ExitNodeOption if local debug prefs was unavailable + if (!hasPrefs) { + isAdvertising = self?.optBoolean("ExitNodeOption", false) ?: false + } + + var activeExitNodeId = "" + var activeExitNodeName = "" + val peerList = mutableListOf() + + val peersObj = json.optJSONObject("Peer") + if (peersObj != null) { + val keys = peersObj.keys() + while (keys.hasNext()) { + val k = keys.next() + val peer = peersObj.optJSONObject(k) ?: continue + val isOption = peer.optBoolean("ExitNodeOption", false) + val isCurrent = peer.optBoolean("ExitNode", false) + val host = peer.optString("HostName", "--") + val ips = peer.optJSONArray("TailscaleIPs") + val ip = ips?.optString(0) ?: "--" + val isOnline = peer.optBoolean("Online", false) + + if (isCurrent) { + activeExitNodeId = ip + activeExitNodeName = host + } + + if (isOption) { + peerList.add( + com.lzxnone.tailscalemanager.model.ExitNodePeer( + id = ip, + hostname = host, + ip = ip, + isCurrentExitNode = isCurrent, + isOnline = isOnline + ) + ) + } + } + } + + com.lzxnone.tailscalemanager.model.ExitNodeState( + currentExitNodeId = activeExitNodeId, + currentExitNodeName = activeExitNodeName, + allowLanAccess = allowLanAccess, + isAdvertisingExitNode = isAdvertising, + availablePeers = peerList + ) + } catch (_: Exception) { + com.lzxnone.tailscalemanager.model.ExitNodeState() + } + } + + suspend fun setExitNode(nodeIpOrName: String, allowLan: Boolean): Result = withContext(Dispatchers.IO) { + try { + val lanFlag = if (allowLan) "--exit-node-allow-lan-access=true" else "--exit-node-allow-lan-access=false" + val cmd = if (nodeIpOrName.isEmpty()) { + "$tailscaleBin set --exit-node=" + } else { + "$tailscaleBin set --exit-node=$nodeIpOrName $lanFlag" + } + val result = RootBridge.execute(cmd) + if (result.isSuccess || result.stderr.isEmpty()) { + Result.success(Unit) + } else { + Result.failure(Exception(result.stderr.ifEmpty { result.stdout })) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun setAllowLanAccess(allow: Boolean): Result = withContext(Dispatchers.IO) { + try { + val flag = if (allow) "--exit-node-allow-lan-access=true" else "--exit-node-allow-lan-access=false" + val result = RootBridge.execute("$tailscaleBin set $flag") + if (result.isSuccess || result.stderr.isEmpty()) { + Result.success(Unit) + } else { + Result.failure(Exception(result.stderr.ifEmpty { result.stdout })) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun setAdvertiseExitNode(enabled: Boolean): Result = withContext(Dispatchers.IO) { + try { + if (enabled) { + // Enable Linux kernel IP forwarding and NAT masquerade automatically + RootBridge.execute("echo 1 > /proc/sys/net/ipv4/ip_forward") + RootBridge.execute("echo 1 > /proc/sys/net/ipv6/conf/all/forwarding") + RootBridge.execute("iptables -t nat -C POSTROUTING -o wlan+ -j MASQUERADE 2>/dev/null || iptables -t nat -A POSTROUTING -o wlan+ -j MASQUERADE 2>/dev/null") + RootBridge.execute("iptables -t nat -C POSTROUTING -o rmnet+ -j MASQUERADE 2>/dev/null || iptables -t nat -A POSTROUTING -o rmnet+ -j MASQUERADE 2>/dev/null") + } else { + RootBridge.execute("iptables -t nat -D POSTROUTING -o wlan+ -j MASQUERADE 2>/dev/null") + RootBridge.execute("iptables -t nat -D POSTROUTING -o rmnet+ -j MASQUERADE 2>/dev/null") + } + val flag = if (enabled) "--advertise-exit-node=true" else "--advertise-exit-node=false" + val result = RootBridge.execute("$tailscaleBin set $flag") + if (result.isSuccess || result.stderr.isEmpty()) { + Result.success(Unit) + } else { + Result.failure(Exception(result.stderr.ifEmpty { result.stdout })) + } + } catch (e: Exception) { + Result.failure(e) + } + } + + suspend fun getServiceVersion(): String = withContext(Dispatchers.IO) { + try { + val result = RootBridge.execute("$tailscaleBin version | head -n 1") + if (result.isSuccess && result.stdout.trim().isNotEmpty()) { + result.stdout.trim().lineSequence().firstOrNull()?.trim() ?: "" + } else { + "" + } + } catch (_: Exception) { + "" + } + } + + suspend fun getDeviceList(): List = withContext(Dispatchers.IO) { + try { + val result = RootBridge.execute("$tailscaleBin status --json") + if (!result.isSuccess || result.stdout.trim().isEmpty()) { + return@withContext emptyList() + } + + val list = mutableListOf() + val json = org.json.JSONObject(result.stdout) + + // 对端设备 (Peers - 排除本机) + val peersObj = json.optJSONObject("Peer") + if (peersObj != null) { + val keys = peersObj.keys() + while (keys.hasNext()) { + val k = keys.next() + val peer = peersObj.optJSONObject(k) ?: continue + val name = peer.optString("HostName", "--") + val ips = peer.optJSONArray("TailscaleIPs") + val ip = ips?.optString(0) ?: "--" + val os = peer.optString("OS", "unknown") + val isOnline = peer.optBoolean("Online", false) + val curAddr = peer.optString("CurAddr", "") + val relay = peer.optString("Relay", "") + val isExitNode = peer.optBoolean("ExitNode", false) + val lastSeen = peer.optString("LastSeen", "") + val version = peer.optString("TailscaleVersion", peer.optString("Version", "")) + + list.add( + com.lzxnone.tailscalemanager.model.TailscaleDevice( + id = peer.optString("ID", k), + name = name, + ip = ip, + os = os, + version = version, + isOnline = isOnline, + isSelf = false, + curAddr = curAddr, + relay = relay, + lastSeen = lastSeen, + isExitNode = isExitNode + ) + ) + } + } + + // 按设备名称字母升序排列 + list.sortedBy { it.name.lowercase() } + } catch (_: Exception) { + emptyList() + } + } + + suspend fun pingDevice(ipOrHost: String): com.lzxnone.tailscalemanager.model.PingResult = withContext(Dispatchers.IO) { + try { + val cmd = "$tailscaleBin ping --c=2 --timeout=4s $ipOrHost" + val result = RootBridge.execute(cmd) + val output = (result.stdout.ifEmpty { result.stderr }).trim() + + val regex = """pong from .*? via (.+?) in (\d+(?:\.\d+)?m?s)""".toRegex(RegexOption.IGNORE_CASE) + val match = regex.find(output) + + if (match != null) { + val via = match.groupValues[1].trim() + val latency = match.groupValues[2].trim() + val isDirect = !via.contains("DERP", ignoreCase = true) + com.lzxnone.tailscalemanager.model.PingResult( + isSuccess = true, + isDirect = isDirect, + relayOrEndpoint = via, + latency = latency, + message = output + ) + } else if (result.isSuccess && output.contains("pong from")) { + com.lzxnone.tailscalemanager.model.PingResult( + isSuccess = true, + isDirect = false, + relayOrEndpoint = "Relay", + latency = "", + message = output + ) + } else { + com.lzxnone.tailscalemanager.model.PingResult( + isSuccess = false, + isDirect = false, + relayOrEndpoint = "", + latency = "", + message = output.ifEmpty { "Ping 超时无响应" } + ) + } + } catch (e: Exception) { + com.lzxnone.tailscalemanager.model.PingResult( + isSuccess = false, + isDirect = false, + relayOrEndpoint = "", + latency = "", + message = e.localizedMessage ?: "Ping 执行异常" + ) + } + } + + suspend fun getNetworkPrefs(): com.lzxnone.tailscalemanager.model.TailscaleNetworkPrefs = withContext(Dispatchers.IO) { + try { + val result = RootBridge.execute("$tailscaleBin debug prefs") + if (result.isSuccess && result.stdout.trim().isNotEmpty()) { + val json = org.json.JSONObject(result.stdout) + val shieldsUp = json.optBoolean("ShieldsUp", false) + val corpDns = json.optBoolean("CorpDNS", true) + val routeAll = json.optBoolean("RouteAll", false) + val autoUpdateObj = json.optJSONObject("AutoUpdate") + val autoUpdate = autoUpdateObj?.optBoolean("Apply", true) ?: true + + com.lzxnone.tailscalemanager.model.TailscaleNetworkPrefs( + allowIncoming = !shieldsUp, + useTailscaleDns = corpDns, + acceptSubnetRoutes = routeAll, + autoUpdate = autoUpdate + ) + } else { + com.lzxnone.tailscalemanager.model.TailscaleNetworkPrefs() + } + } catch (_: Exception) { + com.lzxnone.tailscalemanager.model.TailscaleNetworkPrefs() + } + } + + suspend fun setAllowIncoming(enabled: Boolean): Result = withContext(Dispatchers.IO) { + val flag = if (enabled) "--shields-up=false" else "--shields-up=true" + executeTailscaleSet(flag) + } + + suspend fun setUseTailscaleDns(enabled: Boolean): Result = withContext(Dispatchers.IO) { + val flag = if (enabled) "--accept-dns=true" else "--accept-dns=false" + executeTailscaleSet(flag) + } + + suspend fun setAcceptSubnetRoutes(enabled: Boolean): Result = withContext(Dispatchers.IO) { + val flag = if (enabled) "--accept-routes=true" else "--accept-routes=false" + executeTailscaleSet(flag) + } + + suspend fun setAutoUpdate(enabled: Boolean): Result = withContext(Dispatchers.IO) { + val flag = if (enabled) "--auto-update=true" else "--auto-update=false" + executeTailscaleSet(flag) + } + + suspend fun resetNetworkPrefs(): Result = withContext(Dispatchers.IO) { + executeTailscaleSet("--shields-up=false --accept-dns=true --accept-routes=false") + } + + private suspend fun executeTailscaleSet(flags: String): Result { + val result = RootBridge.execute("$tailscaleBin set $flags") + return if (result.isSuccess || result.stderr.isEmpty()) { + Result.success(Unit) + } else { + Result.failure(Exception(result.stderr.ifEmpty { result.stdout })) + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/core/settings/AppPreferences.kt b/app/src/main/java/com/lzxnone/tailscalemanager/core/settings/AppPreferences.kt new file mode 100644 index 0000000..c763c75 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/core/settings/AppPreferences.kt @@ -0,0 +1,84 @@ +package com.lzxnone.tailscalemanager.core.settings + +import android.content.Context +import android.content.SharedPreferences +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow + +object AppPreferences { + + private const val PREFS_NAME = "tailscale_manager_prefs" + private const val KEY_LANGUAGE = "language" + private const val KEY_THEME_MODE = "theme_mode" + private const val KEY_DYNAMIC_COLOR = "dynamic_color" + private const val KEY_CUSTOM_COLOR = "custom_color" + private const val KEY_SUPPRESSED_APP_UPDATE = "suppressed_app_update_version" + private const val KEY_SUPPRESSED_MODULE_UPDATE = "suppressed_module_update_version" + + private lateinit var prefs: SharedPreferences + + private val _language = MutableStateFlow("system") + val language: StateFlow = _language.asStateFlow() + + private val _themeMode = MutableStateFlow("system") + val themeMode: StateFlow = _themeMode.asStateFlow() + + private val _dynamicColor = MutableStateFlow(true) + val dynamicColor: StateFlow = _dynamicColor.asStateFlow() + + private val _customColorKey = MutableStateFlow("blue") + val customColorKey: StateFlow = _customColorKey.asStateFlow() + + fun init(context: Context) { + prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) + _language.value = prefs.getString(KEY_LANGUAGE, "system") ?: "system" + _themeMode.value = prefs.getString(KEY_THEME_MODE, "system") ?: "system" + _dynamicColor.value = prefs.getBoolean(KEY_DYNAMIC_COLOR, true) + _customColorKey.value = prefs.getString(KEY_CUSTOM_COLOR, "blue") ?: "blue" + } + + fun setLanguage(lang: String) { + _language.value = lang + prefs.edit().putString(KEY_LANGUAGE, lang).apply() + } + + fun setLanguage(context: Context, lang: String) { + setLanguage(lang) + } + + fun setThemeMode(mode: String) { + _themeMode.value = mode + prefs.edit().putString(KEY_THEME_MODE, mode).apply() + } + + fun setDynamicColor(enabled: Boolean) { + _dynamicColor.value = enabled + prefs.edit().putBoolean(KEY_DYNAMIC_COLOR, enabled).apply() + } + + fun setCustomColorKey(key: String) { + _customColorKey.value = key + prefs.edit().putString(KEY_CUSTOM_COLOR, key).apply() + } + + fun getSuppressedAppUpdateVersion(): Long { + return if (::prefs.isInitialized) prefs.getLong(KEY_SUPPRESSED_APP_UPDATE, -1L) else -1L + } + + fun setSuppressedAppUpdateVersion(versionCode: Long) { + if (::prefs.isInitialized) { + prefs.edit().putLong(KEY_SUPPRESSED_APP_UPDATE, versionCode).apply() + } + } + + fun getSuppressedModuleUpdateVersion(): Long { + return if (::prefs.isInitialized) prefs.getLong(KEY_SUPPRESSED_MODULE_UPDATE, -1L) else -1L + } + + fun setSuppressedModuleUpdateVersion(versionCode: Long) { + if (::prefs.isInitialized) { + prefs.edit().putLong(KEY_SUPPRESSED_MODULE_UPDATE, versionCode).apply() + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/core/update/AppUpdateManager.kt b/app/src/main/java/com/lzxnone/tailscalemanager/core/update/AppUpdateManager.kt new file mode 100644 index 0000000..d4657ad --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/core/update/AppUpdateManager.kt @@ -0,0 +1,57 @@ +package com.lzxnone.tailscalemanager.core.update + +import com.lzxnone.tailscalemanager.model.AppUpdateInfo +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.withContext +import org.json.JSONObject +import java.io.BufferedReader +import java.io.InputStreamReader +import java.net.HttpURLConnection +import java.net.URL + +object AppUpdateManager { + + private const val UPDATE_URL = "https://update.lzxnone.cloud/tailscale_manager/version.json" + + suspend fun checkAppUpdate(): Result = withContext(Dispatchers.IO) { + try { + val url = URL(UPDATE_URL) + val connection = (url.openConnection() as HttpURLConnection).apply { + connectTimeout = 8000 + readTimeout = 8000 + requestMethod = "GET" + setRequestProperty("Accept", "application/json") + setRequestProperty("User-Agent", "TailscaleManager-Android") + } + + val responseCode = connection.responseCode + if (responseCode == HttpURLConnection.HTTP_OK) { + val reader = BufferedReader(InputStreamReader(connection.inputStream, Charsets.UTF_8)) + val response = reader.use { it.readText() } + connection.disconnect() + + val json = JSONObject(response) + val versionCode = json.optLong("versionCode", 0L) + val versionName = json.optString("versionName", "") + val changelog = json.optString("changelog", "") + val downloadUrl = json.optString("downloadUrl", "") + val apkSize = json.optString("apkSize", "") + + Result.success( + AppUpdateInfo( + versionCode = versionCode, + versionName = versionName, + changelog = changelog, + downloadUrl = downloadUrl, + apkSize = apkSize + ) + ) + } else { + connection.disconnect() + Result.failure(Exception("HTTP error $responseCode")) + } + } catch (e: Exception) { + Result.failure(e) + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/model/AccountProfile.kt b/app/src/main/java/com/lzxnone/tailscalemanager/model/AccountProfile.kt new file mode 100644 index 0000000..c672d74 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/model/AccountProfile.kt @@ -0,0 +1,9 @@ +package com.lzxnone.tailscalemanager.model + +data class AccountProfile( + val id: String, + val nickname: String, + val tailnet: String, + val account: String, + val isSelected: Boolean +) diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/model/AppUpdateInfo.kt b/app/src/main/java/com/lzxnone/tailscalemanager/model/AppUpdateInfo.kt new file mode 100644 index 0000000..5c7f493 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/model/AppUpdateInfo.kt @@ -0,0 +1,9 @@ +package com.lzxnone.tailscalemanager.model + +data class AppUpdateInfo( + val versionCode: Long, + val versionName: String, + val changelog: String, + val downloadUrl: String, + val apkSize: String +) diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/model/DeviceStatus.kt b/app/src/main/java/com/lzxnone/tailscalemanager/model/DeviceStatus.kt new file mode 100644 index 0000000..ab4e9f8 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/model/DeviceStatus.kt @@ -0,0 +1,10 @@ +package com.lzxnone.tailscalemanager.model + +data class DeviceStatus( + val hostName: String = "--", + val ipAddress: String = "--", + val accountName: String = "", + val displayName: String = "", + val backendState: String = "Stopped", + val authUrl: String = "" +) diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/model/ExitNodeModels.kt b/app/src/main/java/com/lzxnone/tailscalemanager/model/ExitNodeModels.kt new file mode 100644 index 0000000..cb96db9 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/model/ExitNodeModels.kt @@ -0,0 +1,17 @@ +package com.lzxnone.tailscalemanager.model + +data class ExitNodePeer( + val id: String, + val hostname: String, + val ip: String, + val isCurrentExitNode: Boolean, + val isOnline: Boolean +) + +data class ExitNodeState( + val currentExitNodeId: String = "", + val currentExitNodeName: String = "", + val allowLanAccess: Boolean = false, + val isAdvertisingExitNode: Boolean = false, + val availablePeers: List = emptyList() +) diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/model/ModuleInfo.kt b/app/src/main/java/com/lzxnone/tailscalemanager/model/ModuleInfo.kt new file mode 100644 index 0000000..7b9a4db --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/model/ModuleInfo.kt @@ -0,0 +1,15 @@ +package com.lzxnone.tailscalemanager.model + +/** + * Represents metadata of the Tailscale native module. + */ +data class ModuleInfo( + val id: String, + val name: String, + val version: String, + val versionCode: Long, + val author: String, + val description: String, + val isInstalled: Boolean = false, + val isEnabled: Boolean = true +) diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/model/TailscaleDevice.kt b/app/src/main/java/com/lzxnone/tailscalemanager/model/TailscaleDevice.kt new file mode 100644 index 0000000..9c8dd48 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/model/TailscaleDevice.kt @@ -0,0 +1,23 @@ +package com.lzxnone.tailscalemanager.model + +data class TailscaleDevice( + val id: String, + val name: String, + val ip: String, + val os: String, + val version: String = "", + val isOnline: Boolean, + val isSelf: Boolean = false, + val curAddr: String = "", + val relay: String = "", + val lastSeen: String = "", + val isExitNode: Boolean = false +) + +data class PingResult( + val isSuccess: Boolean, + val isDirect: Boolean = false, + val relayOrEndpoint: String = "", + val latency: String = "", + val message: String = "" +) diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/model/TailscaleNetworkPrefs.kt b/app/src/main/java/com/lzxnone/tailscalemanager/model/TailscaleNetworkPrefs.kt new file mode 100644 index 0000000..91c3790 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/model/TailscaleNetworkPrefs.kt @@ -0,0 +1,8 @@ +package com.lzxnone.tailscalemanager.model + +data class TailscaleNetworkPrefs( + val allowIncoming: Boolean = true, + val useTailscaleDns: Boolean = true, + val acceptSubnetRoutes: Boolean = false, + val autoUpdate: Boolean = true +) diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/AppBottomBar.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/AppBottomBar.kt new file mode 100644 index 0000000..bc4241f --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/AppBottomBar.kt @@ -0,0 +1,66 @@ +package com.lzxnone.tailscalemanager.ui.components + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Dashboard +import androidx.compose.material.icons.filled.Devices +import androidx.compose.material.icons.filled.Settings +import androidx.compose.material3.Icon +import androidx.compose.material3.NavigationBar +import androidx.compose.material3.NavigationBarItem +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import com.lzxnone.tailscalemanager.R + +@Composable +fun AppBottomBar( + currentRoute: String = "dashboard", + onNavigate: (String) -> Unit = {} +) { + NavigationBar { + // Tab 1: 仪表盘 + NavigationBarItem( + selected = currentRoute == "dashboard", + onClick = { onNavigate("dashboard") }, + icon = { + Icon( + imageVector = Icons.Default.Dashboard, + contentDescription = stringResource(R.string.nav_dashboard) + ) + }, + label = { + Text(text = stringResource(R.string.nav_dashboard)) + } + ) + + // Tab 2: 设备 + NavigationBarItem( + selected = currentRoute == "devices", + onClick = { onNavigate("devices") }, + icon = { + Icon( + imageVector = Icons.Default.Devices, + contentDescription = stringResource(R.string.nav_devices) + ) + }, + label = { + Text(text = stringResource(R.string.nav_devices)) + } + ) + + // Tab 3: 设置 + NavigationBarItem( + selected = currentRoute == "settings", + onClick = { onNavigate("settings") }, + icon = { + Icon( + imageVector = Icons.Default.Settings, + contentDescription = stringResource(R.string.nav_settings) + ) + }, + label = { + Text(text = stringResource(R.string.nav_settings)) + } + ) + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/AppTopBar.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/AppTopBar.kt new file mode 100644 index 0000000..b3f6669 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/AppTopBar.kt @@ -0,0 +1,53 @@ +package com.lzxnone.tailscalemanager.ui.components + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.AccountCircle +import androidx.compose.material.icons.outlined.Info +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import com.lzxnone.tailscalemanager.R + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun AppTopBar( + onAccountClick: () -> Unit, + onAboutClick: () -> Unit +) { + TopAppBar( + title = { + Text( + text = stringResource(R.string.top_bar_title), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold + ) + }, + actions = { + IconButton(onClick = onAccountClick) { + Icon( + imageVector = Icons.Default.AccountCircle, + contentDescription = stringResource(R.string.nav_account), + tint = MaterialTheme.colorScheme.primary + ) + } + IconButton(onClick = onAboutClick) { + Icon( + imageVector = Icons.Outlined.Info, + contentDescription = stringResource(R.string.section_about), + tint = MaterialTheme.colorScheme.primary + ) + } + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.surface, + titleContentColor = MaterialTheme.colorScheme.onSurface + ) + ) +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/AppUpdateDialog.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/AppUpdateDialog.kt new file mode 100644 index 0000000..ce94cde --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/AppUpdateDialog.kt @@ -0,0 +1,88 @@ +package com.lzxnone.tailscalemanager.ui.components + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.model.AppUpdateInfo + +@Composable +fun AppUpdateDialog( + updateInfo: AppUpdateInfo?, + onDownload: (String) -> Unit, + onDismiss: () -> Unit, + onDontShowAgain: (Long) -> Unit +) { + if (updateInfo == null) return + + val displayVersion = if (updateInfo.versionName.startsWith("v", ignoreCase = true)) { + "V" + updateInfo.versionName.substring(1) + } else { + "V${updateInfo.versionName}" + } + + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( + text = stringResource(R.string.update_dialog_title_format, displayVersion), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold + ) + }, + text = { + Column( + modifier = Modifier + .fillMaxWidth() + .verticalScroll(rememberScrollState()) + ) { + Text( + text = updateInfo.changelog, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface + ) + } + }, + confirmButton = { + Button( + onClick = { + onDownload(updateInfo.downloadUrl) + } + ) { + Text(text = stringResource(R.string.btn_download_update)) + } + }, + dismissButton = { + Row { + TextButton( + onClick = { + onDontShowAgain(updateInfo.versionCode) + } + ) { + Text(text = stringResource(R.string.btn_dont_show_again)) + } + TextButton(onClick = onDismiss) { + Text(text = stringResource(R.string.btn_cancel)) + } + } + } + ) +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/DeleteConfirmDialog.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/DeleteConfirmDialog.kt new file mode 100644 index 0000000..1410d29 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/DeleteConfirmDialog.kt @@ -0,0 +1,49 @@ +package com.lzxnone.tailscalemanager.ui.components + +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import com.lzxnone.tailscalemanager.R + +@Composable +fun DeleteConfirmDialog( + onConfirm: () -> Unit, + onDismiss: () -> Unit +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( + text = stringResource(R.string.module_delete_dialog_title), + style = MaterialTheme.typography.titleLarge + ) + }, + text = { + Text( + text = stringResource(R.string.module_delete_dialog_message), + style = MaterialTheme.typography.bodyMedium + ) + }, + confirmButton = { + Button( + onClick = onConfirm, + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.error, + contentColor = MaterialTheme.colorScheme.onError + ) + ) { + Text(text = stringResource(R.string.btn_confirm_delete)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(text = stringResource(R.string.btn_cancel)) + } + } + ) +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/DeviceCard.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/DeviceCard.kt new file mode 100644 index 0000000..7dee5cf --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/DeviceCard.kt @@ -0,0 +1,130 @@ +package com.lzxnone.tailscalemanager.ui.components + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.widget.Toast +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Edit +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.model.DeviceStatus + +@Composable +fun DeviceCard( + deviceStatus: DeviceStatus, + isLoggedIn: Boolean, + isServiceRunning: Boolean, + onEditClick: () -> Unit, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + val notLoggedInText = stringResource(R.string.account_not_logged_in) + val notConnectedText = stringResource(R.string.device_card_not_connected) + + val hostName = when { + !isLoggedIn -> notLoggedInText + isServiceRunning && deviceStatus.hostName.isNotEmpty() && deviceStatus.hostName != "--" -> deviceStatus.hostName + else -> notConnectedText + } + + val ipAddress = when { + !isLoggedIn -> notLoggedInText + isServiceRunning && deviceStatus.ipAddress.isNotEmpty() && deviceStatus.ipAddress != "--" -> deviceStatus.ipAddress + else -> notConnectedText + } + + val copiedToastText = stringResource(R.string.device_card_ip_copied) + val canCopy = isLoggedIn && isServiceRunning && deviceStatus.ipAddress.isNotEmpty() && deviceStatus.ipAddress != "--" + val canEdit = isLoggedIn && isServiceRunning + + Card( + modifier = modifier + .fillMaxWidth() + .clickable(enabled = canCopy) { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + val clip = ClipData.newPlainText("Tailscale IP", deviceStatus.ipAddress) + clipboard.setPrimaryClip(clip) + Toast.makeText(context, copiedToastText, Toast.LENGTH_SHORT).show() + }, + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLowest + ), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f)), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + // First line: Tailscale Device Hostname (or Not Logged In) + Text( + text = hostName, + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + color = if (!isLoggedIn) MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f) else MaterialTheme.colorScheme.onSurface + ) + + Spacer(modifier = Modifier.height(6.dp)) + + // Second line: Tailscale IP (or Not Logged In) + Text( + text = ipAddress, + style = MaterialTheme.typography.bodyLarge.copy( + fontFamily = if (canCopy) FontFamily.Monospace else FontFamily.Default, + letterSpacing = if (canCopy) 0.5.sp else 0.sp + ), + fontWeight = FontWeight.Medium, + color = when { + !isLoggedIn -> MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) + canCopy -> MaterialTheme.colorScheme.primary + else -> MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f) + } + ) + } + + // Edit Device Name Button + IconButton( + onClick = onEditClick, + enabled = canEdit, + modifier = Modifier.size(38.dp) + ) { + Icon( + imageVector = Icons.Outlined.Edit, + contentDescription = stringResource(R.string.device_btn_edit), + tint = if (canEdit) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.38f) + ) + } + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/EditHostnameDialog.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/EditHostnameDialog.kt new file mode 100644 index 0000000..9102ce3 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/EditHostnameDialog.kt @@ -0,0 +1,134 @@ +package com.lzxnone.tailscalemanager.ui.components + +import android.content.Context +import android.os.Build +import android.provider.Settings +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.RestartAlt +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import com.lzxnone.tailscalemanager.R + +private fun getDefaultDeviceHostname(context: Context): String { + val rawName = try { + Settings.Global.getString(context.contentResolver, "device_name") + ?: Settings.Secure.getString(context.contentResolver, "bluetooth_name") + ?: Build.MODEL + } catch (e: Exception) { + Build.MODEL + } ?: Build.MODEL + + val sanitized = rawName.trim() + .replace(Regex("[\\s_]+"), "-") + .filter { it.isLetterOrDigit() || it == '-' } + .trim('-') + return if (sanitized.isNotEmpty()) sanitized else Build.MODEL.replace(Regex("[^a-zA-Z0-9-]"), "") +} + +@Composable +fun EditHostnameDialog( + currentHostname: String, + onConfirm: (String) -> Unit, + onDismiss: () -> Unit +) { + val context = LocalContext.current + var text by remember { mutableStateOf(if (currentHostname != "--") currentHostname else "") } + + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( + text = stringResource(R.string.edit_hostname_dialog_title), + style = MaterialTheme.typography.titleLarge + ) + }, + text = { + Column(modifier = Modifier.fillMaxWidth()) { + Text( + text = stringResource(R.string.edit_hostname_dialog_hint), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Spacer(modifier = Modifier.height(16.dp)) + + OutlinedTextField( + value = text, + onValueChange = { input -> + // Filter to valid DNS hostname characters (alphanumeric and hyphen) + text = input.filter { it.isLetterOrDigit() || it == '-' } + }, + label = { Text(text = stringResource(R.string.edit_hostname_input_label)) }, + singleLine = true, + modifier = Modifier.fillMaxWidth() + ) + + Spacer(modifier = Modifier.height(8.dp)) + + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.End, + verticalAlignment = Alignment.CenterVertically + ) { + TextButton( + onClick = { + text = getDefaultDeviceHostname(context) + } + ) { + Icon( + imageVector = Icons.Default.RestartAlt, + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + Spacer(modifier = Modifier.width(4.dp)) + Text( + text = stringResource(R.string.btn_restore_default_device_name), + style = MaterialTheme.typography.labelLarge + ) + } + } + } + }, + confirmButton = { + Button( + onClick = { + val sanitized = text.trim() + if (sanitized.isNotEmpty()) { + onConfirm(sanitized) + } + }, + enabled = text.trim().isNotEmpty() + ) { + Text(text = stringResource(R.string.btn_save)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(text = stringResource(R.string.btn_cancel)) + } + } + ) +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ExitNodeBottomSheet.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ExitNodeBottomSheet.kt new file mode 100644 index 0000000..9cb20ea --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ExitNodeBottomSheet.kt @@ -0,0 +1,283 @@ +package com.lzxnone.tailscalemanager.ui.components + +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.navigationBarsPadding +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.Refresh +import androidx.compose.material.icons.outlined.Dns +import androidx.compose.material.icons.outlined.Public +import androidx.compose.material.icons.outlined.Router +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.material3.rememberModalBottomSheetState +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.model.ExitNodeState + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun ExitNodeBottomSheet( + exitNodeState: ExitNodeState, + isRefreshing: Boolean = false, + onRefresh: () -> Unit = {}, + onSelectNode: (String) -> Unit, // pass empty string for None + onToggleAllowLan: (Boolean) -> Unit, + onToggleAdvertiseExitNode: (Boolean) -> Unit, + onDismiss: () -> Unit +) { + val sheetState = rememberModalBottomSheetState() + val isNoneSelected = exitNodeState.currentExitNodeId.isEmpty() + + // 每次打开时自动触发一次刷新,检索最新可用的出口节点设备 + LaunchedEffect(Unit) { + onRefresh() + } + + ModalBottomSheet( + onDismissRequest = onDismiss, + sheetState = sheetState + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp) + .navigationBarsPadding() + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 12.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = stringResource(R.string.exit_node_sheet_title), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) + + if (isRefreshing) { + CircularProgressIndicator( + modifier = Modifier.size(18.dp), + strokeWidth = 2.dp, + color = MaterialTheme.colorScheme.primary + ) + } else { + IconButton( + onClick = onRefresh, + modifier = Modifier.size(28.dp) + ) { + Icon( + imageVector = Icons.Default.Refresh, + contentDescription = stringResource(R.string.top_bar_refresh), + tint = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.size(18.dp) + ) + } + } + } + + // Option 1: None (Direct connection) + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .clickable { onSelectNode("") } + .padding(vertical = 12.dp, horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.Public, + contentDescription = null, + tint = if (isNoneSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.width(16.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = stringResource(R.string.exit_node_none_option), + style = MaterialTheme.typography.bodyLarge, + fontWeight = if (isNoneSelected) FontWeight.Bold else FontWeight.Normal, + color = MaterialTheme.colorScheme.onSurface + ) + } + if (isNoneSelected) { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + } + } + + // Available Exit Node Peers + if (exitNodeState.availablePeers.isEmpty()) { + Text( + text = stringResource(R.string.exit_node_no_available), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f), + modifier = Modifier.padding(start = 40.dp, top = 4.dp, bottom = 12.dp) + ) + } else { + exitNodeState.availablePeers.forEach { peer -> + val isSelected = exitNodeState.currentExitNodeId == peer.id + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .clickable { onSelectNode(peer.id) } + .padding(vertical = 12.dp, horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Outlined.Dns, + contentDescription = null, + tint = if (isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.width(16.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = peer.hostname, + style = MaterialTheme.typography.bodyLarge, + fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Normal, + color = MaterialTheme.colorScheme.onSurface + ) + Text( + text = peer.ip, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + if (isSelected) { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + } + } + } + } + + HorizontalDivider(modifier = Modifier.padding(vertical = 10.dp)) + + // Setting 1: Allow local network access + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 8.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Outlined.Router, + contentDescription = null, + modifier = Modifier.size(24.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.width(16.dp)) + Column { + Text( + text = stringResource(R.string.exit_node_allow_lan), + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = stringResource(R.string.exit_node_allow_lan_desc), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Spacer(modifier = Modifier.width(12.dp)) + + Switch( + checked = exitNodeState.allowLanAccess, + onCheckedChange = { onToggleAllowLan(it) }, + colors = SwitchDefaults.colors( + checkedThumbColor = MaterialTheme.colorScheme.primary, + checkedTrackColor = MaterialTheme.colorScheme.primaryContainer + ) + ) + } + + HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp)) + + // Setting 2: Run as exit node + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 8.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Outlined.Public, + contentDescription = null, + modifier = Modifier.size(24.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.width(16.dp)) + Column { + Text( + text = stringResource(R.string.exit_node_run_as_exit), + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = stringResource(R.string.exit_node_run_as_exit_desc), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Spacer(modifier = Modifier.width(12.dp)) + + Switch( + checked = exitNodeState.isAdvertisingExitNode, + onCheckedChange = { onToggleAdvertiseExitNode(it) }, + colors = SwitchDefaults.colors( + checkedThumbColor = MaterialTheme.colorScheme.primary, + checkedTrackColor = MaterialTheme.colorScheme.primaryContainer + ) + ) + } + + Spacer(modifier = Modifier.height(20.dp)) + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ExitNodeCard.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ExitNodeCard.kt new file mode 100644 index 0000000..2359ced --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ExitNodeCard.kt @@ -0,0 +1,106 @@ +package com.lzxnone.tailscalemanager.ui.components + +import androidx.compose.animation.animateColorAsState +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.model.ExitNodeState + +@Composable +fun ExitNodeCard( + exitNodeState: ExitNodeState, + isServiceRunning: Boolean, + onCardClick: () -> Unit, + modifier: Modifier = Modifier +) { + val isUsingExitNode = exitNodeState.currentExitNodeId.isNotEmpty() + + val statusDotColor by animateColorAsState( + targetValue = if (isServiceRunning && isUsingExitNode) Color(0xFF4CAF50) else Color(0xFF9E9E9E), + label = "exitNodeDotColor" + ) + + Card( + modifier = modifier + .fillMaxWidth() + .clickable(enabled = isServiceRunning) { onCardClick() }, + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLowest + ), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f)), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = stringResource(R.string.exit_node_card_title), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(6.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = Modifier + .size(10.dp) + .clip(CircleShape) + .background(statusDotColor) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = if (isUsingExitNode && exitNodeState.currentExitNodeName.isNotEmpty()) { + stringResource(R.string.exit_node_status_using, exitNodeState.currentExitNodeName) + } else { + stringResource(R.string.exit_node_status_disabled) + }, + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Medium, + color = if (isUsingExitNode) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f) + ) + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/LoginDialog.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/LoginDialog.kt new file mode 100644 index 0000000..cd44b71 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/LoginDialog.kt @@ -0,0 +1,140 @@ +package com.lzxnone.tailscalemanager.ui.components + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.content.Intent +import android.net.Uri +import android.widget.Toast +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import com.lzxnone.tailscalemanager.R + +@Composable +fun LoginDialog( + loginUrl: String?, + isLoading: Boolean, + onDismiss: () -> Unit +) { + val context = LocalContext.current + val copiedText = stringResource(R.string.login_link_copied) + + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( + text = stringResource(R.string.login_dialog_title), + style = MaterialTheme.typography.titleLarge + ) + }, + text = { + Column(modifier = Modifier.fillMaxWidth()) { + Text( + text = stringResource(R.string.login_dialog_message), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Spacer(modifier = Modifier.height(16.dp)) + + if (isLoading || loginUrl.isNullOrEmpty()) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + CircularProgressIndicator( + modifier = Modifier.size(24.dp), + strokeWidth = 2.5.dp + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = stringResource(R.string.login_generating_url), + style = MaterialTheme.typography.bodyMedium + ) + } + } else { + Box( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .background(MaterialTheme.colorScheme.surfaceVariant) + .padding(12.dp) + ) { + Text( + text = loginUrl, + style = MaterialTheme.typography.bodySmall.copy( + fontFamily = FontFamily.Monospace, + fontSize = 11.sp + ), + maxLines = 2, + overflow = TextOverflow.Ellipsis, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + Spacer(modifier = Modifier.height(16.dp)) + + Row(modifier = Modifier.fillMaxWidth()) { + OutlinedButton( + onClick = { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + val clip = ClipData.newPlainText("Tailscale Login URL", loginUrl) + clipboard.setPrimaryClip(clip) + Toast.makeText(context, copiedText, Toast.LENGTH_SHORT).show() + }, + modifier = Modifier.weight(1f) + ) { + Text(text = stringResource(R.string.btn_copy_link)) + } + + Spacer(modifier = Modifier.width(10.dp)) + + Button( + onClick = { + val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(loginUrl)) + context.startActivity(browserIntent) + }, + modifier = Modifier.weight(1f) + ) { + Text(text = stringResource(R.string.btn_open_browser)) + } + } + } + } + }, + confirmButton = {}, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(text = stringResource(R.string.btn_cancel)) + } + } + ) +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/LogoutConfirmDialog.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/LogoutConfirmDialog.kt new file mode 100644 index 0000000..041a5c5 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/LogoutConfirmDialog.kt @@ -0,0 +1,49 @@ +package com.lzxnone.tailscalemanager.ui.components + +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import com.lzxnone.tailscalemanager.R + +@Composable +fun LogoutConfirmDialog( + onConfirm: () -> Unit, + onDismiss: () -> Unit +) { + AlertDialog( + onDismissRequest = onDismiss, + title = { + Text( + text = stringResource(R.string.account_logout_confirm_title), + style = MaterialTheme.typography.titleLarge + ) + }, + text = { + Text( + text = stringResource(R.string.account_logout_confirm_message), + style = MaterialTheme.typography.bodyMedium + ) + }, + confirmButton = { + Button( + onClick = onConfirm, + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.error, + contentColor = MaterialTheme.colorScheme.onError + ) + ) { + Text(text = stringResource(R.string.account_btn_logout)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(text = stringResource(R.string.btn_cancel)) + } + } + ) +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ModuleCard.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ModuleCard.kt new file mode 100644 index 0000000..21a0d35 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ModuleCard.kt @@ -0,0 +1,164 @@ +package com.lzxnone.tailscalemanager.ui.components + +import androidx.compose.animation.animateColorAsState +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.outlined.Delete +import androidx.compose.material.icons.outlined.Sync +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.core.module.ModuleState + +@Composable +fun ModuleCard( + moduleState: ModuleState, + moduleVersion: String, + onToggleModule: () -> Unit, + onInstallClick: () -> Unit, + onDeleteClick: () -> Unit, + onCheckUpdateClick: () -> Unit, + modifier: Modifier = Modifier +) { + val statusColor by animateColorAsState( + targetValue = when (moduleState) { + ModuleState.ENABLED -> Color(0xFF4CAF50) + ModuleState.DISABLED -> Color(0xFF9E9E9E) + ModuleState.NOT_INSTALLED -> MaterialTheme.colorScheme.error + }, + label = "moduleStatusColor" + ) + + Card( + modifier = modifier.fillMaxWidth(), + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLowest + ), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f)), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = stringResource(R.string.module_card_title), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(6.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = Modifier + .size(10.dp) + .clip(CircleShape) + .background(statusColor) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = when (moduleState) { + ModuleState.ENABLED -> stringResource(R.string.module_state_enabled) + ModuleState.DISABLED -> stringResource(R.string.module_state_disabled) + ModuleState.NOT_INSTALLED -> stringResource(R.string.module_state_not_installed) + }, + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold, + color = statusColor + ) + } + if (moduleVersion.isNotEmpty()) { + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = stringResource(R.string.card_version_label, moduleVersion), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + if (moduleState == ModuleState.NOT_INSTALLED) { + Button( + onClick = onInstallClick, + shape = RoundedCornerShape(12.dp), + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.primary + ) + ) { + Text(text = stringResource(R.string.module_btn_install)) + } + } else { + Row(verticalAlignment = Alignment.CenterVertically) { + IconButton( + onClick = onCheckUpdateClick, + modifier = Modifier.size(38.dp) + ) { + Icon( + imageVector = Icons.Outlined.Sync, + contentDescription = stringResource(R.string.module_btn_check_update), + tint = MaterialTheme.colorScheme.primary + ) + } + IconButton( + onClick = onDeleteClick, + modifier = Modifier.size(38.dp) + ) { + Icon( + imageVector = Icons.Outlined.Delete, + contentDescription = stringResource(R.string.module_btn_delete), + tint = MaterialTheme.colorScheme.error.copy(alpha = 0.85f) + ) + } + Spacer(modifier = Modifier.width(4.dp)) + Switch( + checked = moduleState == ModuleState.ENABLED, + onCheckedChange = { onToggleModule() }, + colors = SwitchDefaults.colors( + checkedThumbColor = MaterialTheme.colorScheme.primary, + checkedTrackColor = MaterialTheme.colorScheme.primaryContainer + ) + ) + } + } + } + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ModuleSyncDialog.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ModuleSyncDialog.kt new file mode 100644 index 0000000..b5868cb --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ModuleSyncDialog.kt @@ -0,0 +1,164 @@ +package com.lzxnone.tailscalemanager.ui.components + +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.LinearProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.DialogProperties +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.core.module.ModuleSyncState +import com.lzxnone.tailscalemanager.core.module.SyncStep + +@Composable +fun ModuleSyncDialog( + syncState: ModuleSyncState, + onStartSync: () -> Unit, + onDismiss: () -> Unit, + onRetry: () -> Unit, + onDontShowAgain: ((Long) -> Unit)? = null +) { + if (syncState == ModuleSyncState.Idle || syncState == ModuleSyncState.Checking) { + return + } + + val isSyncing = syncState is ModuleSyncState.Syncing + + AlertDialog( + onDismissRequest = { + if (!isSyncing) onDismiss() + }, + properties = DialogProperties( + dismissOnBackPress = !isSyncing, + dismissOnClickOutside = !isSyncing + ), + title = { + Text( + text = when (syncState) { + is ModuleSyncState.NeedsInstall -> stringResource(R.string.sync_dialog_title_install) + is ModuleSyncState.NeedsUpdate -> { + val displayVersion = if (syncState.bundledVersion.startsWith("v", ignoreCase = true)) { + "V" + syncState.bundledVersion.substring(1) + } else { + "V${syncState.bundledVersion}" + } + stringResource(R.string.update_dialog_title_format, displayVersion) + } + is ModuleSyncState.Syncing -> stringResource(R.string.module_card_title) + is ModuleSyncState.Success -> stringResource(R.string.sync_step_completed) + is ModuleSyncState.Error -> stringResource(R.string.sync_step_failed, "") + else -> "" + }, + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold + ) + }, + text = { + Column(modifier = Modifier.fillMaxWidth()) { + when (syncState) { + is ModuleSyncState.NeedsInstall -> { + Text( + text = stringResource(R.string.sync_dialog_message_install), + style = MaterialTheme.typography.bodyMedium + ) + } + + is ModuleSyncState.NeedsUpdate -> { + Text( + text = stringResource(R.string.module_update_changelog), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurface + ) + } + + is ModuleSyncState.Syncing -> { + val stepText = when (syncState.step) { + SyncStep.PREPARING -> stringResource(R.string.sync_step_preparing) + SyncStep.EXTRACTING -> stringResource(R.string.sync_step_extracting) + SyncStep.INSTALLING -> stringResource(R.string.sync_step_installing) + SyncStep.CONFIGURING_PERMISSIONS -> stringResource(R.string.sync_step_setting_permissions) + SyncStep.COMPLETED -> stringResource(R.string.sync_step_completed) + } + Text(text = stepText, style = MaterialTheme.typography.bodyMedium) + Spacer(modifier = Modifier.height(16.dp)) + LinearProgressIndicator( + progress = { syncState.progress }, + modifier = Modifier.fillMaxWidth(), + ) + } + + is ModuleSyncState.Success -> { + Text( + text = stringResource(R.string.sync_step_completed), + style = MaterialTheme.typography.bodyMedium + ) + } + + is ModuleSyncState.Error -> { + Text( + text = stringResource(R.string.sync_step_failed, syncState.errorMessage), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.error + ) + } + + else -> {} + } + } + }, + confirmButton = { + when (syncState) { + is ModuleSyncState.NeedsInstall -> { + Button(onClick = onStartSync) { + Text(text = stringResource(R.string.btn_start_sync)) + } + } + + is ModuleSyncState.NeedsUpdate -> { + Button(onClick = onStartSync) { + Text(text = stringResource(R.string.btn_update_now)) + } + } + + is ModuleSyncState.Success -> { + Button(onClick = onDismiss) { + Text(text = stringResource(R.string.btn_done)) + } + } + + is ModuleSyncState.Error -> { + Button(onClick = onRetry) { + Text(text = stringResource(R.string.btn_retry)) + } + } + + else -> {} + } + }, + dismissButton = { + if (!isSyncing && syncState !is ModuleSyncState.Success) { + Row { + if (syncState is ModuleSyncState.NeedsUpdate && onDontShowAgain != null) { + TextButton(onClick = { onDontShowAgain(syncState.bundledVersionCode) }) { + Text(text = stringResource(R.string.btn_dont_show_again)) + } + } + TextButton(onClick = onDismiss) { + Text(text = stringResource(R.string.btn_cancel)) + } + } + } + } + ) +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/RootMissingDialog.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/RootMissingDialog.kt new file mode 100644 index 0000000..184d379 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/RootMissingDialog.kt @@ -0,0 +1,47 @@ +package com.lzxnone.tailscalemanager.ui.components + +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.window.DialogProperties +import com.lzxnone.tailscalemanager.R + +@Composable +fun RootMissingDialog( + onConfirmExit: () -> Unit +) { + AlertDialog( + onDismissRequest = {}, + properties = DialogProperties( + dismissOnBackPress = false, + dismissOnClickOutside = false + ), + title = { + Text( + text = stringResource(R.string.root_required_title), + style = MaterialTheme.typography.titleLarge + ) + }, + text = { + Text( + text = stringResource(R.string.root_required_message), + style = MaterialTheme.typography.bodyMedium + ) + }, + confirmButton = { + Button( + onClick = onConfirmExit, + colors = ButtonDefaults.buttonColors( + containerColor = MaterialTheme.colorScheme.error, + contentColor = MaterialTheme.colorScheme.onError + ) + ) { + Text(text = stringResource(R.string.btn_exit)) + } + } + ) +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ServiceCard.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ServiceCard.kt new file mode 100644 index 0000000..3a5d9e8 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/components/ServiceCard.kt @@ -0,0 +1,129 @@ +package com.lzxnone.tailscalemanager.ui.components + +import androidx.compose.animation.animateColorAsState +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.core.service.ServiceState + +@Composable +fun ServiceCard( + isModuleEnabled: Boolean, + serviceState: ServiceState, + serviceVersion: String, + modifier: Modifier = Modifier +) { + val isRunning = isModuleEnabled && serviceState == ServiceState.RUNNING + val isTransitioning = isModuleEnabled && (serviceState == ServiceState.STARTING || serviceState == ServiceState.STOPPING) + + val statusDotColor by animateColorAsState( + targetValue = when { + !isModuleEnabled -> Color(0xFF9E9E9E) + serviceState == ServiceState.RUNNING -> Color(0xFF4CAF50) + serviceState == ServiceState.STARTING || serviceState == ServiceState.STOPPING -> Color(0xFFFF9800) + else -> Color(0xFF9E9E9E) + }, + label = "serviceStatusDotColor" + ) + + Card( + modifier = modifier + .fillMaxWidth() + .alpha(if (isModuleEnabled) 1.0f else 0.6f), + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLowest + ), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f)), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp) + ) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + Text( + text = stringResource(R.string.service_card_title), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(6.dp)) + Row(verticalAlignment = Alignment.CenterVertically) { + if (isTransitioning) { + CircularProgressIndicator( + modifier = Modifier.size(12.dp), + strokeWidth = 2.dp, + color = statusDotColor + ) + } else { + Box( + modifier = Modifier + .size(10.dp) + .clip(CircleShape) + .background(statusDotColor) + ) + } + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = when { + !isModuleEnabled -> stringResource(R.string.service_status_disabled) + serviceState == ServiceState.RUNNING -> stringResource(R.string.service_status_running) + serviceState == ServiceState.STOPPED -> stringResource(R.string.service_status_stopped) + serviceState == ServiceState.STARTING -> stringResource(R.string.service_status_starting) + serviceState == ServiceState.STOPPING -> stringResource(R.string.service_status_stopping) + else -> stringResource(R.string.service_status_unknown) + }, + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.SemiBold, + color = statusDotColor + ) + } + if (serviceVersion.isNotEmpty()) { + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = stringResource(R.string.card_version_label, serviceVersion), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/AboutScreen.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/AboutScreen.kt new file mode 100644 index 0000000..493aa6a --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/AboutScreen.kt @@ -0,0 +1,166 @@ +package com.lzxnone.tailscalemanager.ui.screens + +import androidx.compose.foundation.Image +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Info +import androidx.compose.material.icons.filled.Sync +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.res.painterResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.tailscalemanager.BuildConfig +import com.lzxnone.tailscalemanager.R + +@Composable +fun AboutScreen( + onCheckAppUpdate: () -> Unit = {}, + isCheckingUpdate: Boolean = false, + modifier: Modifier = Modifier +) { + + Column( + modifier = modifier + .fillMaxSize() + .padding(horizontal = 24.dp), + horizontalAlignment = Alignment.CenterHorizontally + ) { + Spacer(modifier = Modifier.height(48.dp)) + + // 软件图标 + Box( + modifier = Modifier + .size(100.dp) + .clip(RoundedCornerShape(22.dp)) + .background(MaterialTheme.colorScheme.surfaceVariant), + contentAlignment = Alignment.Center + ) { + Image( + painter = painterResource(id = R.drawable.ic_launcher_foreground), + contentDescription = stringResource(R.string.app_name), + modifier = Modifier.fillMaxSize() + ) + } + + Spacer(modifier = Modifier.height(18.dp)) + + // 软件名称 + Text( + text = stringResource(R.string.app_name), + style = MaterialTheme.typography.headlineSmall, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) + + Spacer(modifier = Modifier.height(6.dp)) + + // 作者 + Text( + text = stringResource(R.string.about_author, "lzxnone"), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + + Spacer(modifier = Modifier.height(36.dp)) + + // 版本与检查更新卡片 + Card( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(16.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainer + ) + ) { + Column(modifier = Modifier.padding(vertical = 4.dp)) { + // 版本 + Row( + modifier = Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Default.Info, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(24.dp) + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = stringResource(R.string.about_app_version), + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.Medium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f) + ) + Text( + text = "v${BuildConfig.VERSION_NAME}", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + HorizontalDivider( + modifier = Modifier.padding(horizontal = 16.dp), + color = MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.5f) + ) + + // 检查更新 + Row( + modifier = Modifier + .fillMaxWidth() + .clickable(enabled = !isCheckingUpdate) { + onCheckAppUpdate() + } + .padding(horizontal = 16.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Default.Sync, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary, + modifier = Modifier.size(24.dp) + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = stringResource(R.string.about_check_updates), + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.Medium, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.weight(1f) + ) + if (isCheckingUpdate) { + Text( + text = stringResource(R.string.checking_updates), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.primary + ) + } + } + } + } + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/AccountScreen.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/AccountScreen.kt new file mode 100644 index 0000000..64d6495 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/AccountScreen.kt @@ -0,0 +1,316 @@ +package com.lzxnone.tailscalemanager.ui.screens + +import android.content.Intent +import android.net.Uri +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ExitToApp +import androidx.compose.material.icons.filled.Add +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.OpenInBrowser +import androidx.compose.material.icons.filled.Person +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.model.AccountProfile + +@Composable +fun AccountScreen( + currentAccount: AccountProfile?, + accounts: List, + isModuleEnabled: Boolean, + onSelectAccount: (AccountProfile) -> Unit, + onAddAccountClick: () -> Unit, + onLogoutClick: () -> Unit, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + val isLoggedIn = currentAccount != null && currentAccount.account.isNotEmpty() + + val initialLetter = if (isLoggedIn) { + val name = currentAccount.nickname.ifEmpty { currentAccount.account } + name.take(1).uppercase() + } else { + "?" + } + + Column( + modifier = modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + // 1. Current Active Account Profile Card + Card( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLowest + ), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f)), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp) + ) { + Row(verticalAlignment = Alignment.CenterVertically) { + // Avatar circle (matches desktop Tailscale) + Box( + modifier = Modifier + .size(52.dp) + .clip(CircleShape) + .background( + if (isLoggedIn) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant + ), + contentAlignment = Alignment.Center + ) { + Text( + text = initialLetter, + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold, + color = if (isLoggedIn) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + Spacer(modifier = Modifier.width(16.dp)) + + Column(modifier = Modifier.weight(1f)) { + Text( + text = if (isLoggedIn) currentAccount.account else stringResource(R.string.account_not_logged_in), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = if (isLoggedIn) { + currentAccount.nickname.ifEmpty { currentAccount.tailnet } + } else { + stringResource(R.string.account_tap_to_login) + }, + style = MaterialTheme.typography.bodyMedium, + maxLines = 1, + overflow = TextOverflow.Ellipsis, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + if (!isLoggedIn) { + Spacer(modifier = Modifier.height(16.dp)) + Button( + onClick = onAddAccountClick, + enabled = isModuleEnabled, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.fillMaxWidth() + ) { + Text(text = stringResource(R.string.account_tap_to_login)) + } + } + } + } + + // 2. Multi-Account Switcher List (shown when accounts exist) + if (accounts.isNotEmpty()) { + Card( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLowest + ), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f)), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp) + ) { + Text( + text = stringResource(R.string.account_switch_sheet_title), + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface, + modifier = Modifier.padding(bottom = 8.dp) + ) + + accounts.forEachIndexed { index, profile -> + if (index > 0) { + HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp)) + } + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .clickable { onSelectAccount(profile) } + .padding(vertical = 12.dp, horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Default.Person, + contentDescription = null, + tint = if (profile.isSelected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.width(14.dp)) + Column(modifier = Modifier.weight(1f)) { + Text( + text = profile.account, + style = MaterialTheme.typography.bodyLarge, + fontWeight = if (profile.isSelected) FontWeight.Bold else FontWeight.Normal, + color = MaterialTheme.colorScheme.onSurface + ) + if (profile.nickname.isNotEmpty()) { + Text( + text = profile.nickname, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + if (profile.isSelected) { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + } + } + } + } + } + } + + // 3. Actions Card (Add Account / Admin Console / Log Out) + Card( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLowest + ), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f)), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(20.dp) + ) { + // Action A: Add another account... + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .clickable(enabled = isModuleEnabled) { onAddAccountClick() } + .padding(vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Default.Add, + contentDescription = null, + modifier = Modifier.size(24.dp), + tint = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = stringResource(R.string.account_btn_add), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.primary + ) + } + + HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp)) + + // Action B: Admin console... + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .clickable { + val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse("https://login.tailscale.com/admin")) + context.startActivity(browserIntent) + } + .padding(vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Default.OpenInBrowser, + contentDescription = null, + modifier = Modifier.size(24.dp), + tint = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = stringResource(R.string.account_btn_admin), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurface + ) + } + + if (isLoggedIn) { + HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp)) + + // Action C: Log out + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .clickable { onLogoutClick() } + .padding(vertical = 12.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ExitToApp, + contentDescription = null, + modifier = Modifier.size(24.dp), + tint = MaterialTheme.colorScheme.error + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = stringResource(R.string.account_btn_logout), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.error + ) + } + } + } + } + + Spacer(modifier = Modifier.height(32.dp)) + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/DashboardScreen.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/DashboardScreen.kt new file mode 100644 index 0000000..fd788cf --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/DashboardScreen.kt @@ -0,0 +1,118 @@ +package com.lzxnone.tailscalemanager.ui.screens + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.core.module.ModuleState +import com.lzxnone.tailscalemanager.core.service.ServiceState +import com.lzxnone.tailscalemanager.model.DeviceStatus +import com.lzxnone.tailscalemanager.model.ExitNodeState +import com.lzxnone.tailscalemanager.ui.components.DeviceCard +import com.lzxnone.tailscalemanager.ui.components.ExitNodeCard +import com.lzxnone.tailscalemanager.ui.components.ModuleCard +import com.lzxnone.tailscalemanager.ui.components.ServiceCard + +@Composable +fun DashboardScreen( + moduleState: ModuleState, + moduleVersion: String, + serviceVersion: String, + isLoggedIn: Boolean, + deviceStatus: DeviceStatus, + serviceState: ServiceState, + exitNodeState: ExitNodeState, + onToggleModule: () -> Unit, + onInstallModule: () -> Unit, + onDeleteModule: () -> Unit, + onCheckModuleUpdate: () -> Unit, + onEditDeviceName: () -> Unit, + onExitNodeClick: () -> Unit, + onRefresh: () -> Unit = {}, + modifier: Modifier = Modifier +) { + LaunchedEffect(Unit) { + onRefresh() + } + + Column( + modifier = modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + // ========================================== + // 分块 1: 模块与服务 (Module & Service) + // ========================================== + SectionTitle(text = stringResource(R.string.section_module_and_service)) + + // 1.1 KernelSU 模块卡片 + ModuleCard( + moduleState = moduleState, + moduleVersion = moduleVersion, + onToggleModule = onToggleModule, + onInstallClick = onInstallModule, + onDeleteClick = onDeleteModule, + onCheckUpdateClick = onCheckModuleUpdate + ) + + // 1.2 Tailscale 服务卡片 + ServiceCard( + isModuleEnabled = moduleState == ModuleState.ENABLED, + serviceState = serviceState, + serviceVersion = serviceVersion + ) + + // ========================================== + // 分块 2: 设备信息 (Device) + // ========================================== + SectionTitle(text = stringResource(R.string.section_device)) + + // 2.1 设备网络信息卡片 (主机名 + IP + 编辑按钮) + DeviceCard( + deviceStatus = deviceStatus, + isLoggedIn = isLoggedIn, + isServiceRunning = moduleState == ModuleState.ENABLED && serviceState == ServiceState.RUNNING, + onEditClick = onEditDeviceName + ) + + // ========================================== + // 分块 3: 出口节点 (Exit Node) + // ========================================== + SectionTitle(text = stringResource(R.string.section_exit_node)) + + // 3.1 出口节点卡片 + ExitNodeCard( + exitNodeState = exitNodeState, + isServiceRunning = moduleState == ModuleState.ENABLED && serviceState == ServiceState.RUNNING, + onCardClick = onExitNodeClick + ) + + Spacer(modifier = Modifier.height(32.dp)) + } +} + +@Composable +private fun SectionTitle(text: String) { + Text( + text = text, + style = MaterialTheme.typography.labelLarge, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(start = 4.dp, top = 4.dp) + ) +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/DevicesScreen.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/DevicesScreen.kt new file mode 100644 index 0000000..8cb2ba7 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/DevicesScreen.kt @@ -0,0 +1,437 @@ +package com.lzxnone.tailscalemanager.ui.screens + +import android.content.ClipData +import android.content.ClipboardManager +import android.content.Context +import android.widget.Toast +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.animation.animateColorAsState +import androidx.compose.animation.animateContentSize +import androidx.compose.animation.expandVertically +import androidx.compose.animation.fadeIn +import androidx.compose.animation.fadeOut +import androidx.compose.animation.shrinkVertically +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.foundation.lazy.items +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowForward +import androidx.compose.material.icons.filled.ContentCopy +import androidx.compose.material.icons.filled.KeyboardArrowDown +import androidx.compose.material.icons.filled.KeyboardArrowUp +import androidx.compose.material.icons.filled.NetworkCheck +import androidx.compose.material.icons.outlined.Devices +import androidx.compose.material3.Button +import androidx.compose.material3.ButtonDefaults +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.SuggestionChip +import androidx.compose.material3.SuggestionChipDefaults +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.model.PingResult +import com.lzxnone.tailscalemanager.model.TailscaleDevice + +@Composable +fun DevicesScreen( + devices: List, + pingResults: Map, + pingingDevices: Set, + onPingDevice: (TailscaleDevice) -> Unit, + onRefresh: () -> Unit = {}, + modifier: Modifier = Modifier +) { + LaunchedEffect(Unit) { + onRefresh() + } + + val context = LocalContext.current + var expandedDeviceId by remember { mutableStateOf(null) } + + if (devices.isEmpty()) { + Box( + modifier = modifier + .fillMaxSize() + .padding(32.dp), + contentAlignment = Alignment.Center + ) { + Column(horizontalAlignment = Alignment.CenterHorizontally) { + Icon( + imageVector = Icons.Outlined.Devices, + contentDescription = null, + modifier = Modifier.size(56.dp), + tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f) + ) + Spacer(modifier = Modifier.height(16.dp)) + Text( + text = stringResource(R.string.devices_empty), + style = MaterialTheme.typography.bodyLarge, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } else { + LazyColumn( + modifier = modifier + .fillMaxSize() + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(12.dp) + ) { + items(devices, key = { it.id }) { device -> + val isExpanded = expandedDeviceId == device.id + val deviceKey = device.ip.ifEmpty { device.name } + val pingResult = pingResults[deviceKey] + val isPinging = pingingDevices.contains(deviceKey) + + DeviceItemCard( + device = device, + isExpanded = isExpanded, + pingResult = pingResult, + isPinging = isPinging, + onToggleExpand = { + expandedDeviceId = if (isExpanded) null else device.id + }, + onPing = { onPingDevice(device) }, + onCopyIp = { + val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager + clipboard.setPrimaryClip(ClipData.newPlainText("IP", device.ip)) + Toast.makeText(context, context.getString(R.string.device_card_ip_copied), Toast.LENGTH_SHORT).show() + } + ) + } + + item { + Spacer(modifier = Modifier.height(24.dp)) + } + } + } +} + +@Composable +private fun DeviceItemCard( + device: TailscaleDevice, + isExpanded: Boolean, + pingResult: PingResult?, + isPinging: Boolean, + onToggleExpand: () -> Unit, + onPing: () -> Unit, + onCopyIp: () -> Unit, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + val onlineDotColor by animateColorAsState( + targetValue = if (device.isOnline) Color(0xFF4CAF50) else Color(0xFF9E9E9E), + label = "deviceOnlineColor" + ) + + Card( + modifier = modifier + .fillMaxWidth() + .animateContentSize() + .clickable { onToggleExpand() }, + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLowest + ), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f)), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + ) { + // Header Row: 两行文字 (第一行设备名称,第二行 IP) + 展开按钮 + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Column(modifier = Modifier.weight(1f)) { + // 第一行:设备名称 + 在线圆点 + OS徽标 + 出口节点徽标 + Row(verticalAlignment = Alignment.CenterVertically) { + Box( + modifier = Modifier + .size(8.dp) + .clip(CircleShape) + .background(onlineDotColor) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text( + text = device.name, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurface + ) + if (device.os.isNotEmpty() && device.os != "unknown") { + Spacer(modifier = Modifier.width(8.dp)) + Surface( + shape = RoundedCornerShape(6.dp), + color = MaterialTheme.colorScheme.secondaryContainer + ) { + Text( + text = formatOsName(device.os), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onSecondaryContainer, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp), + fontWeight = FontWeight.SemiBold + ) + } + } + if (device.isExitNode) { + Spacer(modifier = Modifier.width(6.dp)) + Surface( + shape = RoundedCornerShape(6.dp), + color = MaterialTheme.colorScheme.tertiaryContainer + ) { + Text( + text = stringResource(R.string.device_tag_exit_node), + style = MaterialTheme.typography.labelSmall, + color = MaterialTheme.colorScheme.onTertiaryContainer, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp), + fontWeight = FontWeight.SemiBold + ) + } + } + } + + Spacer(modifier = Modifier.height(4.dp)) + + // 第二行:IP 地址 + 版本号 (如果有) + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + text = device.ip, + style = MaterialTheme.typography.bodyMedium, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + if (device.version.isNotEmpty()) { + Text( + text = " · ${device.version}", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.8f) + ) + } + } + + // 第三行:仅在离线时显示最后在线时间 (在线时不显示) + if (!device.isOnline && device.lastSeen.isNotEmpty()) { + Spacer(modifier = Modifier.height(4.dp)) + val formattedLastSeen = formatLastSeen(device.lastSeen, context) + Text( + text = stringResource(R.string.device_last_seen_label, formattedLastSeen), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f) + ) + } + } + + Icon( + imageVector = if (isExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + + // 点击卡片展开后显示的下拉菜单与探测区域 + AnimatedVisibility( + visible = isExpanded, + enter = expandVertically() + fadeIn(), + exit = shrinkVertically() + fadeOut() + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(top = 12.dp) + ) { + HorizontalDivider(modifier = Modifier.padding(vertical = 8.dp)) + + // 操作栏:Ping 按钮 + 复制 IP 按钮 + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Button( + onClick = onPing, + enabled = !isPinging, + shape = RoundedCornerShape(12.dp), + modifier = Modifier.weight(1f) + ) { + if (isPinging) { + CircularProgressIndicator( + modifier = Modifier.size(16.dp), + strokeWidth = 2.dp, + color = MaterialTheme.colorScheme.onPrimary + ) + Spacer(modifier = Modifier.width(8.dp)) + Text(text = stringResource(R.string.device_ping_running), style = MaterialTheme.typography.bodySmall) + } else { + Icon( + imageVector = Icons.Default.NetworkCheck, + contentDescription = null, + modifier = Modifier.size(18.dp) + ) + Spacer(modifier = Modifier.width(8.dp)) + Text(text = stringResource(R.string.device_ping_btn)) + } + } + + OutlinedButton( + onClick = onCopyIp, + shape = RoundedCornerShape(12.dp) + ) { + Icon( + imageVector = Icons.Default.ContentCopy, + contentDescription = null, + modifier = Modifier.size(16.dp) + ) + Spacer(modifier = Modifier.width(6.dp)) + Text(text = stringResource(R.string.device_btn_copy_ip), style = MaterialTheme.typography.bodySmall) + } + } + + // Ping 结果展示区 (直连/中继、延迟等信息) + if (pingResult != null) { + Spacer(modifier = Modifier.height(10.dp)) + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(12.dp), + color = MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f) + ) { + Column(modifier = Modifier.padding(12.dp)) { + if (pingResult.isSuccess) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + // 模式徽标:直连 vs 中继 + Surface( + shape = RoundedCornerShape(6.dp), + color = if (pingResult.isDirect) Color(0xFFE8F5E9) else Color(0xFFFFF3E0) + ) { + Text( + text = if (pingResult.isDirect) { + stringResource(R.string.device_ping_direct) + } else { + stringResource(R.string.device_ping_relay) + }, + color = if (pingResult.isDirect) Color(0xFF2E7D32) else Color(0xFFE65100), + style = MaterialTheme.typography.labelMedium, + fontWeight = FontWeight.Bold, + modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp) + ) + } + + if (pingResult.latency.isNotEmpty()) { + Text( + text = stringResource(R.string.device_ping_latency_label, pingResult.latency), + style = MaterialTheme.typography.bodyMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary + ) + } + } + + if (pingResult.relayOrEndpoint.isNotEmpty()) { + Spacer(modifier = Modifier.height(6.dp)) + Text( + text = stringResource(R.string.device_ping_route_label, pingResult.relayOrEndpoint), + style = MaterialTheme.typography.bodySmall, + fontFamily = FontFamily.Monospace, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } else { + Text( + text = stringResource(R.string.device_ping_failed, pingResult.message), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.error + ) + } + } + } + } + } + } + } + } +} + +private fun formatOsName(os: String): String { + return when (os.lowercase()) { + "windows" -> "Windows" + "linux" -> "Linux" + "darwin", "macos" -> "macOS" + "ios" -> "iOS" + "android" -> "Android" + else -> os.replaceFirstChar { if (it.isLowerCase()) it.titlecase() else it.toString() } + } +} + +private fun formatLastSeen(isoString: String, context: Context): String { + if (isoString.isEmpty() || isoString.startsWith("0001-01-01")) { + return context.getString(R.string.device_last_seen_unknown) + } + return try { + val instant = java.time.Instant.parse(isoString) + val zoneId = java.time.ZoneId.systemDefault() + val localDateTime = instant.atZone(zoneId).toLocalDateTime() + val now = java.time.LocalDateTime.now() + val duration = java.time.Duration.between(localDateTime, now) + + val minutes = duration.toMinutes() + val hours = duration.toHours() + val days = duration.toDays() + + when { + minutes < 1 -> context.getString(R.string.time_just_now) + minutes < 60 -> context.getString(R.string.time_minutes_ago, minutes) + hours < 24 -> context.getString(R.string.time_hours_ago, hours) + days < 30 -> context.getString(R.string.time_days_ago, days) + else -> { + val formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm") + localDateTime.format(formatter) + } + } + } catch (_: Exception) { + isoString.take(16).replace("T", " ") + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/MainScreen.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/MainScreen.kt new file mode 100644 index 0000000..892e7f9 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/MainScreen.kt @@ -0,0 +1,324 @@ +package com.lzxnone.tailscalemanager.ui.screens + +import android.content.Intent +import android.net.Uri +import androidx.activity.compose.BackHandler +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.padding +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.lifecycle.viewmodel.compose.viewModel +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.core.module.ModuleState +import com.lzxnone.tailscalemanager.core.root.RootState +import com.lzxnone.tailscalemanager.core.service.ServiceState +import com.lzxnone.tailscalemanager.ui.components.AppBottomBar +import com.lzxnone.tailscalemanager.ui.components.AppTopBar +import com.lzxnone.tailscalemanager.ui.components.AppUpdateDialog +import com.lzxnone.tailscalemanager.ui.components.DeleteConfirmDialog +import com.lzxnone.tailscalemanager.ui.components.EditHostnameDialog +import com.lzxnone.tailscalemanager.ui.components.ExitNodeBottomSheet +import com.lzxnone.tailscalemanager.ui.components.LoginDialog +import com.lzxnone.tailscalemanager.ui.components.LogoutConfirmDialog +import com.lzxnone.tailscalemanager.ui.components.ModuleSyncDialog +import com.lzxnone.tailscalemanager.ui.components.RootMissingDialog +import com.lzxnone.tailscalemanager.ui.viewmodel.MainViewModel + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun MainScreen( + onExitApp: () -> Unit, + viewModel: MainViewModel = viewModel() +) { + val context = LocalContext.current + val rootState by viewModel.rootState.collectAsState() + val moduleState by viewModel.moduleState.collectAsState() + val installedModule by viewModel.installedModule.collectAsState() + val moduleSyncState by viewModel.moduleSyncState.collectAsState() + val serviceState by viewModel.serviceState.collectAsState() + val serviceVersion by viewModel.serviceVersion.collectAsState() + val deviceStatus by viewModel.deviceStatus.collectAsState() + val deviceList by viewModel.deviceList.collectAsState() + val pingResults by viewModel.pingResults.collectAsState() + val pingingDevices by viewModel.pingingDevices.collectAsState() + val exitNodeState by viewModel.exitNodeState.collectAsState() + val networkPrefs by viewModel.networkPrefs.collectAsState() + val currentAccount by viewModel.currentAccount.collectAsState() + val accountList by viewModel.accountList.collectAsState() + val loginUrl by viewModel.loginUrl.collectAsState() + val isGeneratingLoginUrl by viewModel.isGeneratingLoginUrl.collectAsState() + val isRefreshingExitNodes by viewModel.isRefreshingExitNodes.collectAsState() + val appUpdateInfo by viewModel.appUpdateInfo.collectAsState() + val isCheckingAppUpdate by viewModel.isCheckingAppUpdate.collectAsState() + + var currentRoute by remember { mutableStateOf("dashboard") } + var isAccountViewOpen by remember { mutableStateOf(false) } + var isAboutViewOpen by remember { mutableStateOf(false) } + var showDeleteConfirm by remember { mutableStateOf(false) } + var showLogoutConfirm by remember { mutableStateOf(false) } + var showEditHostname by remember { mutableStateOf(false) } + var showExitNodeSheet by remember { mutableStateOf(false) } + + if (isAccountViewOpen) { + // System back gesture / back button returns to previous screen + BackHandler { + isAccountViewOpen = false + } + + Scaffold( + modifier = Modifier.fillMaxSize(), + topBar = { + TopAppBar( + navigationIcon = { + IconButton(onClick = { isAccountViewOpen = false }) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.btn_back) + ) + } + }, + title = { + Text( + text = stringResource(R.string.nav_account), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold + ) + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.surface, + titleContentColor = MaterialTheme.colorScheme.onSurface + ) + ) + } + ) { innerPadding -> + AccountScreen( + currentAccount = currentAccount, + accounts = accountList, + isModuleEnabled = moduleState == ModuleState.ENABLED, + onSelectAccount = { profile -> viewModel.switchAccount(profile) }, + onAddAccountClick = { viewModel.startLoginFlow() }, + onLogoutClick = { showLogoutConfirm = true }, + modifier = Modifier.padding(innerPadding) + ) + } + } else if (isAboutViewOpen) { + BackHandler { + isAboutViewOpen = false + } + + Scaffold( + modifier = Modifier.fillMaxSize(), + topBar = { + TopAppBar( + navigationIcon = { + IconButton(onClick = { isAboutViewOpen = false }) { + Icon( + imageVector = Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.btn_back) + ) + } + }, + title = { + Text( + text = stringResource(R.string.section_about), + style = MaterialTheme.typography.titleLarge, + fontWeight = FontWeight.Bold + ) + }, + colors = TopAppBarDefaults.topAppBarColors( + containerColor = MaterialTheme.colorScheme.surface, + titleContentColor = MaterialTheme.colorScheme.onSurface + ) + ) + } + ) { innerPadding -> + AboutScreen( + onCheckAppUpdate = { viewModel.checkAppUpdateManually(context) }, + isCheckingUpdate = isCheckingAppUpdate, + modifier = Modifier.padding(innerPadding) + ) + } + } else { + Scaffold( + modifier = Modifier.fillMaxSize(), + topBar = { + AppTopBar( + onAccountClick = { isAccountViewOpen = true }, + onAboutClick = { isAboutViewOpen = true } + ) + }, + bottomBar = { + AppBottomBar( + currentRoute = currentRoute, + onNavigate = { route -> currentRoute = route } + ) + } + ) { innerPadding -> + when (currentRoute) { + "dashboard" -> { + val isLoggedIn = currentAccount != null && currentAccount?.account?.isNotEmpty() == true + DashboardScreen( + moduleState = moduleState, + moduleVersion = installedModule?.version ?: "", + serviceVersion = serviceVersion, + isLoggedIn = isLoggedIn, + deviceStatus = deviceStatus, + serviceState = serviceState, + exitNodeState = exitNodeState, + onToggleModule = { viewModel.toggleModule(context) }, + onInstallModule = { viewModel.showInstallDialog() }, + onDeleteModule = { showDeleteConfirm = true }, + onCheckModuleUpdate = { viewModel.checkModuleUpdateManually(context) }, + onEditDeviceName = { showEditHostname = true }, + onExitNodeClick = { + showExitNodeSheet = true + viewModel.refreshExitNodes() + }, + onRefresh = { viewModel.refreshManually() }, + modifier = Modifier.padding(innerPadding) + ) + } + "devices" -> { + DevicesScreen( + devices = deviceList, + pingResults = pingResults, + pingingDevices = pingingDevices, + onPingDevice = { device -> viewModel.pingDevice(device) }, + onRefresh = { viewModel.refreshDeviceList() }, + modifier = Modifier.padding(innerPadding) + ) + } + "settings" -> { + SettingsScreen( + networkPrefs = networkPrefs, + isServiceRunning = moduleState == ModuleState.ENABLED && serviceState == ServiceState.RUNNING, + onToggleAllowIncoming = { viewModel.setAllowIncoming(it) }, + onToggleUseDns = { viewModel.setUseTailscaleDns(it) }, + onToggleAcceptSubnets = { viewModel.setAcceptSubnetRoutes(it) }, + onResetNetworkPrefs = { viewModel.resetNetworkPrefs() }, + modifier = Modifier.padding(innerPadding) + ) + } + } + } + } + + // Dialog 1: Root permission check + if (rootState == RootState.DENIED) { + RootMissingDialog( + onConfirmExit = onExitApp + ) + } + + // Dialog 2: Module install / update sync + ModuleSyncDialog( + syncState = moduleSyncState, + onStartSync = { viewModel.startModuleSync(context) }, + onDismiss = { viewModel.dismissSyncDialog() }, + onRetry = { viewModel.startModuleSync(context) }, + onDontShowAgain = { versionCode -> viewModel.suppressModuleUpdate(versionCode) } + ) + + // Dialog 3: App Update + AppUpdateDialog( + updateInfo = appUpdateInfo, + onDownload = { url -> + try { + val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)) + context.startActivity(intent) + } catch (_: Exception) {} + viewModel.dismissAppUpdate() + }, + onDismiss = { viewModel.dismissAppUpdate() }, + onDontShowAgain = { versionCode -> viewModel.suppressAppUpdate(versionCode) } + ) + + // Dialog 3: Module deletion confirmation + if (showDeleteConfirm) { + DeleteConfirmDialog( + onConfirm = { + showDeleteConfirm = false + viewModel.deleteModule() + }, + onDismiss = { + showDeleteConfirm = false + } + ) + } + + // Dialog 4: Browser-guided Login Dialog + if (isGeneratingLoginUrl || !loginUrl.isNullOrEmpty()) { + LoginDialog( + loginUrl = loginUrl, + isLoading = isGeneratingLoginUrl, + onDismiss = { viewModel.dismissLoginDialog() } + ) + } + + // Dialog 5: Logout confirmation + if (showLogoutConfirm) { + LogoutConfirmDialog( + onConfirm = { + showLogoutConfirm = false + viewModel.logout() + }, + onDismiss = { + showLogoutConfirm = false + } + ) + } + + // Dialog 6: Edit Device Hostname + if (showEditHostname) { + EditHostnameDialog( + currentHostname = deviceStatus.hostName, + onConfirm = { newName -> + showEditHostname = false + viewModel.updateHostname(newName, context) + }, + onDismiss = { + showEditHostname = false + } + ) + } + + // BottomSheet: Exit Node Settings (Matches desktop UI) + if (showExitNodeSheet) { + ExitNodeBottomSheet( + exitNodeState = exitNodeState, + isRefreshing = isRefreshingExitNodes, + onRefresh = { viewModel.refreshExitNodes() }, + onSelectNode = { nodeId -> + showExitNodeSheet = false + viewModel.setExitNode(nodeId) + }, + onToggleAllowLan = { allow -> + viewModel.toggleAllowLanAccess(allow) + }, + onToggleAdvertiseExitNode = { advertise -> + viewModel.toggleAdvertiseExitNode(advertise) + }, + onDismiss = { + showExitNodeSheet = false + } + ) + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/SettingsScreen.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/SettingsScreen.kt new file mode 100644 index 0000000..ff79d6d --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/screens/SettingsScreen.kt @@ -0,0 +1,586 @@ +package com.lzxnone.tailscalemanager.ui.screens + +import android.widget.Toast +import androidx.compose.animation.AnimatedVisibility +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.background +import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.ColorLens +import androidx.compose.material.icons.filled.DarkMode +import androidx.compose.material.icons.filled.Dns +import androidx.compose.material.icons.filled.Info +import androidx.compose.material.icons.filled.Language +import androidx.compose.material.icons.filled.Palette +import androidx.compose.material.icons.filled.RestartAlt +import androidx.compose.material.icons.filled.Security +import androidx.compose.material.icons.filled.Sync +import androidx.compose.material.icons.filled.Update +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.RadioButton +import androidx.compose.material3.Switch +import androidx.compose.material3.SwitchDefaults +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import com.lzxnone.tailscalemanager.R +import com.lzxnone.tailscalemanager.core.settings.AppPreferences +import com.lzxnone.tailscalemanager.model.TailscaleNetworkPrefs + +@Composable +fun SettingsScreen( + networkPrefs: TailscaleNetworkPrefs, + isServiceRunning: Boolean, + onToggleAllowIncoming: (Boolean) -> Unit, + onToggleUseDns: (Boolean) -> Unit, + onToggleAcceptSubnets: (Boolean) -> Unit, + onResetNetworkPrefs: () -> Unit, + modifier: Modifier = Modifier +) { + val context = LocalContext.current + + val language by AppPreferences.language.collectAsState() + val themeMode by AppPreferences.themeMode.collectAsState() + val dynamicColor by AppPreferences.dynamicColor.collectAsState() + val customColorKey by AppPreferences.customColorKey.collectAsState() + + var showLanguageDialog by remember { mutableStateOf(false) } + var showThemeModeDialog by remember { mutableStateOf(false) } + var showColorPaletteDialog by remember { mutableStateOf(false) } + var showResetConfirmDialog by remember { mutableStateOf(false) } + + val colorOptions = listOf( + "blue" to Color(0xFF1976D2), + "purple" to Color(0xFF6750A4), + "green" to Color(0xFF2E7D32), + "orange" to Color(0xFFE65100), + "crimson" to Color(0xFFC2185B), + "teal" to Color(0xFF00796B) + ) + + Column( + modifier = modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp) + ) { + // ========================================== + // 板块 1: 语言板块 + // ========================================== + SectionHeader(text = stringResource(R.string.section_language)) + + SettingsCard { + SettingsItemRow( + icon = { + Icon( + imageVector = Icons.Default.Language, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + }, + title = stringResource(R.string.settings_language_title), + subtitle = when (language) { + "zh" -> stringResource(R.string.settings_lang_zh) + "en" -> stringResource(R.string.settings_lang_en) + else -> stringResource(R.string.settings_lang_system) + }, + onClick = { showLanguageDialog = true } + ) + } + + // ========================================== + // 板块 2: 外观板块 + // ========================================== + SectionHeader(text = stringResource(R.string.section_appearance)) + + SettingsCard { + // 2.1 主题模式 + SettingsItemRow( + icon = { + Icon( + imageVector = Icons.Default.DarkMode, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + }, + title = stringResource(R.string.settings_theme_mode), + subtitle = when (themeMode) { + "light" -> stringResource(R.string.settings_theme_light) + "dark" -> stringResource(R.string.settings_theme_dark) + else -> stringResource(R.string.settings_theme_system) + }, + onClick = { showThemeModeDialog = true } + ) + + HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp)) + + // 2.2 系统主题颜色 (Switch) + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 12.dp, horizontal = 4.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Default.ColorLens, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = stringResource(R.string.settings_dynamic_color), + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + } + + Spacer(modifier = Modifier.width(12.dp)) + + Switch( + checked = dynamicColor, + onCheckedChange = { AppPreferences.setDynamicColor(it) }, + colors = SwitchDefaults.colors( + checkedThumbColor = MaterialTheme.colorScheme.primary, + checkedTrackColor = MaterialTheme.colorScheme.primaryContainer + ) + ) + } + + HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp)) + + // 2.3 主题颜色 (动态主题开启时禁用,默认为蓝色) + val isCustomColorEnabled = !dynamicColor + val currentColor = colorOptions.find { it.first == customColorKey }?.second ?: Color(0xFF1976D2) + + Row( + modifier = Modifier + .fillMaxWidth() + .alpha(if (isCustomColorEnabled) 1.0f else 0.45f) + .clip(RoundedCornerShape(12.dp)) + .clickable(enabled = isCustomColorEnabled) { showColorPaletteDialog = true } + .padding(vertical = 12.dp, horizontal = 4.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = Icons.Default.Palette, + contentDescription = null, + tint = if (isCustomColorEnabled) currentColor else MaterialTheme.colorScheme.onSurfaceVariant + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = stringResource(R.string.settings_theme_color), + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + } + + Box( + modifier = Modifier + .size(24.dp) + .clip(CircleShape) + .background(currentColor) + ) + } + } + + // ========================================== + // 板块 3: Tailscale 偏好设置板块 (上面的内容) + // ========================================== + SectionHeader(text = stringResource(R.string.section_network_prefs)) + + SettingsCard { + // 3.1 允许入站连接 + PreferenceSwitchRow( + icon = Icons.Default.Security, + title = stringResource(R.string.prefs_allow_incoming), + subtitle = stringResource(R.string.prefs_allow_incoming_desc), + checked = networkPrefs.allowIncoming, + enabled = isServiceRunning, + onCheckedChange = onToggleAllowIncoming + ) + + HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp)) + + // 3.2 使用 Tailscale DNS 设置 + PreferenceSwitchRow( + icon = Icons.Default.Dns, + title = stringResource(R.string.prefs_use_dns), + subtitle = stringResource(R.string.prefs_use_dns_desc), + checked = networkPrefs.useTailscaleDns, + enabled = isServiceRunning, + onCheckedChange = onToggleUseDns + ) + + HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp)) + + // 3.3 接收子网路由 + PreferenceSwitchRow( + icon = Icons.Default.Sync, + title = stringResource(R.string.prefs_use_subnets), + subtitle = stringResource(R.string.prefs_use_subnets_desc), + checked = networkPrefs.acceptSubnetRoutes, + enabled = isServiceRunning, + onCheckedChange = onToggleAcceptSubnets + ) + + HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp)) + + // 3.4 恢复默认设置 + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .clickable(enabled = isServiceRunning) { showResetConfirmDialog = true } + .padding(vertical = 12.dp, horizontal = 4.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Icon( + imageVector = Icons.Default.RestartAlt, + contentDescription = null, + tint = MaterialTheme.colorScheme.error + ) + Spacer(modifier = Modifier.width(16.dp)) + Text( + text = stringResource(R.string.prefs_reset_defaults), + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.error + ) + } + } + + Spacer(modifier = Modifier.height(24.dp)) + } + + // Dialog 1: 语言选择 + if (showLanguageDialog) { + AlertDialog( + onDismissRequest = { showLanguageDialog = false }, + title = { Text(text = stringResource(R.string.settings_language_title)) }, + text = { + Column { + listOf( + "system" to stringResource(R.string.settings_lang_system), + "zh" to stringResource(R.string.settings_lang_zh), + "en" to stringResource(R.string.settings_lang_en) + ).forEach { (code, label) -> + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .clickable { + AppPreferences.setLanguage(context, code) + showLanguageDialog = false + } + .padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + RadioButton( + selected = language == code, + onClick = { + AppPreferences.setLanguage(context, code) + showLanguageDialog = false + } + ) + Spacer(modifier = Modifier.width(8.dp)) + Text(text = label, style = MaterialTheme.typography.bodyLarge) + } + } + } + }, + confirmButton = { + TextButton(onClick = { showLanguageDialog = false }) { + Text(text = stringResource(R.string.btn_confirm)) + } + } + ) + } + + // Dialog 2: 主题模式选择 + if (showThemeModeDialog) { + AlertDialog( + onDismissRequest = { showThemeModeDialog = false }, + title = { Text(text = stringResource(R.string.settings_theme_mode)) }, + text = { + Column { + listOf( + "system" to stringResource(R.string.settings_theme_system), + "light" to stringResource(R.string.settings_theme_light), + "dark" to stringResource(R.string.settings_theme_dark) + ).forEach { (mode, label) -> + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(8.dp)) + .clickable { + AppPreferences.setThemeMode(mode) + showThemeModeDialog = false + } + .padding(vertical = 8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + RadioButton( + selected = themeMode == mode, + onClick = { + AppPreferences.setThemeMode(mode) + showThemeModeDialog = false + } + ) + Spacer(modifier = Modifier.width(8.dp)) + Text(text = label, style = MaterialTheme.typography.bodyLarge) + } + } + } + }, + confirmButton = { + TextButton(onClick = { showThemeModeDialog = false }) { + Text(text = stringResource(R.string.btn_confirm)) + } + } + ) + } + + // Dialog 3: 主题颜色选择(圆形色块直接排列,无名称) + if (showColorPaletteDialog) { + AlertDialog( + onDismissRequest = { showColorPaletteDialog = false }, + title = { Text(text = stringResource(R.string.settings_theme_color)) }, + text = { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 12.dp), + horizontalArrangement = Arrangement.SpaceEvenly, + verticalAlignment = Alignment.CenterVertically + ) { + colorOptions.forEach { (key, color) -> + val isSelected = customColorKey == key + Box( + modifier = Modifier + .size(42.dp) + .clip(CircleShape) + .background(color) + .clickable { + AppPreferences.setCustomColorKey(key) + showColorPaletteDialog = false + }, + contentAlignment = Alignment.Center + ) { + if (isSelected) { + Icon( + imageVector = Icons.Default.Check, + contentDescription = null, + tint = Color.White, + modifier = Modifier.size(24.dp) + ) + } + } + } + } + }, + confirmButton = { + TextButton(onClick = { showColorPaletteDialog = false }) { + Text(text = stringResource(R.string.btn_confirm)) + } + } + ) + } + + // Dialog 4: 恢复默认设置确认 + if (showResetConfirmDialog) { + AlertDialog( + onDismissRequest = { showResetConfirmDialog = false }, + title = { Text(text = stringResource(R.string.prefs_reset_dialog_title)) }, + text = { Text(text = stringResource(R.string.prefs_reset_dialog_message)) }, + confirmButton = { + TextButton( + onClick = { + showResetConfirmDialog = false + onResetNetworkPrefs() + } + ) { + Text(text = stringResource(R.string.btn_confirm), color = MaterialTheme.colorScheme.error) + } + }, + dismissButton = { + TextButton(onClick = { showResetConfirmDialog = false }) { + Text(text = stringResource(R.string.btn_cancel)) + } + } + ) + } +} + +@Composable +private fun SectionHeader(text: String) { + Text( + text = text, + style = MaterialTheme.typography.titleMedium, + fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.primary, + modifier = Modifier.padding(start = 4.dp, top = 4.dp) + ) +} + +@Composable +private fun SettingsCard(content: @Composable () -> Unit) { + Card( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(20.dp), + colors = CardDefaults.cardColors( + containerColor = MaterialTheme.colorScheme.surfaceContainerLowest + ), + border = BorderStroke(1.dp, MaterialTheme.colorScheme.outlineVariant.copy(alpha = 0.7f)), + elevation = CardDefaults.cardElevation(defaultElevation = 1.dp) + ) { + Column( + modifier = Modifier + .fillMaxWidth() + .padding(16.dp) + ) { + content() + } + } +} + +@Composable +private fun SettingsItemRow( + icon: @Composable () -> Unit, + title: String, + subtitle: String, + onClick: () -> Unit +) { + Row( + modifier = Modifier + .fillMaxWidth() + .clip(RoundedCornerShape(12.dp)) + .clickable { onClick() } + .padding(vertical = 12.dp, horizontal = 4.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + icon() + Spacer(modifier = Modifier.width(16.dp)) + Column { + Text( + text = title, + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + if (subtitle.isNotEmpty()) { + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + } + + Icon( + imageVector = Icons.AutoMirrored.Filled.KeyboardArrowRight, + contentDescription = null, + tint = MaterialTheme.colorScheme.onSurfaceVariant + ) + } +} + +@Composable +private fun PreferenceSwitchRow( + icon: androidx.compose.ui.graphics.vector.ImageVector, + title: String, + subtitle: String, + checked: Boolean, + enabled: Boolean, + onCheckedChange: (Boolean) -> Unit +) { + Row( + modifier = Modifier + .fillMaxWidth() + .alpha(if (enabled) 1.0f else 0.5f) + .padding(vertical = 12.dp, horizontal = 4.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { + Icon( + imageVector = icon, + contentDescription = null, + tint = MaterialTheme.colorScheme.primary + ) + Spacer(modifier = Modifier.width(16.dp)) + Column { + Text( + text = title, + style = MaterialTheme.typography.bodyLarge, + fontWeight = FontWeight.SemiBold, + color = MaterialTheme.colorScheme.onSurface + ) + Spacer(modifier = Modifier.height(2.dp)) + Text( + text = subtitle, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant + ) + } + } + + Spacer(modifier = Modifier.width(12.dp)) + + Switch( + checked = checked, + enabled = enabled, + onCheckedChange = { onCheckedChange(it) }, + colors = SwitchDefaults.colors( + checkedThumbColor = MaterialTheme.colorScheme.primary, + checkedTrackColor = MaterialTheme.colorScheme.primaryContainer + ) + ) + } +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/theme/Color.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/theme/Color.kt new file mode 100644 index 0000000..f03aa26 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/theme/Color.kt @@ -0,0 +1,11 @@ +package com.lzxnone.tailscalemanager.ui.theme + +import androidx.compose.ui.graphics.Color + +val Purple80 = Color(0xFFD0BCFF) +val PurpleGrey80 = Color(0xFFCCC2DC) +val Pink80 = Color(0xFFEFB8C8) + +val Purple40 = Color(0xFF6650a4) +val PurpleGrey40 = Color(0xFF625b71) +val Pink40 = Color(0xFF7D5260) \ No newline at end of file diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/theme/Theme.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/theme/Theme.kt new file mode 100644 index 0000000..a354c04 --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/theme/Theme.kt @@ -0,0 +1,419 @@ +package com.lzxnone.tailscalemanager.ui.theme + +import android.os.Build +import androidx.compose.foundation.isSystemInDarkTheme +import androidx.compose.material3.ColorScheme +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.darkColorScheme +import androidx.compose.material3.dynamicDarkColorScheme +import androidx.compose.material3.dynamicLightColorScheme +import androidx.compose.material3.lightColorScheme +import androidx.compose.runtime.Composable +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.platform.LocalContext + +data class ThemeColorPalette( + val primary: Color, + val onPrimary: Color, + val primaryContainer: Color, + val onPrimaryContainer: Color, + val secondary: Color, + val onSecondary: Color, + val secondaryContainer: Color, + val onSecondaryContainer: Color, + val background: Color, + val onBackground: Color, + val surface: Color, + val onSurface: Color, + val surfaceVariant: Color, + val onSurfaceVariant: Color, + val surfaceContainer: Color, + val surfaceContainerLow: Color, + val surfaceContainerLowest: Color, + val surfaceContainerHigh: Color, + val surfaceContainerHighest: Color, + val outline: Color, + val outlineVariant: Color +) + +private fun ThemeColorPalette.toColorScheme(isDark: Boolean): ColorScheme { + return if (isDark) { + darkColorScheme( + primary = primary, + onPrimary = onPrimary, + primaryContainer = primaryContainer, + onPrimaryContainer = onPrimaryContainer, + secondary = secondary, + onSecondary = onSecondary, + secondaryContainer = secondaryContainer, + onSecondaryContainer = onSecondaryContainer, + background = background, + onBackground = onBackground, + surface = surface, + onSurface = onSurface, + surfaceVariant = surfaceVariant, + onSurfaceVariant = onSurfaceVariant, + surfaceContainer = surfaceContainer, + surfaceContainerLow = surfaceContainerLow, + surfaceContainerLowest = surfaceContainerLowest, + surfaceContainerHigh = surfaceContainerHigh, + surfaceContainerHighest = surfaceContainerHighest, + outline = outline, + outlineVariant = outlineVariant + ) + } else { + lightColorScheme( + primary = primary, + onPrimary = onPrimary, + primaryContainer = primaryContainer, + onPrimaryContainer = onPrimaryContainer, + secondary = secondary, + onSecondary = onSecondary, + secondaryContainer = secondaryContainer, + onSecondaryContainer = onSecondaryContainer, + background = background, + onBackground = onBackground, + surface = surface, + onSurface = onSurface, + surfaceVariant = surfaceVariant, + onSurfaceVariant = onSurfaceVariant, + surfaceContainer = surfaceContainer, + surfaceContainerLow = surfaceContainerLow, + surfaceContainerLowest = surfaceContainerLowest, + surfaceContainerHigh = surfaceContainerHigh, + surfaceContainerHighest = surfaceContainerHighest, + outline = outline, + outlineVariant = outlineVariant + ) + } +} + +fun getCustomColorScheme(colorKey: String, isDark: Boolean): ColorScheme { + val palette = when (colorKey) { + "green" -> if (isDark) { + ThemeColorPalette( + primary = Color(0xFF81C784), + onPrimary = Color(0xFF003A08), + primaryContainer = Color(0xFF1B5E20), + onPrimaryContainer = Color(0xFFC8E6C9), + secondary = Color(0xFFB9CCB5), + onSecondary = Color(0xFF253424), + secondaryContainer = Color(0xFF3B4B39), + onSecondaryContainer = Color(0xFFD5E8D0), + background = Color(0xFF111511), + onBackground = Color(0xFFE1E4DF), + surface = Color(0xFF111511), + onSurface = Color(0xFFE1E4DF), + surfaceVariant = Color(0xFF424940), + onSurfaceVariant = Color(0xFFC2C9BE), + surfaceContainer = Color(0xFF1C221C), + surfaceContainerLow = Color(0xFF161C16), + surfaceContainerLowest = Color(0xFF0D110E), + surfaceContainerHigh = Color(0xFF242A24), + surfaceContainerHighest = Color(0xFF2D342D), + outline = Color(0xFF8C9388), + outlineVariant = Color(0xFF2B332B) + ) + } else { + ThemeColorPalette( + primary = Color(0xFF2E7D32), + onPrimary = Color.White, + primaryContainer = Color(0xFFC8E6C9), + onPrimaryContainer = Color(0xFF002204), + secondary = Color(0xFF526350), + onSecondary = Color.White, + secondaryContainer = Color(0xFFD5E8D0), + onSecondaryContainer = Color(0xFF101F10), + background = Color(0xFFF7FBF6), + onBackground = Color(0xFF191C19), + surface = Color(0xFFF7FBF6), + onSurface = Color(0xFF191C19), + surfaceVariant = Color(0xFFDEE5D9), + onSurfaceVariant = Color(0xFF424940), + surfaceContainer = Color(0xFFE8F1E7), + surfaceContainerLow = Color(0xFFEFF6EE), + surfaceContainerLowest = Color(0xFFFFFFFF), + surfaceContainerHigh = Color(0xFFE2EBE1), + surfaceContainerHighest = Color(0xFFDCE5DB), + outline = Color(0xFF72796F), + outlineVariant = Color(0xFFD5DFD3) + ) + } + "orange" -> if (isDark) { + ThemeColorPalette( + primary = Color(0xFFFFB59D), + onPrimary = Color(0xFF5A1B00), + primaryContainer = Color(0xFF7D2900), + onPrimaryContainer = Color(0xFFFFDBCF), + secondary = Color(0xFFE7BDB2), + onSecondary = Color(0xFF442A22), + secondaryContainer = Color(0xFF5D4037), + onSecondaryContainer = Color(0xFFFFDBD1), + background = Color(0xFF181210), + onBackground = Color(0xFFECE0DB), + surface = Color(0xFF181210), + onSurface = Color(0xFFECE0DB), + surfaceVariant = Color(0xFF53433F), + onSurfaceVariant = Color(0xFFD8C2BC), + surfaceContainer = Color(0xFF261D1A), + surfaceContainerLow = Color(0xFF201815), + surfaceContainerLowest = Color(0xFF130D0B), + surfaceContainerHigh = Color(0xFF302521), + surfaceContainerHighest = Color(0xFF3B2F2A), + outline = Color(0xFFA08C86), + outlineVariant = Color(0xFF382B27) + ) + } else { + ThemeColorPalette( + primary = Color(0xFFE65100), + onPrimary = Color.White, + primaryContainer = Color(0xFFFFDBCF), + onPrimaryContainer = Color(0xFF380D00), + secondary = Color(0xFF77574E), + onSecondary = Color.White, + secondaryContainer = Color(0xFFFFDBD1), + onSecondaryContainer = Color(0xFF2C150F), + background = Color(0xFFFDF8F6), + onBackground = Color(0xFF201A18), + surface = Color(0xFFFDF8F6), + onSurface = Color(0xFF201A18), + surfaceVariant = Color(0xFFF5DED8), + onSurfaceVariant = Color(0xFF53433F), + surfaceContainer = Color(0xFFF6ECE7), + surfaceContainerLow = Color(0xFFFCF2ED), + surfaceContainerLowest = Color(0xFFFFFFFF), + surfaceContainerHigh = Color(0xFFF1E6E1), + surfaceContainerHighest = Color(0xFFECE0DB), + outline = Color(0xFF85736E), + outlineVariant = Color(0xFFE7DDD8) + ) + } + "purple" -> if (isDark) { + ThemeColorPalette( + primary = Color(0xFFD0BCFF), + onPrimary = Color(0xFF381E72), + primaryContainer = Color(0xFF4F378B), + onPrimaryContainer = Color(0xFFEADDFF), + secondary = Color(0xFFCCC2DC), + onSecondary = Color(0xFF332D41), + secondaryContainer = Color(0xFF4A4458), + onSecondaryContainer = Color(0xFFE8DEF8), + background = Color(0xFF141218), + onBackground = Color(0xFFE6E1E5), + surface = Color(0xFF141218), + onSurface = Color(0xFFE6E1E5), + surfaceVariant = Color(0xFF49454E), + onSurfaceVariant = Color(0xFFCAC4D0), + surfaceContainer = Color(0xFF221F28), + surfaceContainerLow = Color(0xFF1C1921), + surfaceContainerLowest = Color(0xFF0F0D13), + surfaceContainerHigh = Color(0xFF2B2731), + surfaceContainerHighest = Color(0xFF34303B), + outline = Color(0xFF948F9A), + outlineVariant = Color(0xFF332F3B) + ) + } else { + ThemeColorPalette( + primary = Color(0xFF6750A4), + onPrimary = Color.White, + primaryContainer = Color(0xFFEADDFF), + onPrimaryContainer = Color(0xFF21005D), + secondary = Color(0xFF625B71), + onSecondary = Color.White, + secondaryContainer = Color(0xFFE8DEF8), + onSecondaryContainer = Color(0xFF1D192B), + background = Color(0xFFFAF7FD), + onBackground = Color(0xFF1D1B20), + surface = Color(0xFFFAF7FD), + onSurface = Color(0xFF1D1B20), + surfaceVariant = Color(0xFFE7E0EB), + onSurfaceVariant = Color(0xFF49454E), + surfaceContainer = Color(0xFFF1EDF6), + surfaceContainerLow = Color(0xFFF7F2FC), + surfaceContainerLowest = Color(0xFFFFFFFF), + surfaceContainerHigh = Color(0xFFEBE7F0), + surfaceContainerHighest = Color(0xFFE5E1EA), + outline = Color(0xFF7A757F), + outlineVariant = Color(0xFFDDD8E3) + ) + } + "crimson" -> if (isDark) { + ThemeColorPalette( + primary = Color(0xFFFFAFD0), + onPrimary = Color(0xFF5C002B), + primaryContainer = Color(0xFF81083E), + onPrimaryContainer = Color(0xFFFFD8E4), + secondary = Color(0xFFE2BDC6), + onSecondary = Color(0xFF422931), + secondaryContainer = Color(0xFF5A3F47), + onSecondaryContainer = Color(0xFFFFD9E2), + background = Color(0xFF171213), + onBackground = Color(0xFFEAE0E2), + surface = Color(0xFF171213), + onSurface = Color(0xFFEAE0E2), + surfaceVariant = Color(0xFF514347), + onSurfaceVariant = Color(0xFFD6C2C6), + surfaceContainer = Color(0xFF261D20), + surfaceContainerLow = Color(0xFF1E1719), + surfaceContainerLowest = Color(0xFF120D0E), + surfaceContainerHigh = Color(0xFF302428), + surfaceContainerHighest = Color(0xFF3B2E32), + outline = Color(0xFF9E8C90), + outlineVariant = Color(0xFF3A2C30) + ) + } else { + ThemeColorPalette( + primary = Color(0xFFC2185B), + onPrimary = Color.White, + primaryContainer = Color(0xFFFFD8E4), + onPrimaryContainer = Color(0xFF3E001D), + secondary = Color(0xFF74565F), + onSecondary = Color.White, + secondaryContainer = Color(0xFFFFD9E2), + onSecondaryContainer = Color(0xFF2B151C), + background = Color(0xFFFDF7F8), + onBackground = Color(0xFF201A1B), + surface = Color(0xFFFDF7F8), + onSurface = Color(0xFF201A1B), + surfaceVariant = Color(0xFFF2DDE1), + onSurfaceVariant = Color(0xFF514347), + surfaceContainer = Color(0xFFF6ECEE), + surfaceContainerLow = Color(0xFFFCF1F3), + surfaceContainerLowest = Color(0xFFFFFFFF), + surfaceContainerHigh = Color(0xFFF0E6E8), + surfaceContainerHighest = Color(0xFFEAE0E2), + outline = Color(0xFF837377), + outlineVariant = Color(0xFFE4DADB) + ) + } + "teal" -> if (isDark) { + ThemeColorPalette( + primary = Color(0xFF53DBC9), + onPrimary = Color(0xFF003731), + primaryContainer = Color(0xFF005048), + onPrimaryContainer = Color(0xFF73F8E6), + secondary = Color(0xFFB1CCC6), + onSecondary = Color(0xFF1C3531), + secondaryContainer = Color(0xFF324B47), + onSecondaryContainer = Color(0xFFCCE8E2), + background = Color(0xFF0F1514), + onBackground = Color(0xFFDEE4E2), + surface = Color(0xFF0F1514), + onSurface = Color(0xFFDEE4E2), + surfaceVariant = Color(0xFF3F4946), + onSurfaceVariant = Color(0xFFBFC9C6), + surfaceContainer = Color(0xFF1B2321), + surfaceContainerLow = Color(0xFF151C1B), + surfaceContainerLowest = Color(0xFF0B100F), + surfaceContainerHigh = Color(0xFF232C2A), + surfaceContainerHighest = Color(0xFF2C3633), + outline = Color(0xFF899390), + outlineVariant = Color(0xFF283431) + ) + } else { + ThemeColorPalette( + primary = Color(0xFF006A60), + onPrimary = Color.White, + primaryContainer = Color(0xFF73F8E6), + onPrimaryContainer = Color(0xFF00201C), + secondary = Color(0xFF4A635F), + onSecondary = Color.White, + secondaryContainer = Color(0xFFCCE8E2), + onSecondaryContainer = Color(0xFF05201C), + background = Color(0xFFF5FAF9), + onBackground = Color(0xFF191C1C), + surface = Color(0xFFF5FAF9), + onSurface = Color(0xFF191C1C), + surfaceVariant = Color(0xFFDAE5E1), + onSurfaceVariant = Color(0xFF3F4946), + surfaceContainer = Color(0xFFE6F0EE), + surfaceContainerLow = Color(0xFFEDF6F4), + surfaceContainerLowest = Color(0xFFFFFFFF), + surfaceContainerHigh = Color(0xFFE0EAE8), + surfaceContainerHighest = Color(0xFFDAE5E3), + outline = Color(0xFF6F7976), + outlineVariant = Color(0xFFD4DFDC) + ) + } + else -> { // "blue" (默认蓝色) + if (isDark) { + ThemeColorPalette( + primary = Color(0xFF9ECAFF), + onPrimary = Color(0xFF003258), + primaryContainer = Color(0xFF00497D), + onPrimaryContainer = Color(0xFFD1E4FF), + secondary = Color(0xFFBBC7DB), + onSecondary = Color(0xFF253140), + secondaryContainer = Color(0xFF3B4858), + onSecondaryContainer = Color(0xFFD7E3F7), + background = Color(0xFF111418), + onBackground = Color(0xFFE1E2E8), + surface = Color(0xFF111418), + onSurface = Color(0xFFE1E2E8), + surfaceVariant = Color(0xFF43474E), + onSurfaceVariant = Color(0xFFC3C7D0), + surfaceContainer = Color(0xFF1D2228), + surfaceContainerLow = Color(0xFF171B20), + surfaceContainerLowest = Color(0xFF0E1114), + surfaceContainerHigh = Color(0xFF272C33), + surfaceContainerHighest = Color(0xFF32373E), + outline = Color(0xFF8D9199), + outlineVariant = Color(0xFF2C323B) + ) + } else { + ThemeColorPalette( + primary = Color(0xFF1976D2), + onPrimary = Color.White, + primaryContainer = Color(0xFFD1E4FF), + onPrimaryContainer = Color(0xFF001D36), + secondary = Color(0xFF535F70), + onSecondary = Color.White, + secondaryContainer = Color(0xFFD7E3F7), + onSecondaryContainer = Color(0xFF101C2B), + background = Color(0xFFF8F9FF), + onBackground = Color(0xFF191C20), + surface = Color(0xFFF8F9FF), + onSurface = Color(0xFF191C20), + surfaceVariant = Color(0xFFDFE2EB), + onSurfaceVariant = Color(0xFF43474E), + surfaceContainer = Color(0xFFEAEFF7), + surfaceContainerLow = Color(0xFFF1F5FC), + surfaceContainerLowest = Color(0xFFFFFFFF), + surfaceContainerHigh = Color(0xFFE4E9F1), + surfaceContainerHighest = Color(0xFFDEE3EB), + outline = Color(0xFF73777F), + outlineVariant = Color(0xFFD6DCE6) + ) + } + } + } + return palette.toColorScheme(isDark) +} + +@Composable +fun TailscaleManagerTheme( + themeMode: String = "system", + dynamicColor: Boolean = true, + customColorKey: String = "blue", + content: @Composable () -> Unit +) { + val isDark = when (themeMode) { + "light" -> false + "dark" -> true + else -> isSystemInDarkTheme() + } + + val colorScheme = when { + dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> { + val context = LocalContext.current + if (isDark) dynamicDarkColorScheme(context) else dynamicLightColorScheme(context) + } + else -> getCustomColorScheme(customColorKey, isDark) + } + + MaterialTheme( + colorScheme = colorScheme, + typography = Typography, + content = content + ) +} diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/theme/Type.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/theme/Type.kt new file mode 100644 index 0000000..529ea7d --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/theme/Type.kt @@ -0,0 +1,34 @@ +package com.lzxnone.tailscalemanager.ui.theme + +import androidx.compose.material3.Typography +import androidx.compose.ui.text.TextStyle +import androidx.compose.ui.text.font.FontFamily +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.sp + +// Set of Material typography styles to start with +val Typography = Typography( + bodyLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 16.sp, + lineHeight = 24.sp, + letterSpacing = 0.5.sp + ) + /* Other default text styles to override + titleLarge = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Normal, + fontSize = 22.sp, + lineHeight = 28.sp, + letterSpacing = 0.sp + ), + labelSmall = TextStyle( + fontFamily = FontFamily.Default, + fontWeight = FontWeight.Medium, + fontSize = 11.sp, + lineHeight = 16.sp, + letterSpacing = 0.5.sp + ) + */ +) \ No newline at end of file diff --git a/app/src/main/java/com/lzxnone/tailscalemanager/ui/viewmodel/MainViewModel.kt b/app/src/main/java/com/lzxnone/tailscalemanager/ui/viewmodel/MainViewModel.kt new file mode 100644 index 0000000..680499f --- /dev/null +++ b/app/src/main/java/com/lzxnone/tailscalemanager/ui/viewmodel/MainViewModel.kt @@ -0,0 +1,473 @@ +package com.lzxnone.tailscalemanager.ui.viewmodel + +import android.content.Context +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import com.lzxnone.tailscalemanager.BuildConfig +import com.lzxnone.tailscalemanager.core.module.ModuleManager +import com.lzxnone.tailscalemanager.core.module.ModuleState +import com.lzxnone.tailscalemanager.core.module.ModuleSyncState +import com.lzxnone.tailscalemanager.core.root.RootBridge +import com.lzxnone.tailscalemanager.core.root.RootState +import com.lzxnone.tailscalemanager.core.service.ServiceState +import com.lzxnone.tailscalemanager.core.service.TailscaleController +import com.lzxnone.tailscalemanager.core.settings.AppPreferences +import com.lzxnone.tailscalemanager.core.update.AppUpdateManager +import com.lzxnone.tailscalemanager.model.AppUpdateInfo +import com.lzxnone.tailscalemanager.model.ModuleInfo +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch + +class MainViewModel : ViewModel() { + + private val _rootState = MutableStateFlow(RootState.CHECKING) + val rootState: StateFlow = _rootState.asStateFlow() + + private val _moduleState = MutableStateFlow(ModuleState.NOT_INSTALLED) + val moduleState: StateFlow = _moduleState.asStateFlow() + + private val _moduleSyncState = MutableStateFlow(ModuleSyncState.Idle) + val moduleSyncState: StateFlow = _moduleSyncState.asStateFlow() + + private val _installedModule = MutableStateFlow(null) + val installedModule: StateFlow = _installedModule.asStateFlow() + + private val _serviceState = MutableStateFlow(ServiceState.UNKNOWN) + val serviceState: StateFlow = _serviceState.asStateFlow() + + private val _deviceStatus = MutableStateFlow(com.lzxnone.tailscalemanager.model.DeviceStatus()) + val deviceStatus: StateFlow = _deviceStatus.asStateFlow() + + private val _accountList = MutableStateFlow>(emptyList()) + val accountList: StateFlow> = _accountList.asStateFlow() + + private val _currentAccount = MutableStateFlow(null) + val currentAccount: StateFlow = _currentAccount.asStateFlow() + + private val _loginUrl = MutableStateFlow(null) + val loginUrl: StateFlow = _loginUrl.asStateFlow() + + private val _exitNodeState = MutableStateFlow(com.lzxnone.tailscalemanager.model.ExitNodeState()) + val exitNodeState: StateFlow = _exitNodeState.asStateFlow() + + private val _isGeneratingLoginUrl = MutableStateFlow(false) + val isGeneratingLoginUrl: StateFlow = _isGeneratingLoginUrl.asStateFlow() + + private val _isRefreshing = MutableStateFlow(false) + val isRefreshing: StateFlow = _isRefreshing.asStateFlow() + + private val _isRefreshingExitNodes = MutableStateFlow(false) + val isRefreshingExitNodes: StateFlow = _isRefreshingExitNodes.asStateFlow() + + private val _serviceVersion = MutableStateFlow("") + val serviceVersion: StateFlow = _serviceVersion.asStateFlow() + + private val _deviceList = MutableStateFlow>(emptyList()) + val deviceList: StateFlow> = _deviceList.asStateFlow() + + private val _pingResults = MutableStateFlow>(emptyMap()) + val pingResults: StateFlow> = _pingResults.asStateFlow() + + private val _pingingDevices = MutableStateFlow>(emptySet()) + val pingingDevices: StateFlow> = _pingingDevices.asStateFlow() + + private val _networkPrefs = MutableStateFlow(com.lzxnone.tailscalemanager.model.TailscaleNetworkPrefs()) + val networkPrefs: StateFlow = _networkPrefs.asStateFlow() + + private val _appUpdateInfo = MutableStateFlow(null) + val appUpdateInfo: StateFlow = _appUpdateInfo.asStateFlow() + + private val _isCheckingAppUpdate = MutableStateFlow(false) + val isCheckingAppUpdate: StateFlow = _isCheckingAppUpdate.asStateFlow() + + init { + performInitialCheck() + } + + fun performInitialCheck() { + viewModelScope.launch { + // 步骤 1: 检查 Root 权限 + _rootState.value = RootState.CHECKING + val hasRoot = RootBridge.checkRootAccess() + if (!hasRoot) { + _rootState.value = RootState.DENIED + return@launch + } + _rootState.value = RootState.GRANTED + + // 步骤 2: 检查软件更新 + try { + val appUpdateResult = AppUpdateManager.checkAppUpdate() + if (appUpdateResult.isSuccess) { + val info = appUpdateResult.getOrNull() + val suppressedVersion = AppPreferences.getSuppressedAppUpdateVersion() + if (info != null && info.versionCode > BuildConfig.VERSION_CODE && info.versionCode != suppressedVersion) { + _appUpdateInfo.value = info + } + } + } catch (_: Exception) {} + + // 步骤 3: 检查模块与服务状态 (包含自动模块更新检查) + refreshModuleAndServiceStatus(isAutoCheck = true) + } + } + + suspend fun refreshModuleAndServiceStatus(isAutoCheck: Boolean = false) { + _isRefreshing.value = true + try { + val state = ModuleManager.getModuleState() + _moduleState.value = state + + val module = ModuleManager.getInstalledModule() + _installedModule.value = module + + if (state != ModuleState.NOT_INSTALLED) { + _serviceVersion.value = TailscaleController.getServiceVersion() + val syncStatus = ModuleManager.checkSyncStatus() + if (syncStatus is ModuleSyncState.NeedsUpdate) { + val suppressed = AppPreferences.getSuppressedModuleUpdateVersion() + if (!isAutoCheck || syncStatus.bundledVersionCode != suppressed) { + _moduleSyncState.value = syncStatus + } + } + } else { + _serviceVersion.value = "" + } + + // Tailscale service is only active when module is enabled + if (state == ModuleState.ENABLED) { + val sState = TailscaleController.getServiceState() + _serviceState.value = sState + if (sState == ServiceState.RUNNING) { + _deviceStatus.value = TailscaleController.getDeviceStatus() + } else { + _deviceStatus.value = com.lzxnone.tailscalemanager.model.DeviceStatus() + } + + // Fetch account profiles + val profiles = TailscaleController.getAccountProfiles() + _accountList.value = profiles + _currentAccount.value = profiles.find { it.isSelected } ?: profiles.firstOrNull() + + // Fetch exit node state + _exitNodeState.value = TailscaleController.getExitNodeState() + + // Fetch device list + _deviceList.value = TailscaleController.getDeviceList() + + // Fetch network preferences + _networkPrefs.value = TailscaleController.getNetworkPrefs() + } else { + _serviceState.value = ServiceState.STOPPED + _deviceStatus.value = com.lzxnone.tailscalemanager.model.DeviceStatus() + _accountList.value = emptyList() + _currentAccount.value = null + _exitNodeState.value = com.lzxnone.tailscalemanager.model.ExitNodeState() + _deviceList.value = emptyList() + _networkPrefs.value = com.lzxnone.tailscalemanager.model.TailscaleNetworkPrefs() + } + } finally { + _isRefreshing.value = false + } + } + + fun refreshManually() { + viewModelScope.launch { + refreshModuleAndServiceStatus() + } + } + + fun switchAccount(profile: com.lzxnone.tailscalemanager.model.AccountProfile) { + viewModelScope.launch { + TailscaleController.switchAccount(profile.id) + refreshModuleAndServiceStatus() + } + } + + fun startLoginFlow() { + viewModelScope.launch { + _isGeneratingLoginUrl.value = true + _loginUrl.value = null + val result = TailscaleController.generateLoginUrl() + _isGeneratingLoginUrl.value = false + if (result.isSuccess) { + _loginUrl.value = result.getOrNull() + } + } + } + + fun dismissLoginDialog() { + _loginUrl.value = null + _isGeneratingLoginUrl.value = false + refreshManually() + } + + fun logout() { + viewModelScope.launch { + TailscaleController.logout() + refreshModuleAndServiceStatus() + } + } + + fun setExitNode(nodeIdOrName: String) { + viewModelScope.launch { + val allowLan = _exitNodeState.value.allowLanAccess + TailscaleController.setExitNode(nodeIdOrName, allowLan) + refreshModuleAndServiceStatus() + } + } + + fun refreshExitNodes() { + viewModelScope.launch { + if (_moduleState.value != ModuleState.ENABLED || _serviceState.value != ServiceState.RUNNING) { + return@launch + } + _isRefreshingExitNodes.value = true + try { + _exitNodeState.value = TailscaleController.getExitNodeState() + } finally { + _isRefreshingExitNodes.value = false + } + } + } + + fun refreshDeviceList() { + viewModelScope.launch { + if (_moduleState.value == ModuleState.ENABLED && _serviceState.value == ServiceState.RUNNING) { + _deviceList.value = TailscaleController.getDeviceList() + } + } + } + + fun pingDevice(device: com.lzxnone.tailscalemanager.model.TailscaleDevice) { + viewModelScope.launch { + val key = device.ip.ifEmpty { device.name } + _pingingDevices.value = _pingingDevices.value + key + try { + val result = TailscaleController.pingDevice(key) + _pingResults.value = _pingResults.value + (key to result) + } finally { + _pingingDevices.value = _pingingDevices.value - key + } + } + } + + fun toggleAllowLanAccess(allow: Boolean) { + viewModelScope.launch { + _exitNodeState.value = _exitNodeState.value.copy(allowLanAccess = allow) + TailscaleController.setAllowLanAccess(allow) + val currentId = _exitNodeState.value.currentExitNodeId + if (currentId.isNotEmpty()) { + TailscaleController.setExitNode(currentId, allow) + } + refreshModuleAndServiceStatus() + } + } + + fun toggleAdvertiseExitNode(advertise: Boolean) { + viewModelScope.launch { + _exitNodeState.value = _exitNodeState.value.copy(isAdvertisingExitNode = advertise) + TailscaleController.setAdvertiseExitNode(advertise) + refreshModuleAndServiceStatus() + } + } + + fun setAllowIncoming(enabled: Boolean) { + viewModelScope.launch { + _networkPrefs.value = _networkPrefs.value.copy(allowIncoming = enabled) + TailscaleController.setAllowIncoming(enabled) + refreshModuleAndServiceStatus() + } + } + + fun setUseTailscaleDns(enabled: Boolean) { + viewModelScope.launch { + _networkPrefs.value = _networkPrefs.value.copy(useTailscaleDns = enabled) + TailscaleController.setUseTailscaleDns(enabled) + refreshModuleAndServiceStatus() + } + } + + fun setAcceptSubnetRoutes(enabled: Boolean) { + viewModelScope.launch { + _networkPrefs.value = _networkPrefs.value.copy(acceptSubnetRoutes = enabled) + TailscaleController.setAcceptSubnetRoutes(enabled) + refreshModuleAndServiceStatus() + } + } + + fun setAutoUpdate(enabled: Boolean) { + viewModelScope.launch { + _networkPrefs.value = _networkPrefs.value.copy(autoUpdate = enabled) + TailscaleController.setAutoUpdate(enabled) + refreshModuleAndServiceStatus() + } + } + + fun resetNetworkPrefs() { + viewModelScope.launch { + TailscaleController.resetNetworkPrefs() + refreshModuleAndServiceStatus() + } + } + + fun updateHostname(newHostname: String, context: Context) { + viewModelScope.launch { + // 立即在 UI 上响应,卡片名称毫秒级自动变化! + val previousStatus = _deviceStatus.value + _deviceStatus.value = previousStatus.copy(hostName = newHostname) + + val result = TailscaleController.updateHostname(newHostname) + if (result.isSuccess) { + val msg = context.getString(com.lzxnone.tailscalemanager.R.string.edit_hostname_success, newHostname) + android.widget.Toast.makeText(context, msg, android.widget.Toast.LENGTH_SHORT).show() + refreshModuleAndServiceStatus() + } else { + _deviceStatus.value = previousStatus + val err = result.exceptionOrNull()?.localizedMessage ?: "Failed to update hostname" + android.widget.Toast.makeText(context, err, android.widget.Toast.LENGTH_SHORT).show() + } + } + } + + fun showInstallDialog() { + _moduleSyncState.value = ModuleSyncState.NeedsInstall( + bundledVersion = com.lzxnone.tailscalemanager.core.module.ModuleConfig.BUNDLED_VERSION_NAME, + bundledVersionCode = com.lzxnone.tailscalemanager.core.module.ModuleConfig.BUNDLED_VERSION_CODE + ) + } + + fun deleteModule() { + viewModelScope.launch { + ModuleManager.deleteModule() + refreshModuleAndServiceStatus() + } + } + + fun toggleModule(context: Context) { + viewModelScope.launch { + when (_moduleState.value) { + ModuleState.NOT_INSTALLED -> { + // Trigger installation dialog + _moduleSyncState.value = ModuleSyncState.NeedsInstall( + bundledVersion = com.lzxnone.tailscalemanager.core.module.ModuleConfig.BUNDLED_VERSION_NAME, + bundledVersionCode = com.lzxnone.tailscalemanager.core.module.ModuleConfig.BUNDLED_VERSION_CODE + ) + } + ModuleState.ENABLED -> { + ModuleManager.disableModule() + refreshModuleAndServiceStatus() + } + ModuleState.DISABLED -> { + ModuleManager.enableModule() + refreshModuleAndServiceStatus() + } + } + } + } + + fun startModuleSync(context: Context) { + viewModelScope.launch { + val result = ModuleManager.syncModule(context) { step, progress -> + _moduleSyncState.value = ModuleSyncState.Syncing(step, progress) + } + if (result.isSuccess) { + _moduleSyncState.value = ModuleSyncState.Success + refreshModuleAndServiceStatus() + } else { + val errorMsg = result.exceptionOrNull()?.localizedMessage ?: "Unknown error" + _moduleSyncState.value = ModuleSyncState.Error(errorMsg) + } + } + } + + fun dismissSyncDialog() { + _moduleSyncState.value = ModuleSyncState.Idle + } + + fun suppressModuleUpdate(versionCode: Long) { + AppPreferences.setSuppressedModuleUpdateVersion(versionCode) + _moduleSyncState.value = ModuleSyncState.Idle + } + + fun checkModuleUpdateManually(context: Context) { + viewModelScope.launch { + val state = ModuleManager.getModuleState() + if (state == ModuleState.NOT_INSTALLED) { + showInstallDialog() + return@launch + } + val syncStatus = ModuleManager.checkSyncStatus() + if (syncStatus is ModuleSyncState.NeedsUpdate) { + _moduleSyncState.value = syncStatus + } else { + val version = _installedModule.value?.version ?: "" + val msg = context.getString(com.lzxnone.tailscalemanager.R.string.module_already_latest, version) + android.widget.Toast.makeText(context, msg, android.widget.Toast.LENGTH_SHORT).show() + } + } + } + + fun checkAppUpdateManually(context: Context) { + viewModelScope.launch { + _isCheckingAppUpdate.value = true + try { + val result = AppUpdateManager.checkAppUpdate() + if (result.isSuccess) { + val info = result.getOrNull() + if (info != null && info.versionCode > BuildConfig.VERSION_CODE) { + _appUpdateInfo.value = info + } else { + android.widget.Toast.makeText( + context, + context.getString(com.lzxnone.tailscalemanager.R.string.about_latest_version), + android.widget.Toast.LENGTH_SHORT + ).show() + } + } else { + val errorMsg = result.exceptionOrNull()?.localizedMessage ?: "Unknown error" + android.widget.Toast.makeText( + context, + context.getString(com.lzxnone.tailscalemanager.R.string.update_check_failed, errorMsg), + android.widget.Toast.LENGTH_SHORT + ).show() + } + } finally { + _isCheckingAppUpdate.value = false + } + } + } + + fun dismissAppUpdate() { + _appUpdateInfo.value = null + } + + fun suppressAppUpdate(versionCode: Long) { + AppPreferences.setSuppressedAppUpdateVersion(versionCode) + _appUpdateInfo.value = null + } + + fun toggleService() { + viewModelScope.launch { + if (_moduleState.value != ModuleState.ENABLED) return@launch + + val current = _serviceState.value + if (current == ServiceState.RUNNING) { + _serviceState.value = ServiceState.STOPPING + TailscaleController.stopService() + } else { + _serviceState.value = ServiceState.STARTING + TailscaleController.startService() + } + val newState = TailscaleController.getServiceState() + _serviceState.value = newState + if (newState == ServiceState.RUNNING) { + _deviceStatus.value = TailscaleController.getDeviceStatus() + } else { + _deviceStatus.value = com.lzxnone.tailscalemanager.model.DeviceStatus() + } + } + } +} diff --git a/app/src/main/res/drawable/ic_launcher_background.xml b/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 0000000..2dea913 --- /dev/null +++ b/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,10 @@ + + + + diff --git a/app/src/main/res/drawable/ic_launcher_foreground.png b/app/src/main/res/drawable/ic_launcher_foreground.png new file mode 100644 index 0000000..e524879 Binary files /dev/null and b/app/src/main/res/drawable/ic_launcher_foreground.png differ diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher.xml b/app/src/main/res/mipmap-anydpi/ic_launcher.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi/ic_launcher.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml b/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml new file mode 100644 index 0000000..6f3b755 --- /dev/null +++ b/app/src/main/res/mipmap-anydpi/ic_launcher_round.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher.webp b/app/src/main/res/mipmap-hdpi/ic_launcher.webp new file mode 100644 index 0000000..00eb85e Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp new file mode 100644 index 0000000..f95a119 Binary files /dev/null and b/app/src/main/res/mipmap-hdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher.webp b/app/src/main/res/mipmap-mdpi/ic_launcher.webp new file mode 100644 index 0000000..b7af274 Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp new file mode 100644 index 0000000..3e09d2f Binary files /dev/null and b/app/src/main/res/mipmap-mdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp new file mode 100644 index 0000000..24973b2 Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..229d5fb Binary files /dev/null and b/app/src/main/res/mipmap-xhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp new file mode 100644 index 0000000..29dbd64 Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..008caba Binary files /dev/null and b/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp new file mode 100644 index 0000000..a83650d Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher.webp differ diff --git a/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp new file mode 100644 index 0000000..294695d Binary files /dev/null and b/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.webp differ diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xml new file mode 100644 index 0000000..ec176dd --- /dev/null +++ b/app/src/main/res/values-zh-rCN/strings.xml @@ -0,0 +1,192 @@ + + Tailscale Manager + Tailscale Manager + 刷新状态 + + + 仪表盘 + 设备 + 账号 + 设置 + + + 语言 + 应用语言 + 跟随系统 + 简体中文 + English + + 外观 + 主题模式 + 跟随系统 + 浅色模式 + 深色模式 + 系统主题颜色 + 开启后使用 Android 系统动态颜色 (Material You),默认开启 + 主题颜色 + 当系统主题颜色开启时被禁用,默认为蓝色 + 经典蓝 (默认) + 优雅紫 + 自然绿 + 活力橙 + 深绯红 + 沉稳青 + + 偏好设置 + 允许入站连接 + 允许 Tailnet 中的其他设备主动连接此设备 (Shields Up 关闭) + 使用 Tailscale DNS 设置 + 使用 Tailscale MagicDNS 与自定义内网域名解析 + 接收子网路由 + 接收并使用其他节点广播的局域网网段 (Subnet Routes) + 自动安装更新 + 当官方发布新组件时在后台自动更新 + 恢复默认设置 + 恢复默认偏好设置 + 确定要将 Tailscale 网络偏好设置恢复为默认配置吗? + + 关于 + 作者:%1$s + 版本 + 检查更新 + 当前已是最新版本 + + + 所有设备 + 暂未获取到设备列表,请确保 Tailscale 服务已启动 + 本机 + 出口节点 + Ping 探测 + 正在探测连通性与路由… + 直连 + 中继 (DERP) + 延迟:%1$s + 路由端点:%1$s + 探测失败:%1$s + 复制 IP + 系统:%1$s + 版本:%1$s + 最后在线:%1$s + 离线 + 刚刚 + %1$d 分钟前 + %1$d 小时前 + %1$d 天前 + + + 模块与服务 + 设备信息 + 出口节点 + + + 需要 Root 权限 + Tailscale 控制器依赖 Root 权限(KernelSU / APatch / Magisk)来管理 Linux 内核原生网络隧道与后台守护服务。未检测到 Root 权限,请在授权管理器中授权后重新打开应用。 + 退出应用 + + + Tailscale Native Service + 已开启 + 已关闭 + 未安装 + 安装模块 + 删除模块 + + + 删除模块确认 + 确定要彻底删除 Tailscale KernelSU 模块吗?当前运行的后台网络隧道将被终止,系统终端软链接也将被移除。 + 确认删除 + + + 当前账号 + 未登录 + 点击登录账号 + 账号管理 + 添加另一个账号… + 管理控制台… + 退出登录 + 已切换账号至 %1$s + 退出登录确认 + 确定要退出当前已绑定的 Tailscale 账号吗?本地设备节点将解除授权。 + + + 登录 Tailscale + 请在浏览器中打开授权链接,完成 Tailscale 账号登录与设备绑定授权。 + 正在生成授权链接… + 在浏览器中打开 + 复制链接 + 授权链接已复制到剪贴板 + 账号登录授权成功! + + + Tailscale 服务 + 正在运行 + 已停止 + 正在启动服务… + 正在停止服务… + 模块未开启 + 状态未知 + + + 设备网络信息 + 设备名称 + Tailscale IP + 未连接 + IP 已复制到剪贴板 + 修改设备名称 + 修改设备名称 + 为当前设备设置新名称。名称仅可包含字母、数字和连字符(-)。 + 设备名称 + 设备名称已修改为 %1$s + 保存 + + + 版本:%1$s + + + 出口节点 + 无 + %1$s + 出口节点设置 + 无 + 暂无可用的出口节点 + 允许访问本地局域网 + 在使用出口节点时,依然可以访问当前 Wi-Fi 局域网内的设备 (如路由器后台、打印机)。 + 本机作为出口节点 + 允许 Tailnet 中的其他设备借用本机的网络上网(需在管理控制台批准审核)。 + 出口节点设置已生效 + + + 安装 Tailscale 模块 + 更新 Tailscale 模块 + 正在自动部署 Tailscale 原生守护核心、动态切网自愈服务,并注册全系统终端 CLI 软链接 (/data/adb/ksu/bin/tailscale)。 + 检测到应用内置了更高版本的 Tailscale 模块组件,是否立即进行同步更新? + 正在准备模块资源… + 正在解压模块文件… + 正在部署到系统模块目录… + 正在配置执行权限与全局软链接… + 模块安装与配置完成! + 操作失败:%1$s + 开始安装 + 取消 + 确定 + 完成 + 重试 + 返回 + 恢复默认名称 + 立即更新 + 不再显示 + 下载更新 + 检查更新 + 当前版本: %1$s → 新版本: %2$s + 当前模块 (%1$s) 已是最新版本 + 1. 同步最新原生 Tailscale 守护进程核心\n2. 优化开机自启与网络环境自愈机制\n3. 增强路由规则与防死锁策略 + + + 发现新版本 + 新版本 %1$s + Tailscale Manager 发布了新版本,建议立即更新以体验最新功能与修复。 + 版本:%1$s (%2$s) + 更新日志: + 正在检查更新… + 检查更新失败:%1$s + diff --git a/app/src/main/res/values/colors.xml b/app/src/main/res/values/colors.xml new file mode 100644 index 0000000..f8c6127 --- /dev/null +++ b/app/src/main/res/values/colors.xml @@ -0,0 +1,10 @@ + + + #FFBB86FC + #FF6200EE + #FF3700B3 + #FF03DAC5 + #FF018786 + #FF000000 + #FFFFFFFF + \ No newline at end of file diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml new file mode 100644 index 0000000..13c6596 --- /dev/null +++ b/app/src/main/res/values/strings.xml @@ -0,0 +1,192 @@ + + Tailscale Manager + Tailscale Manager + Refresh Status + + + Dashboard + Devices + Account + Settings + + + Language + App Language + System Default + 简体中文 (Simplified Chinese) + English + + Appearance + Theme Mode + System Default + Light + Dark + Dynamic Color + Use Android dynamic system colors (Material You), enabled by default + Theme Color + Disabled when dynamic color is enabled, default is Blue + Classic Blue (Default) + Elegant Purple + Nature Green + Vibrant Orange + Crimson Red + Slate Teal + + Preferences + Allow incoming connections + Allow other Tailnet machines to initiate connections to this device + Use Tailscale DNS settings + Accept DNS configurations and MagicDNS from admin panel + Use Tailscale subnets + Accept advertised subnet routes from other nodes + Automatically install updates + Automatically install newer component updates + Reset to defaults + Reset Preferences + Are you sure you want to reset Tailscale network preferences to defaults? + + About + Author: %1$s + Version + Check for Updates + Already up to date + + + All Devices + No devices found. Ensure Tailscale service is running. + This device + Exit Node + Ping + Pinging route and latency… + Direct + DERP Relay + Latency: %1$s + Endpoint: %1$s + Ping failed: %1$s + Copy IP + OS: %1$s + Version: %1$s + Last seen: %1$s + Offline + Just now + %1$d min ago + %1$d h ago + %1$d d ago + + + Module & Service + Device + Exit Node + + + Root Access Required + Tailscale Manager requires Root privileges (KernelSU / APatch / Magisk) to manage Linux network tunnels and system daemon services. Please grant root access and restart the app. + Exit + + + Tailscale Native Service + Enabled + Disabled + Not Installed + Install Module + Delete + + + Delete Module + Are you sure you want to delete the Tailscale KernelSU module? Active services will be stopped and system symlinks will be removed. + Delete + + + Account + Not Logged In + Tap to log in + Accounts + Add another account… + Admin console… + Log out + Switched account to %1$s + Log Out Confirmation + Are you sure you want to log out of the current Tailscale account? + + + Log in to Tailscale + Please open the authorization link in your browser to complete device authentication. + Generating login URL… + Open in Browser + Copy Link + Link copied to clipboard + Logged in successfully! + + + Tailscale Service + Running + Stopped + Starting service… + Stopping service… + Module Disabled + Unknown Status + + + Device Information + Device Name + Tailscale IP + Not Connected + IP copied to clipboard + Edit Device Name + Edit Device Name + Enter a new name for this device. Valid characters are letters, numbers, and hyphens. + Device Name + Device name updated to %1$s + Save + + + Version: %1$s + + + Exit Node + None + %1$s + Exit Nodes + None + No exit node available + Allow local network access + Access local network devices (printers, router web UI) while connected through an exit node. + Run as exit node + Allow other devices in your Tailnet to route their internet traffic through this device (approval in admin console required). + Exit node settings applied + + + Install Tailscale Module + Update Tailscale Module + Deploying native Tailscale daemon, route auto-healing scripts, and system-wide CLI symlinks (/data/adb/ksu/bin/tailscale). + A newer version of the native Tailscale module is available. Would you like to update it now? + Preparing module assets… + Extracting module files… + Deploying to KernelSU modules… + Configuring Linux permissions and symlinks… + Module installation completed! + Operation failed: %1$s + Start Install + Cancel + Confirm + Done + Retry + Back + Restore Default Name + Update Now + Don\'t show again + Download Update + Check for Updates + Installed: %1$s → Available: %2$s + Current module (%1$s) is already up to date + 1. Updated native Tailscale daemon core\n2. Optimized boot start & route auto-healing\n3. Enhanced proxy routing & stability + + + Update Available + New Version %1$s + A new version of Tailscale Manager is available. We recommend updating to get the latest features and improvements. + Version: %1$s (%2$s) + Changelog: + Checking for updates… + Update check failed: %1$s + diff --git a/app/src/main/res/values/themes.xml b/app/src/main/res/values/themes.xml new file mode 100644 index 0000000..e383c22 --- /dev/null +++ b/app/src/main/res/values/themes.xml @@ -0,0 +1,5 @@ + + + +