From 758a6e5f4be1438946cf6f139f223c00d3e0dba1 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 25 Oct 2022 00:09:07 +0200 Subject: [PATCH 01/36] Cargo init --- .github/ISSUE_TEMPLATE/bug_report.md | 30 - .github/ISSUE_TEMPLATE/feature_request.md | 20 - .github/dependabot.yml | 2 +- .github/workflows/codeql-analysis.yml | 70 -- .gitignore | 9 +- Cargo.lock | 7 + Cargo.toml | 9 + LICENSE | 948 +++++++--------------- README.md | 18 +- SECURITY.md | 11 +- cyrkensia.go | 123 --- go.mod | 20 - go.sum | 51 -- help.go | 42 - info.go | 28 - server/handles.go | 29 - server/hostinfo.go | 130 --- server/middleware.go | 22 - server/server.go | 101 --- src/main.rs | 3 + utils/config.go | 107 --- utils/filesystem.go | 44 - utils/printer.go | 7 - 23 files changed, 320 insertions(+), 1511 deletions(-) delete mode 100644 .github/ISSUE_TEMPLATE/bug_report.md delete mode 100644 .github/ISSUE_TEMPLATE/feature_request.md delete mode 100644 .github/workflows/codeql-analysis.yml create mode 100644 Cargo.lock create mode 100644 Cargo.toml delete mode 100644 cyrkensia.go delete mode 100644 go.mod delete mode 100644 go.sum delete mode 100644 help.go delete mode 100644 info.go delete mode 100644 server/handles.go delete mode 100644 server/hostinfo.go delete mode 100644 server/middleware.go delete mode 100644 server/server.go create mode 100644 src/main.rs delete mode 100644 utils/config.go delete mode 100644 utils/filesystem.go delete mode 100644 utils/printer.go diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 30ac063..0000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,30 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: "[BUG] Your issue here" -labels: bug -assignees: '' - ---- - -**Describe the bug** -A clear and concise description of what the bug is. - -**To Reproduce** -Steps to reproduce the behavior: -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - -**Expected behavior** -A clear and concise description of what you expected to happen. - -**Screenshots** -If applicable, add screenshots to help explain your problem. - -**System information:** -If your error seems platform relevant, then please also add information about your system (OS version and config, e.g. filesystem and network) as well as your build of Cyrkensia. - -**Additional context** -Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 42752dc..0000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project -title: '' -labels: enhancement -assignees: '' - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. It isn't required but would help inetgrating it faster and better. - -**Additional context** -Add any other context or screenshots about the feature request here. diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 1dc37e9..3843c25 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -5,7 +5,7 @@ version: 2 updates: - - package-ecosystem: "gomod" + - package-ecosystem: "cargo" directory: "/" schedule: interval: "daily" diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml deleted file mode 100644 index 79c37d9..0000000 --- a/.github/workflows/codeql-analysis.yml +++ /dev/null @@ -1,70 +0,0 @@ -# For most projects, this workflow file will not need changing; you simply need -# to commit it to your repository. -# -# You may wish to alter this file to override the set of languages analyzed, -# or to provide custom queries or build logic. -# -# ******** NOTE ******** -# We have attempted to detect the languages in your repository. Please check -# the `language` matrix defined below to confirm you have the correct set of -# supported CodeQL languages. -# -name: "CodeQL" - -on: - push: - branches: [ master ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ master ] - schedule: - - cron: '30 1 * * 4' - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - permissions: - actions: read - contents: read - security-events: write - - strategy: - fail-fast: false - matrix: - language: [ 'go' ] - # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] - # Learn more about CodeQL language support at https://git.io/codeql-language-support - - steps: - - name: Checkout repository - uses: actions/checkout@v2 - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v1 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - # queries: ./path/to/local/query, your-org/your-repo/queries@main - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v1 - - # ℹ️ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl - - # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language - - #- run: | - # make bootstrap - # make release - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 diff --git a/.gitignore b/.gitignore index 3fb0666..d7d92ec 100644 --- a/.gitignore +++ b/.gitignore @@ -1,7 +1,2 @@ -# Go -/build/ -/cyrkensia.exe -/cyrkensia - -# Test -test.json +# Cargo +/target/ \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..3dc628e --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "cyrkensia" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..2e67f24 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "cyrkensia" +version = "1.2.0" +edition = "2021" +license = "EUPL-1.2" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/LICENSE b/LICENSE index ada1a81..4153cd3 100644 --- a/LICENSE +++ b/LICENSE @@ -1,661 +1,287 @@ - GNU AFFERO GENERAL PUBLIC LICENSE - Version 3, 19 November 2007 - - Copyright (C) 2007 Free Software Foundation, Inc. - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - - The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are intended to guarantee your freedom to -share and change all versions of a program--to make sure it remains free -software for all its users. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -them if you wish), that you receive source code or can get it if you -want it, that you can change the software or use pieces of it in new -free programs, and that you know you can do these things. - - Developers that use our General Public Licenses protect your rights -with two steps: (1) assert copyright on the software, and (2) offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - - A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - - The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - - An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - - The precise terms and conditions for copying, distribution and -modification follow. - - TERMS AND CONDITIONS - - 0. Definitions. - - "This License" refers to version 3 of the GNU Affero General Public License. - - "Copyright" also means copyright-like laws that apply to other kinds of -works, such as semiconductor masks. - - "The Program" refers to any copyrightable work licensed under this -License. Each licensee is addressed as "you". "Licensees" and -"recipients" may be individuals or organizations. - - To "modify" a work means to copy from or adapt all or part of the work -in a fashion requiring copyright permission, other than the making of an -exact copy. The resulting work is called a "modified version" of the -earlier work or a work "based on" the earlier work. - - A "covered work" means either the unmodified Program or a work based -on the Program. - - To "propagate" a work means to do anything with it that, without -permission, would make you directly or secondarily liable for -infringement under applicable copyright law, except executing it on a -computer or modifying a private copy. Propagation includes copying, -distribution (with or without modification), making available to the -public, and in some countries other activities as well. - - To "convey" a work means any kind of propagation that enables other -parties to make or receive copies. Mere interaction with a user through -a computer network, with no transfer of a copy, is not conveying. - - An interactive user interface displays "Appropriate Legal Notices" -to the extent that it includes a convenient and prominently visible -feature that (1) displays an appropriate copyright notice, and (2) -tells the user that there is no warranty for the work (except to the -extent that warranties are provided), that licensees may convey the -work under this License, and how to view a copy of this License. If -the interface presents a list of user commands or options, such as a -menu, a prominent item in the list meets this criterion. - - 1. Source Code. - - The "source code" for a work means the preferred form of the work -for making modifications to it. "Object code" means any non-source -form of a work. - - A "Standard Interface" means an interface that either is an official -standard defined by a recognized standards body, or, in the case of -interfaces specified for a particular programming language, one that -is widely used among developers working in that language. - - The "System Libraries" of an executable work include anything, other -than the work as a whole, that (a) is included in the normal form of -packaging a Major Component, but which is not part of that Major -Component, and (b) serves only to enable use of the work with that -Major Component, or to implement a Standard Interface for which an -implementation is available to the public in source code form. A -"Major Component", in this context, means a major essential component -(kernel, window system, and so on) of the specific operating system -(if any) on which the executable work runs, or a compiler used to -produce the work, or an object code interpreter used to run it. - - The "Corresponding Source" for a work in object code form means all -the source code needed to generate, install, and (for an executable -work) run the object code and to modify the work, including scripts to -control those activities. However, it does not include the work's -System Libraries, or general-purpose tools or generally available free -programs which are used unmodified in performing those activities but -which are not part of the work. For example, Corresponding Source -includes interface definition files associated with source files for -the work, and the source code for shared libraries and dynamically -linked subprograms that the work is specifically designed to require, -such as by intimate data communication or control flow between those -subprograms and other parts of the work. - - The Corresponding Source need not include anything that users -can regenerate automatically from other parts of the Corresponding -Source. - - The Corresponding Source for a work in source code form is that -same work. - - 2. Basic Permissions. - - All rights granted under this License are granted for the term of -copyright on the Program, and are irrevocable provided the stated -conditions are met. This License explicitly affirms your unlimited -permission to run the unmodified Program. The output from running a -covered work is covered by this License only if the output, given its -content, constitutes a covered work. This License acknowledges your -rights of fair use or other equivalent, as provided by copyright law. - - You may make, run and propagate covered works that you do not -convey, without conditions so long as your license otherwise remains -in force. You may convey covered works to others for the sole purpose -of having them make modifications exclusively for you, or provide you -with facilities for running those works, provided that you comply with -the terms of this License in conveying all material for which you do -not control copyright. Those thus making or running the covered works -for you must do so exclusively on your behalf, under your direction -and control, on terms that prohibit them from making any copies of -your copyrighted material outside their relationship with you. - - Conveying under any other circumstances is permitted solely under -the conditions stated below. Sublicensing is not allowed; section 10 -makes it unnecessary. - - 3. Protecting Users' Legal Rights From Anti-Circumvention Law. - - No covered work shall be deemed part of an effective technological -measure under any applicable law fulfilling obligations under article -11 of the WIPO copyright treaty adopted on 20 December 1996, or -similar laws prohibiting or restricting circumvention of such -measures. - - When you convey a covered work, you waive any legal power to forbid -circumvention of technological measures to the extent such circumvention -is effected by exercising rights under this License with respect to -the covered work, and you disclaim any intention to limit operation or -modification of the work as a means of enforcing, against the work's -users, your or third parties' legal rights to forbid circumvention of -technological measures. - - 4. Conveying Verbatim Copies. - - You may convey verbatim copies of the Program's source code as you -receive it, in any medium, provided that you conspicuously and -appropriately publish on each copy an appropriate copyright notice; -keep intact all notices stating that this License and any -non-permissive terms added in accord with section 7 apply to the code; -keep intact all notices of the absence of any warranty; and give all -recipients a copy of this License along with the Program. - - You may charge any price or no price for each copy that you convey, -and you may offer support or warranty protection for a fee. - - 5. Conveying Modified Source Versions. - - You may convey a work based on the Program, or the modifications to -produce it from the Program, in the form of source code under the -terms of section 4, provided that you also meet all of these conditions: - - a) The work must carry prominent notices stating that you modified - it, and giving a relevant date. - - b) The work must carry prominent notices stating that it is - released under this License and any conditions added under section - 7. This requirement modifies the requirement in section 4 to - "keep intact all notices". - - c) You must license the entire work, as a whole, under this - License to anyone who comes into possession of a copy. This - License will therefore apply, along with any applicable section 7 - additional terms, to the whole of the work, and all its parts, - regardless of how they are packaged. This License gives no - permission to license the work in any other way, but it does not - invalidate such permission if you have separately received it. - - d) If the work has interactive user interfaces, each must display - Appropriate Legal Notices; however, if the Program has interactive - interfaces that do not display Appropriate Legal Notices, your - work need not make them do so. - - A compilation of a covered work with other separate and independent -works, which are not by their nature extensions of the covered work, -and which are not combined with it such as to form a larger program, -in or on a volume of a storage or distribution medium, is called an -"aggregate" if the compilation and its resulting copyright are not -used to limit the access or legal rights of the compilation's users -beyond what the individual works permit. Inclusion of a covered work -in an aggregate does not cause this License to apply to the other -parts of the aggregate. - - 6. Conveying Non-Source Forms. - - You may convey a covered work in object code form under the terms -of sections 4 and 5, provided that you also convey the -machine-readable Corresponding Source under the terms of this License, -in one of these ways: - - a) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by the - Corresponding Source fixed on a durable physical medium - customarily used for software interchange. - - b) Convey the object code in, or embodied in, a physical product - (including a physical distribution medium), accompanied by a - written offer, valid for at least three years and valid for as - long as you offer spare parts or customer support for that product - model, to give anyone who possesses the object code either (1) a - copy of the Corresponding Source for all the software in the - product that is covered by this License, on a durable physical - medium customarily used for software interchange, for a price no - more than your reasonable cost of physically performing this - conveying of source, or (2) access to copy the - Corresponding Source from a network server at no charge. - - c) Convey individual copies of the object code with a copy of the - written offer to provide the Corresponding Source. This - alternative is allowed only occasionally and noncommercially, and - only if you received the object code with such an offer, in accord - with subsection 6b. - - d) Convey the object code by offering access from a designated - place (gratis or for a charge), and offer equivalent access to the - Corresponding Source in the same way through the same place at no - further charge. You need not require recipients to copy the - Corresponding Source along with the object code. If the place to - copy the object code is a network server, the Corresponding Source - may be on a different server (operated by you or a third party) - that supports equivalent copying facilities, provided you maintain - clear directions next to the object code saying where to find the - Corresponding Source. Regardless of what server hosts the - Corresponding Source, you remain obligated to ensure that it is - available for as long as needed to satisfy these requirements. - - e) Convey the object code using peer-to-peer transmission, provided - you inform other peers where the object code and Corresponding - Source of the work are being offered to the general public at no - charge under subsection 6d. - - A separable portion of the object code, whose source code is excluded -from the Corresponding Source as a System Library, need not be -included in conveying the object code work. - - A "User Product" is either (1) a "consumer product", which means any -tangible personal property which is normally used for personal, family, -or household purposes, or (2) anything designed or sold for incorporation -into a dwelling. In determining whether a product is a consumer product, -doubtful cases shall be resolved in favor of coverage. For a particular -product received by a particular user, "normally used" refers to a -typical or common use of that class of product, regardless of the status -of the particular user or of the way in which the particular user -actually uses, or expects or is expected to use, the product. A product -is a consumer product regardless of whether the product has substantial -commercial, industrial or non-consumer uses, unless such uses represent -the only significant mode of use of the product. - - "Installation Information" for a User Product means any methods, -procedures, authorization keys, or other information required to install -and execute modified versions of a covered work in that User Product from -a modified version of its Corresponding Source. The information must -suffice to ensure that the continued functioning of the modified object -code is in no case prevented or interfered with solely because -modification has been made. - - If you convey an object code work under this section in, or with, or -specifically for use in, a User Product, and the conveying occurs as -part of a transaction in which the right of possession and use of the -User Product is transferred to the recipient in perpetuity or for a -fixed term (regardless of how the transaction is characterized), the -Corresponding Source conveyed under this section must be accompanied -by the Installation Information. But this requirement does not apply -if neither you nor any third party retains the ability to install -modified object code on the User Product (for example, the work has -been installed in ROM). - - The requirement to provide Installation Information does not include a -requirement to continue to provide support service, warranty, or updates -for a work that has been modified or installed by the recipient, or for -the User Product in which it has been modified or installed. Access to a -network may be denied when the modification itself materially and -adversely affects the operation of the network or violates the rules and -protocols for communication across the network. - - Corresponding Source conveyed, and Installation Information provided, -in accord with this section must be in a format that is publicly -documented (and with an implementation available to the public in -source code form), and must require no special password or key for -unpacking, reading or copying. - - 7. Additional Terms. - - "Additional permissions" are terms that supplement the terms of this -License by making exceptions from one or more of its conditions. -Additional permissions that are applicable to the entire Program shall -be treated as though they were included in this License, to the extent -that they are valid under applicable law. If additional permissions -apply only to part of the Program, that part may be used separately -under those permissions, but the entire Program remains governed by -this License without regard to the additional permissions. - - When you convey a copy of a covered work, you may at your option -remove any additional permissions from that copy, or from any part of -it. (Additional permissions may be written to require their own -removal in certain cases when you modify the work.) You may place -additional permissions on material, added by you to a covered work, -for which you have or can give appropriate copyright permission. - - Notwithstanding any other provision of this License, for material you -add to a covered work, you may (if authorized by the copyright holders of -that material) supplement the terms of this License with terms: - - a) Disclaiming warranty or limiting liability differently from the - terms of sections 15 and 16 of this License; or - - b) Requiring preservation of specified reasonable legal notices or - author attributions in that material or in the Appropriate Legal - Notices displayed by works containing it; or - - c) Prohibiting misrepresentation of the origin of that material, or - requiring that modified versions of such material be marked in - reasonable ways as different from the original version; or - - d) Limiting the use for publicity purposes of names of licensors or - authors of the material; or - - e) Declining to grant rights under trademark law for use of some - trade names, trademarks, or service marks; or - - f) Requiring indemnification of licensors and authors of that - material by anyone who conveys the material (or modified versions of - it) with contractual assumptions of liability to the recipient, for - any liability that these contractual assumptions directly impose on - those licensors and authors. - - All other non-permissive additional terms are considered "further -restrictions" within the meaning of section 10. If the Program as you -received it, or any part of it, contains a notice stating that it is -governed by this License along with a term that is a further -restriction, you may remove that term. If a license document contains -a further restriction but permits relicensing or conveying under this -License, you may add to a covered work material governed by the terms -of that license document, provided that the further restriction does -not survive such relicensing or conveying. - - If you add terms to a covered work in accord with this section, you -must place, in the relevant source files, a statement of the -additional terms that apply to those files, or a notice indicating -where to find the applicable terms. - - Additional terms, permissive or non-permissive, may be stated in the -form of a separately written license, or stated as exceptions; -the above requirements apply either way. - - 8. Termination. - - You may not propagate or modify a covered work except as expressly -provided under this License. Any attempt otherwise to propagate or -modify it is void, and will automatically terminate your rights under -this License (including any patent licenses granted under the third -paragraph of section 11). - - However, if you cease all violation of this License, then your -license from a particular copyright holder is reinstated (a) -provisionally, unless and until the copyright holder explicitly and -finally terminates your license, and (b) permanently, if the copyright -holder fails to notify you of the violation by some reasonable means -prior to 60 days after the cessation. - - Moreover, your license from a particular copyright holder is -reinstated permanently if the copyright holder notifies you of the -violation by some reasonable means, this is the first time you have -received notice of violation of this License (for any work) from that -copyright holder, and you cure the violation prior to 30 days after -your receipt of the notice. - - Termination of your rights under this section does not terminate the -licenses of parties who have received copies or rights from you under -this License. If your rights have been terminated and not permanently -reinstated, you do not qualify to receive new licenses for the same -material under section 10. - - 9. Acceptance Not Required for Having Copies. - - You are not required to accept this License in order to receive or -run a copy of the Program. Ancillary propagation of a covered work -occurring solely as a consequence of using peer-to-peer transmission -to receive a copy likewise does not require acceptance. However, -nothing other than this License grants you permission to propagate or -modify any covered work. These actions infringe copyright if you do -not accept this License. Therefore, by modifying or propagating a -covered work, you indicate your acceptance of this License to do so. - - 10. Automatic Licensing of Downstream Recipients. - - Each time you convey a covered work, the recipient automatically -receives a license from the original licensors, to run, modify and -propagate that work, subject to this License. You are not responsible -for enforcing compliance by third parties with this License. - - An "entity transaction" is a transaction transferring control of an -organization, or substantially all assets of one, or subdividing an -organization, or merging organizations. If propagation of a covered -work results from an entity transaction, each party to that -transaction who receives a copy of the work also receives whatever -licenses to the work the party's predecessor in interest had or could -give under the previous paragraph, plus a right to possession of the -Corresponding Source of the work from the predecessor in interest, if -the predecessor has it or can get it with reasonable efforts. - - You may not impose any further restrictions on the exercise of the -rights granted or affirmed under this License. For example, you may -not impose a license fee, royalty, or other charge for exercise of -rights granted under this License, and you may not initiate litigation -(including a cross-claim or counterclaim in a lawsuit) alleging that -any patent claim is infringed by making, using, selling, offering for -sale, or importing the Program or any portion of it. - - 11. Patents. - - A "contributor" is a copyright holder who authorizes use under this -License of the Program or a work on which the Program is based. The -work thus licensed is called the contributor's "contributor version". - - A contributor's "essential patent claims" are all patent claims -owned or controlled by the contributor, whether already acquired or -hereafter acquired, that would be infringed by some manner, permitted -by this License, of making, using, or selling its contributor version, -but do not include claims that would be infringed only as a -consequence of further modification of the contributor version. For -purposes of this definition, "control" includes the right to grant -patent sublicenses in a manner consistent with the requirements of -this License. - - Each contributor grants you a non-exclusive, worldwide, royalty-free -patent license under the contributor's essential patent claims, to -make, use, sell, offer for sale, import and otherwise run, modify and -propagate the contents of its contributor version. - - In the following three paragraphs, a "patent license" is any express -agreement or commitment, however denominated, not to enforce a patent -(such as an express permission to practice a patent or covenant not to -sue for patent infringement). To "grant" such a patent license to a -party means to make such an agreement or commitment not to enforce a -patent against the party. - - If you convey a covered work, knowingly relying on a patent license, -and the Corresponding Source of the work is not available for anyone -to copy, free of charge and under the terms of this License, through a -publicly available network server or other readily accessible means, -then you must either (1) cause the Corresponding Source to be so -available, or (2) arrange to deprive yourself of the benefit of the -patent license for this particular work, or (3) arrange, in a manner -consistent with the requirements of this License, to extend the patent -license to downstream recipients. "Knowingly relying" means you have -actual knowledge that, but for the patent license, your conveying the -covered work in a country, or your recipient's use of the covered work -in a country, would infringe one or more identifiable patents in that -country that you have reason to believe are valid. - - If, pursuant to or in connection with a single transaction or -arrangement, you convey, or propagate by procuring conveyance of, a -covered work, and grant a patent license to some of the parties -receiving the covered work authorizing them to use, propagate, modify -or convey a specific copy of the covered work, then the patent license -you grant is automatically extended to all recipients of the covered -work and works based on it. - - A patent license is "discriminatory" if it does not include within -the scope of its coverage, prohibits the exercise of, or is -conditioned on the non-exercise of one or more of the rights that are -specifically granted under this License. You may not convey a covered -work if you are a party to an arrangement with a third party that is -in the business of distributing software, under which you make payment -to the third party based on the extent of your activity of conveying -the work, and under which the third party grants, to any of the -parties who would receive the covered work from you, a discriminatory -patent license (a) in connection with copies of the covered work -conveyed by you (or copies made from those copies), or (b) primarily -for and in connection with specific products or compilations that -contain the covered work, unless you entered into that arrangement, -or that patent license was granted, prior to 28 March 2007. - - Nothing in this License shall be construed as excluding or limiting -any implied license or other defenses to infringement that may -otherwise be available to you under applicable patent law. - - 12. No Surrender of Others' Freedom. - - If conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot convey a -covered work so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you may -not convey it at all. For example, if you agree to terms that obligate you -to collect a royalty for further conveying from those to whom you convey -the Program, the only way you could satisfy both those terms and this -License would be to refrain entirely from conveying the Program. - - 13. Remote Network Interaction; Use with the GNU General Public License. - - Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - - Notwithstanding any other provision of this License, you have -permission to link or combine any covered work with a work licensed -under version 3 of the GNU General Public License into a single -combined work, and to convey the resulting work. The terms of this -License will continue to apply to the part which is the covered work, -but the work with which it is combined will remain governed by version -3 of the GNU General Public License. - - 14. Revised Versions of this License. - - The Free Software Foundation may publish revised and/or new versions of -the GNU Affero General Public License from time to time. Such new versions -will be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - - Each version is given a distinguishing version number. If the -Program specifies that a certain numbered version of the GNU Affero General -Public License "or any later version" applies to it, you have the -option of following the terms and conditions either of that numbered -version or of any later version published by the Free Software -Foundation. If the Program does not specify a version number of the -GNU Affero General Public License, you may choose any version ever published -by the Free Software Foundation. - - If the Program specifies that a proxy can decide which future -versions of the GNU Affero General Public License can be used, that proxy's -public statement of acceptance of a version permanently authorizes you -to choose that version for the Program. - - Later license versions may give you additional or different -permissions. However, no additional obligations are imposed on any -author or copyright holder as a result of your choosing to follow a -later version. - - 15. Disclaimer of Warranty. - - THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY -APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT -HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY -OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, -THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM -IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF -ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - - 16. Limitation of Liability. - - IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS -THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY -GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE -USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF -DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD -PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), -EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF -SUCH DAMAGES. - - 17. Interpretation of Sections 15 and 16. - - If the disclaimer of warranty and limitation of liability provided -above cannot be given local legal effect according to their terms, -reviewing courts shall apply local law that most closely approximates -an absolute waiver of all civil liability in connection with the -Program, unless a warranty or assumption of liability accompanies a -copy of the Program in return for a fee. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -state the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - - Copyright (C) - - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU Affero General Public License as published - by the Free Software Foundation, either version 3 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU Affero General Public License for more details. - - You should have received a copy of the GNU Affero General Public License - along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - - If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - - You should also get your employer (if you work as a programmer) or school, -if any, to sign a "copyright disclaimer" for the program, if necessary. -For more information on this, and how to apply and follow the GNU AGPL, see -. + EUROPEAN UNION PUBLIC LICENCE v. 1.2 + EUPL © the European Union 2007, 2016 + +This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined +below) which is provided under the terms of this Licence. Any use of the Work, +other than as authorised under this Licence is prohibited (to the extent such +use is covered by a right of the copyright holder of the Work). + +The Work is provided under the terms of this Licence when the Licensor (as +defined below) has placed the following notice immediately following the +copyright notice for the Work: + + Licensed under the EUPL + +or has expressed by any other means his willingness to license under the EUPL. + +1. Definitions + +In this Licence, the following terms have the following meaning: + +- ‘The Licence’: this Licence. + +- ‘The Original Work’: the work or software distributed or communicated by the + Licensor under this Licence, available as Source Code and also as Executable + Code as the case may be. + +- ‘Derivative Works’: the works or software that could be created by the + Licensee, based upon the Original Work or modifications thereof. This Licence + does not define the extent of modification or dependence on the Original Work + required in order to classify a work as a Derivative Work; this extent is + determined by copyright law applicable in the country mentioned in Article 15. + +- ‘The Work’: the Original Work or its Derivative Works. + +- ‘The Source Code’: the human-readable form of the Work which is the most + convenient for people to study and modify. + +- ‘The Executable Code’: any code which has generally been compiled and which is + meant to be interpreted by a computer as a program. + +- ‘The Licensor’: the natural or legal person that distributes or communicates + the Work under the Licence. + +- ‘Contributor(s)’: any natural or legal person who modifies the Work under the + Licence, or otherwise contributes to the creation of a Derivative Work. + +- ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of + the Work under the terms of the Licence. + +- ‘Distribution’ or ‘Communication’: any act of selling, giving, lending, + renting, distributing, communicating, transmitting, or otherwise making + available, online or offline, copies of the Work or providing access to its + essential functionalities at the disposal of any other natural or legal + person. + +2. Scope of the rights granted by the Licence + +The Licensor hereby grants You a worldwide, royalty-free, non-exclusive, +sublicensable licence to do the following, for the duration of copyright vested +in the Original Work: + +- use the Work in any circumstance and for all usage, +- reproduce the Work, +- modify the Work, and make Derivative Works based upon the Work, +- communicate to the public, including the right to make available or display + the Work or copies thereof to the public and perform publicly, as the case may + be, the Work, +- distribute the Work or copies thereof, +- lend and rent the Work or copies thereof, +- sublicense rights in the Work or copies thereof. + +Those rights can be exercised on any media, supports and formats, whether now +known or later invented, as far as the applicable law permits so. + +In the countries where moral rights apply, the Licensor waives his right to +exercise his moral right to the extent allowed by law in order to make effective +the licence of the economic rights here above listed. + +The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to +any patents held by the Licensor, to the extent necessary to make use of the +rights granted on the Work under this Licence. + +3. Communication of the Source Code + +The Licensor may provide the Work either in its Source Code form, or as +Executable Code. If the Work is provided as Executable Code, the Licensor +provides in addition a machine-readable copy of the Source Code of the Work +along with each copy of the Work that the Licensor distributes or indicates, in +a notice following the copyright notice attached to the Work, a repository where +the Source Code is easily and freely accessible for as long as the Licensor +continues to distribute or communicate the Work. + +4. Limitations on copyright + +Nothing in this Licence is intended to deprive the Licensee of the benefits from +any exception or limitation to the exclusive rights of the rights owners in the +Work, of the exhaustion of those rights or of other applicable limitations +thereto. + +5. Obligations of the Licensee + +The grant of the rights mentioned above is subject to some restrictions and +obligations imposed on the Licensee. Those obligations are the following: + +Attribution right: The Licensee shall keep intact all copyright, patent or +trademarks notices and all notices that refer to the Licence and to the +disclaimer of warranties. The Licensee must include a copy of such notices and a +copy of the Licence with every copy of the Work he/she distributes or +communicates. The Licensee must cause any Derivative Work to carry prominent +notices stating that the Work has been modified and the date of modification. + +Copyleft clause: If the Licensee distributes or communicates copies of the +Original Works or Derivative Works, this Distribution or Communication will be +done under the terms of this Licence or of a later version of this Licence +unless the Original Work is expressly distributed only under this version of the +Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee +(becoming Licensor) cannot offer or impose any additional terms or conditions on +the Work or Derivative Work that alter or restrict the terms of the Licence. + +Compatibility clause: If the Licensee Distributes or Communicates Derivative +Works or copies thereof based upon both the Work and another work licensed under +a Compatible Licence, this Distribution or Communication can be done under the +terms of this Compatible Licence. For the sake of this clause, ‘Compatible +Licence’ refers to the licences listed in the appendix attached to this Licence. +Should the Licensee's obligations under the Compatible Licence conflict with +his/her obligations under this Licence, the obligations of the Compatible +Licence shall prevail. + +Provision of Source Code: When distributing or communicating copies of the Work, +the Licensee will provide a machine-readable copy of the Source Code or indicate +a repository where this Source will be easily and freely available for as long +as the Licensee continues to distribute or communicate the Work. + +Legal Protection: This Licence does not grant permission to use the trade names, +trademarks, service marks, or names of the Licensor, except as required for +reasonable and customary use in describing the origin of the Work and +reproducing the content of the copyright notice. + +6. Chain of Authorship + +The original Licensor warrants that the copyright in the Original Work granted +hereunder is owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each Contributor warrants that the copyright in the modifications he/she brings +to the Work are owned by him/her or licensed to him/her and that he/she has the +power and authority to grant the Licence. + +Each time You accept the Licence, the original Licensor and subsequent +Contributors grant You a licence to their contributions to the Work, under the +terms of this Licence. + +7. Disclaimer of Warranty + +The Work is a work in progress, which is continuously improved by numerous +Contributors. It is not a finished work and may therefore contain defects or +‘bugs’ inherent to this type of development. + +For the above reason, the Work is provided under the Licence on an ‘as is’ basis +and without warranties of any kind concerning the Work, including without +limitation merchantability, fitness for a particular purpose, absence of defects +or errors, accuracy, non-infringement of intellectual property rights other than +copyright as stated in Article 6 of this Licence. + +This disclaimer of warranty is an essential part of the Licence and a condition +for the grant of any rights to the Work. + +8. Disclaimer of Liability + +Except in the cases of wilful misconduct or damages directly caused to natural +persons, the Licensor will in no event be liable for any direct or indirect, +material or moral, damages of any kind, arising out of the Licence or of the use +of the Work, including without limitation, damages for loss of goodwill, work +stoppage, computer failure or malfunction, loss of data or any commercial +damage, even if the Licensor has been advised of the possibility of such damage. +However, the Licensor will be liable under statutory product liability laws as +far such laws apply to the Work. + +9. Additional agreements + +While distributing the Work, You may choose to conclude an additional agreement, +defining obligations or services consistent with this Licence. However, if +accepting obligations, You may act only on your own behalf and on your sole +responsibility, not on behalf of the original Licensor or any other Contributor, +and only if You agree to indemnify, defend, and hold each Contributor harmless +for any liability incurred by, or claims asserted against such Contributor by +the fact You have accepted any warranty or additional liability. + +10. Acceptance of the Licence + +The provisions of this Licence can be accepted by clicking on an icon ‘I agree’ +placed under the bottom of a window displaying the text of this Licence or by +affirming consent in any other similar way, in accordance with the rules of +applicable law. Clicking on that icon indicates your clear and irrevocable +acceptance of this Licence and all of its terms and conditions. + +Similarly, you irrevocably accept this Licence and all of its terms and +conditions by exercising any rights granted to You by Article 2 of this Licence, +such as the use of the Work, the creation by You of a Derivative Work or the +Distribution or Communication by You of the Work or copies thereof. + +11. Information to the public + +In case of any Distribution or Communication of the Work by means of electronic +communication by You (for example, by offering to download the Work from a +remote location) the distribution channel or media (for example, a website) must +at least provide to the public the information requested by the applicable law +regarding the Licensor, the Licence and the way it may be accessible, concluded, +stored and reproduced by the Licensee. + +12. Termination of the Licence + +The Licence and the rights granted hereunder will terminate automatically upon +any breach by the Licensee of the terms of the Licence. + +Such a termination will not terminate the licences of any person who has +received the Work from the Licensee under the Licence, provided such persons +remain in full compliance with the Licence. + +13. Miscellaneous + +Without prejudice of Article 9 above, the Licence represents the complete +agreement between the Parties as to the Work. + +If any provision of the Licence is invalid or unenforceable under applicable +law, this will not affect the validity or enforceability of the Licence as a +whole. Such provision will be construed or reformed so as necessary to make it +valid and enforceable. + +The European Commission may publish other linguistic versions or new versions of +this Licence or updated versions of the Appendix, so far this is required and +reasonable, without reducing the scope of the rights granted by the Licence. New +versions of the Licence will be published with a unique version number. + +All linguistic versions of this Licence, approved by the European Commission, +have identical value. Parties can take advantage of the linguistic version of +their choice. + +14. Jurisdiction + +Without prejudice to specific agreement between parties, + +- any litigation resulting from the interpretation of this License, arising + between the European Union institutions, bodies, offices or agencies, as a + Licensor, and any Licensee, will be subject to the jurisdiction of the Court + of Justice of the European Union, as laid down in article 272 of the Treaty on + the Functioning of the European Union, + +- any litigation arising between other parties and resulting from the + interpretation of this License, will be subject to the exclusive jurisdiction + of the competent court where the Licensor resides or conducts its primary + business. + +15. Applicable Law + +Without prejudice to specific agreement between parties, + +- this Licence shall be governed by the law of the European Union Member State + where the Licensor has his seat, resides or has his registered office, + +- this licence shall be governed by Belgian law if the Licensor has no seat, + residence or registered office inside a European Union Member State. + +Appendix + +‘Compatible Licences’ according to Article 5 EUPL are: + +- GNU General Public License (GPL) v. 2, v. 3 +- GNU Affero General Public License (AGPL) v. 3 +- Open Software License (OSL) v. 2.1, v. 3.0 +- Eclipse Public License (EPL) v. 1.0 +- CeCILL v. 2.0, v. 2.1 +- Mozilla Public Licence (MPL) v. 2 +- GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3 +- Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for + works other than software +- European Union Public Licence (EUPL) v. 1.1, v. 1.2 +- Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong + Reciprocity (LiLiQ-R+). + +The European Commission may update this Appendix to later versions of the above +licences without producing a new version of the EUPL, as long as they provide +the rights granted in Article 2 of this Licence and protect the covered Source +Code from exclusive appropriation. + +All other changes or additions to this Appendix require the production of a new +EUPL version. diff --git a/README.md b/README.md index 0a7df6a..0548752 100644 --- a/README.md +++ b/README.md @@ -1,16 +1,10 @@ # Cyrkensia Server for [Azura](https://github.com/Stridsvagn69420/Azura) and [Shigure](https://github.com/Stridsvagn69420/Shigure) music repositories -# Features -* ✅ Simple cloud hosting for your music files -* 💻 Available everywhere where [Go](https://go.dev/) compiles -* 🔒 Direct support for SSL/TLS and HTTP-Authentication -* 🚀 Blazingly fast thanks to the [Fiber](https://github.com/gofiber/fiber)-Framework and Go's performant architecture + -# Installation, Usage, Configuration and RPC-Assets -You can find every info, from installing Cyrkensia to just looking at available RPC-Assets, in the Wiki: -* [File Structure](https://github.com/Stridsvagn69420/Cyrkensia/wiki/File-Structure) -* [Rich Presence Assets](https://github.com/Stridsvagn69420/Cyrkensia/wiki/RPC-Assets) -* [Access Control](https://github.com/Stridsvagn69420/Cyrkensia/wiki/Access-Control) -* [Installation](https://github.com/Stridsvagn69420/Cyrkensia/wiki/Installation) -* [Usage](https://github.com/Stridsvagn69420/Cyrkensia/wiki/Usage) +# Installation +WIP. + +# Usage +WIP. \ No newline at end of file diff --git a/SECURITY.md b/SECURITY.md index e8bb74f..de87f9b 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -1,9 +1,8 @@ # Security Policy -## Supported Versions -| Version | Supported | -| ------- | ------------------ | -| 1.0.0 | :white_check_mark: | +## Supported Version +As of the major transition from v1.1.5 to v1.2.0, the Go versions are abandoned and thus not supported, since the codebase got rewritten in Rust. +Only the latest stable/released version is supported! These versions can be found on [GitHub](https://github.com/Stridsvagn69420/Cyrkensia/releases) and [crates.io](https://crates.io/crates/cyrkensia). +Custom modified builds or nightly builds are not supported! Despite this, if the significant code is the same as in a custom *stable* build, the issue will be dealt with. ## Reporting a Vulnerability -Since I don't expect any big vulnerability in the Cyrkensia code itself but rather it's dependencies, any issue can be reported in GitHub's issue tab. Pull Request (e.g. by Dependabot) will be accepted immediately when it's fixing a big security vulnerability in a dependency. -Despite it, only the current Minor version with it's Patch versions is supported, like 1.0.* (e.g. 1.0.0, 1.0.1, 1.0.2, ...). +Since I don't expect any big vulnerability in the Cyrkensia code itself but rather it's dependencies, any issue can be reported in GitHub's issue tab. Pull Request (e.g. by Dependabot) will be accepted immediately when it's fixing a big security vulnerability in a dependency. \ No newline at end of file diff --git a/cyrkensia.go b/cyrkensia.go deleted file mode 100644 index 5817adb..0000000 --- a/cyrkensia.go +++ /dev/null @@ -1,123 +0,0 @@ -package main - -import ( - "flag" - "os" - "path/filepath" - "strconv" - - "github.com/Stridsvagn69420/Cyrkensia/server" - "github.com/Stridsvagn69420/Cyrkensia/utils" - "github.com/Stridsvagn69420/pringo" - - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/cors" - "github.com/gofiber/fiber/v2/middleware/logger" -) - -const BindDesc string = "IP address to bind to" -const PortDesc string = "Port to listen on" -const FilesDesc string = "Folder holding all the audio files" -const NameDesc string = "Name to represent the server" -const IconDesc string = "Icon key to represent the server" -const UuidDesc string = "UUIDv4 of the server" -const HtpasswdDesc string = "Path to htpasswd file for password protection" -const PemDesc string = "Path to the PEM file. Only needed for HTTPS." -const KeyDesc string = "Path to the KEY file. Only needed for HTTPS." -const ConfigDesc string = "Config file location" - -var cfgpath string = filepath.Join(utils.GetHomeDir(), ".config/cyrkensia/config.json") - -const BindName string = "Bind" -const PortName string = "Port" -const FilesName string = "Files" -const NameName string = "Name" -const IconName string = "Icon" -const UuidName string = "Uuid" -const HtpasswdName string = "Htpasswd" -const PemName string = "Pem" -const KeyName string = "Key" -const ConfigName string = "Config" - -func main() { - // Load default config - utils.LoadConfig(cfgpath) - - // Info and Help message - if len(os.Args) > 1 { - switch os.Args[1] { - case "info", "version", "-V", "--version": - InfoMessage() - os.Exit(0) - - case "help", "-h", "--help": - HelpMessage() - os.Exit(0) - } - } - - // ------ Flags ------ - configPath := flag.String("Config", cfgpath, ConfigDesc) - // Listening address and port and file directory - flag.StringVar(&utils.Config.BindAddr, BindName, utils.Config.BindAddr, BindDesc) - flag.IntVar(&utils.Config.Port, PortName, utils.Config.Port, PortDesc) - flag.StringVar(&utils.Config.CDNpath, FilesName, utils.Config.CDNpath, FilesDesc) - // Appearance and UUID - flag.StringVar(&utils.Config.Name, NameName, utils.Config.Name, NameDesc) - flag.StringVar(&utils.Config.Icon, IconName, utils.Config.Icon, IconDesc) - flag.StringVar(&utils.Config.Uuid, UuidName, utils.Config.Uuid, UuidDesc) - // User access and HTTPS - flag.StringVar(&utils.Config.Access, HtpasswdName, utils.Config.Access, HtpasswdDesc) - flag.StringVar(&utils.Config.Pem, PemName, utils.Config.Pem, PemDesc) - flag.StringVar(&utils.Config.Key, KeyName, utils.Config.Key, KeyDesc) - - // Parse flags and load config - flag.Parse() - utils.LoadConfig(*configPath) - - // ------ Server ------ - // Initialize server - if utils.Config.Locked { - if err := server.InitHtpasswdAuth(utils.Config.Access); err != nil { - utils.Prnt.Println("An error occured while initializing HTTP-Basic Auth!", pringo.Red) - utils.Prnt.Println("WARNING: Server will shut down!", pringo.Yellow) - os.Exit(1) - } - } - app := fiber.New() - // Middleware - app.Use(logger.New(logger.Config{ - Format: "[${ip}]:${port} ${status} - ${method} ${path}\n", - TimeZone: "UTC", - TimeFormat: "2006-01-02 15:04:05", - })) - app.Use(cors.New(cors.Config{ - AllowOrigins: "*", - AllowHeaders: "Origin, Content-Type, Accept, DNT, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Range, Content-Length, Accept-Language, Accept-Encoding, Connection, Access-Control-Allow-Origin", - AllowCredentials: true, - AllowMethods: "GET, HEAD, OPTIONS", - ExposeHeaders: "Content-Length, Content-Range", - })) - app.Use(server.AgplHeaders) - app.Use(server.ServerHeader) - - // Routes - app.Get("/", server.HostinfoEndpoint) - app.Get("/:route", server.RouteEndpoint) - if utils.Config.Locked { - app.Get("/:directory/:file", server.FileServerLocked) - } else { - app.Get("/:directory/:file", server.FileServer) - } - - // Start - if utils.Config.Key != "" && utils.Config.Pem != "" && utils.FileExists(utils.Config.Key) && utils.FileExists(utils.Config.Pem) { - app.ListenTLS( - utils.Config.BindAddr+":"+strconv.Itoa(utils.Config.Port), - utils.Config.Pem, - utils.Config.Key, - ) - } else { - app.Listen(utils.Config.BindAddr + ":" + strconv.Itoa(utils.Config.Port)) - } -} diff --git a/go.mod b/go.mod deleted file mode 100644 index 8d91e9d..0000000 --- a/go.mod +++ /dev/null @@ -1,20 +0,0 @@ -module github.com/Stridsvagn69420/Cyrkensia - -go 1.17 - -require ( - github.com/Stridsvagn69420/pringo v0.9.1 - github.com/gofiber/fiber/v2 v2.38.1 - github.com/tg123/go-htpasswd v1.2.0 -) - -require ( - github.com/GehirnInc/crypt v0.0.0-20200316065508-bb7000b8a962 // indirect - github.com/andybalholm/brotli v1.0.4 // indirect - github.com/klauspost/compress v1.15.0 // indirect - github.com/valyala/bytebufferpool v1.0.0 // indirect - github.com/valyala/fasthttp v1.40.0 // indirect - github.com/valyala/tcplisten v1.0.0 // indirect - golang.org/x/crypto v0.0.0-20220214200702-86341886e292 // indirect - golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 // indirect -) diff --git a/go.sum b/go.sum deleted file mode 100644 index 1dc404c..0000000 --- a/go.sum +++ /dev/null @@ -1,51 +0,0 @@ -github.com/GehirnInc/crypt v0.0.0-20200316065508-bb7000b8a962 h1:KeNholpO2xKjgaaSyd+DyQRrsQjhbSeS7qe4nEw8aQw= -github.com/GehirnInc/crypt v0.0.0-20200316065508-bb7000b8a962/go.mod h1:kC29dT1vFpj7py2OvG1khBdQpo3kInWP+6QipLbdngo= -github.com/Stridsvagn69420/Cyrkensia/go/src v0.0.0-20220830220806-454d5777eee6 h1:cnvFeqD0UAVTAMtATtetixV0Ym+0oECA+NaPXAXzNQo= -github.com/Stridsvagn69420/Cyrkensia/go/src v0.0.0-20220830220806-454d5777eee6/go.mod h1:VxVPsFrKwkBOIxtoT122DLVM4UzBpD9vzerRUkWwFAc= -github.com/Stridsvagn69420/pringo v0.9.1 h1:R12yIwBQ+0G5tSgUoNittptYW2hQKodbjvZyK2kUgRs= -github.com/Stridsvagn69420/pringo v0.9.1/go.mod h1:zBTFaDFeRX7WZP5SnI43+Yo5U396YELfoHnqKhxNkFA= -github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY= -github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= -github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/gofiber/fiber/v2 v2.37.0 h1:KVboSQ7e0wDbSFXNjXKqoigwp9HYUqgWn4uGFaUO1P8= -github.com/gofiber/fiber/v2 v2.37.0/go.mod h1:xm3pDGlfE1xqVKb77iH8weLU0FFoTeWeK3nbiYM2Nh0= -github.com/gofiber/fiber/v2 v2.38.1 h1:GEQ/Yt3Wsf2a30iTqtLXlBYJZso0JXPovt/tmj5H9jU= -github.com/gofiber/fiber/v2 v2.38.1/go.mod h1:t0NlbaXzuGH7I+7M4paE848fNWInZ7mfxI/Er1fTth8= -github.com/klauspost/compress v1.15.0 h1:xqfchp4whNFxn5A4XFyyYtitiWI8Hy5EW59jEwcyL6U= -github.com/klauspost/compress v1.15.0/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/tg123/go-htpasswd v1.2.0 h1:UKp34m9H467/xklxUxU15wKRru7fwXoTojtxg25ITF0= -github.com/tg123/go-htpasswd v1.2.0/go.mod h1:h7IzlfpvIWnVJhNZ0nQ9HaFxHb7pn5uFJYLlEUJa2sM= -github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= -github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= -github.com/valyala/fasthttp v1.39.0 h1:lW8mGeM7yydOqZKmwyMTaz/PH/A+CLgtmmcjv+OORfU= -github.com/valyala/fasthttp v1.39.0/go.mod h1:t/G+3rLek+CyY9bnIE+YlMRddxVAAGjhxndDB4i4C0I= -github.com/valyala/fasthttp v1.40.0 h1:CRq/00MfruPGFLTQKY8b+8SfdK60TxNztjRMnH0t1Yc= -github.com/valyala/fasthttp v1.40.0/go.mod h1:t/G+3rLek+CyY9bnIE+YlMRddxVAAGjhxndDB4i4C0I= -github.com/valyala/tcplisten v1.0.0 h1:rBHj/Xf+E1tRGZyWIWwJDiRY0zc1Js+CV5DqwacVSA8= -github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= -golang.org/x/crypto v0.0.0-20190228161510-8dd112bcdc25/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20220214200702-86341886e292 h1:f+lwQ+GtmgoY+A2YaQxlSOnDjXcQ7ZRLWOHbC6HtRqE= -golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= -golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 h1:nhht2DYV/Sn3qOayu8lM+cU1ii9sTLUeBQwQQfUHtrs= -golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/help.go b/help.go deleted file mode 100644 index 0dc5665..0000000 --- a/help.go +++ /dev/null @@ -1,42 +0,0 @@ -package main - -import ( - "fmt" - - "github.com/Stridsvagn69420/Cyrkensia/server" - "github.com/Stridsvagn69420/Cyrkensia/utils" - "github.com/Stridsvagn69420/pringo" -) - -func HelpMessage() { - utils.Prnt.Println("USAGE: cyrkensia [FLAGS]", color1) - - help(ConfigName, ConfigDesc, cfgpath) - help(BindName, BindDesc, utils.Config.BindAddr) - help(FilesName, FilesDesc, utils.Config.CDNpath) - help(PortName, PortDesc, fmt.Sprint(utils.Config.Port)) - help(HtpasswdName, HtpasswdDesc, utils.Config.Access) - help(UuidName, UuidDesc, utils.Config.Uuid) - help(IconName, IconDesc, utils.Config.Icon) - help(NameName, NameDesc, utils.Config.Name) - help(PemName, PemDesc, utils.Config.Pem) - help(KeyName, KeyDesc, utils.Config.Key) - - utils.Prnt.Print("See ", pringo.Blue) - utils.Prnt.Print("cyrkensia info", pringo.BlueBright) - utils.Prnt.Print(" or ", pringo.Blue) - utils.Prnt.Print(server.SourceCode, pringo.BlueBright) - utils.Prnt.Println(" for more!", pringo.Blue) -} - -func help(x string, y string, z string) { - utils.Prnt.Print("-"+x+": ", color2) - utils.Prnt.Writeln(y) - utils.Prnt.Print("Default: ", pringo.Blue) - if z != "" { - utils.Prnt.Writeln(z) - } else { - utils.Prnt.Writeln("None") - } - utils.Prnt.Writeln("") -} diff --git a/info.go b/info.go deleted file mode 100644 index 536cace..0000000 --- a/info.go +++ /dev/null @@ -1,28 +0,0 @@ -package main - -import ( - "runtime" - - "github.com/Stridsvagn69420/Cyrkensia/server" - "github.com/Stridsvagn69420/Cyrkensia/utils" - "github.com/Stridsvagn69420/pringo" -) - -// Printer -var color1 pringo.Color = pringo.MagentaBright -var color2 pringo.Color = pringo.Magenta - -func InfoMessage() { - utils.Prnt.Println("Cyrkensia - Server for Azura and Shigure music repositories", color1) - info("Repository", server.SourceCode) - info("License", server.License) - info("Version", server.AppVersion) - info("OS", runtime.GOOS) - info("Arch", runtime.GOARCH) - info("Go", runtime.Version()) -} - -func info(x string, y string) { - utils.Prnt.Print(x+": ", color2) - utils.Prnt.Writeln(y) -} diff --git a/server/handles.go b/server/handles.go deleted file mode 100644 index 95acfaa..0000000 --- a/server/handles.go +++ /dev/null @@ -1,29 +0,0 @@ -package server - -import ( - "github.com/Stridsvagn69420/Cyrkensia/utils" - "github.com/Stridsvagn69420/pringo" - - "github.com/gofiber/fiber/v2" -) - -func ServerError500(c *fiber.Ctx, err error) error { - if err != nil { - utils.Prnt.Errorln(err.Error(), pringo.Red) - return c.Status(fiber.StatusInternalServerError).SendString("Internal Server Error") - } - return nil -} - -func AuthError401(c *fiber.Ctx) error { - c.Set("WWW-Authenticate", "Basic realm=Cyrkensia") - return c.Status(fiber.StatusUnauthorized).SendString("Unauthorized") -} - -func ServeError404(c *fiber.Ctx) error { - return c.Status(fiber.StatusNotFound).SendString("Not Found") -} - -func Forbidden403(c *fiber.Ctx) error { - return c.Status(fiber.StatusForbidden).SendString("Forbidden") -} diff --git a/server/hostinfo.go b/server/hostinfo.go deleted file mode 100644 index ed6e080..0000000 --- a/server/hostinfo.go +++ /dev/null @@ -1,130 +0,0 @@ -package server - -import ( - "encoding/json" - "io/fs" - "os" - "path" - "strconv" - - "github.com/Stridsvagn69420/Cyrkensia/utils" - - "github.com/gofiber/fiber/v2" -) - -type metadata struct { - Name string `json:"name"` - Cover string `json:"cover"` - Authors []utils.Author `json:"authors"` -} - -func HostinfoEndpoint(c *fiber.Ctx) error { - // Generate hostinfo - hostinfo := utils.Hostinfo{ - Name: utils.Config.Name, - Hosticon: utils.Config.Icon, - Uuid: utils.Config.Uuid, - Secured: utils.Config.Locked, - Root: "", - OriginURI: c.Protocol() + "://" + c.Hostname() + c.Path(), - Owners: utils.Config.Owners, - } - - // Append dynamic fields - hostinfo.Albums, hostinfo.Size = readAlbums(c, utils.Config.CDNpath) - - // Convert to JSON - json, err := json.Marshal(hostinfo) - ServerError500(c, err) - // Set Headers - c.Append("Content-Type", fiber.MIMEApplicationJSON) - c.Append("Content-Length", strconv.Itoa(len(json))) - - // Send JSON response - return c.Status(fiber.StatusOK).Send(json) -} - -// Hostinfo specific IO functions for reading out available songs and albums -func readAlbums(c *fiber.Ctx, pathdir string) ([]utils.Album, int) { - // Read files - files, err := os.ReadDir(pathdir) - if err != nil { - ServerError500(c, err) - } - - // Vars - size := 0 - var albums []utils.Album - - // Read directories - for _, file := range files { - if file.IsDir() { - albumpath := path.Join(pathdir, file.Name()) - // Extract metadata - if _, finderr := os.Stat(path.Join(albumpath, ".metadata.json")); finderr == nil { - meta := readMetadata(c, albumpath) - album := utils.Album{ - Name: meta.Name, - Dir: file.Name(), - Cover: meta.Cover, - Files: readFiles(c, albumpath, &size), - Authors: meta.Authors, - } - albums = append(albums, album) - } - } - } - if len(albums) == 0 { - albums = make([]utils.Album, 0) - } - - // Return albums and size - return albums, size -} - -func readMetadata(c *fiber.Ctx, dirpath string) metadata { - var metadata metadata - // Read metadata - file, err := os.ReadFile(path.Join(dirpath, ".metadata.json")) - if err != nil { - ServerError500(c, err) - } - - // Parse JSON - err = json.Unmarshal(file, &metadata) - if err != nil { - ServerError500(c, err) - } - - // Retunr metadata - return metadata -} - -func readFiles(c *fiber.Ctx, dirpath string, size *int) []string { - // Read files - entries, err := os.ReadDir(dirpath) - if err != nil { - ServerError500(c, err) - } - // Get file info - files := make([]fs.FileInfo, 0, len(entries)) - for _, entry := range entries { - info, err := entry.Info() - if err != nil { - ServerError500(c, err) - } - files = append(files, info) - } - - // Parse metadata - musicfiles := make([]string, len(files)-1) - for i, file := range files { - if !file.IsDir() && file.Name() != ".metadata.json" { - *size += int(file.Size()) - musicfiles[i-1] = file.Name() - } - } - - // Return music files - return musicfiles -} diff --git a/server/middleware.go b/server/middleware.go deleted file mode 100644 index e2836d4..0000000 --- a/server/middleware.go +++ /dev/null @@ -1,22 +0,0 @@ -package server - -import ( - "github.com/gofiber/fiber/v2" -) - -func AgplHeaders(c *fiber.Ctx) error { - c.Set("X-License", License) - c.Set("X-License-URL", "https://www.gnu.org/licenses/agpl-3.0.html") - c.Set("X-Source-Code", SourceCode) - return c.Next() -} - -func ServerHeader(c *fiber.Ctx) error { - c.Set("Server", "Cyrkensia/"+AppVersion+" Fiber/"+fiber.Version) - c.Set("Access-Control-Allow-Private-Network", "true") - return c.Next() -} - -var AppVersion string = "1.2.0" -var SourceCode string = "https://github.com/Stridsvagn69420/Cyrkensia" -var License string = "AGPL-3.0" diff --git a/server/server.go b/server/server.go deleted file mode 100644 index ca8b3c9..0000000 --- a/server/server.go +++ /dev/null @@ -1,101 +0,0 @@ -package server - -import ( - "github.com/Stridsvagn69420/Cyrkensia/utils" - - "encoding/base64" - "net/url" - "path/filepath" - "strings" - - "github.com/gofiber/fiber/v2" - "github.com/tg123/go-htpasswd" -) - -func FileServer(c *fiber.Ctx) error { - // Get directory - directory, err := url.QueryUnescape(c.Params("directory")) - if err != nil { - return ServerError500(c, err) - } - - // Get filename - file, err := url.QueryUnescape(c.Params("file")) - if err != nil { - return ServerError500(c, err) - } - - // Create filepath - filePath := filepath.Join(utils.Config.CDNpath, directory, file) - - // Send file if it exists - return sendIfExists(c, filePath) -} - -func FileServerLocked(c *fiber.Ctx) error { - // Check Authorization header - userpass := c.GetReqHeaders()["Authorization"] - if userpass == "" { - return AuthError401(c) - } - - // Decode base64 value - decodedBytes, err := base64.StdEncoding.DecodeString(userpass[6:]) - ServerError500(c, err) - - // Parse decoded values - decoded := strings.Split(string(decodedBytes), ":") - if len(decoded) != 2 { - return AuthError401(c) - } - if Auth.Match(decoded[0], decoded[1]) { - return FileServer(c) - } - return AuthError401(c) -} - -var Auth *htpasswd.File - -func InitHtpasswdAuth(htpath string) error { - var err error - Auth, err = htpasswd.New(htpath, htpasswd.DefaultSystems, nil) - return err -} - -func RouteEndpoint(c *fiber.Ctx) error { - route := c.Params("route") - switch route { - // Favicon - case "favicon.ico": - return sendIfExists(c, filepath.Join(utils.Config.CDNpath, "favicon.ico")) - - // Source Code - case "github": - return c.Redirect("https://github.com/Stridsvagn69420/Cyrkensia", fiber.StatusMovedPermanently) - - // Hostinfo - case "hostinfo": - return HostinfoEndpoint(c) - // License - case "license": - return c.Redirect("https://www.gnu.org/licenses/agpl-3.0.html", fiber.StatusMovedPermanently) - - // Album Index - default: - albumRoot := filepath.Join(utils.Config.CDNpath, route) - if utils.FileExists(albumRoot) { - fileList := utils.ListFiles(albumRoot) - return c.JSON(fileList) - } else { - return ServeError404(c) - } - } -} - -func sendIfExists(c *fiber.Ctx, filePath string) error { - if utils.FileExists(filePath) { - return c.SendFile(filePath) - } else { - return ServeError404(c) - } -} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..e7a11a9 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/utils/config.go b/utils/config.go deleted file mode 100644 index 97d437f..0000000 --- a/utils/config.go +++ /dev/null @@ -1,107 +0,0 @@ -package utils - -import ( - "encoding/json" - "errors" - "os" - - "github.com/Stridsvagn69420/pringo" -) - -type ConfigType struct { - Port int `json:"port"` - CDNpath string `json:"root"` - BindAddr string `json:"bindAddr"` - Icon string `json:"hosticon"` - Uuid string `json:"uuid"` - Locked bool - Name string `json:"vendorName"` - Access string `json:"htpasswd"` - Pem string `json:"pemTLS"` - Key string `json:"keyTLS"` - Owners []Owner `json:"owners"` -} - -type Hostinfo struct { - Name string `json:"name"` - Hosticon string `json:"hosticon"` - Uuid string `json:"uuid"` - Secured bool `json:"secured"` - Size int `json:"size"` - Root string `json:"root"` - OriginURI string `json:"originURI"` - Albums []Album `json:"albums"` - Owners []Owner `json:"owners"` -} - -type Album struct { - Cover string `json:"cover"` - Dir string `json:"dir"` - Name string `json:"name"` - Files []string `json:"files"` - Authors []Author `json:"authors"` -} - -type Owner struct { - Name string `json:"name"` - Website string `json:"website"` - Email string `json:"email"` -} - -type Author struct { - Name string `json:"name"` - Website string `json:"website"` - Email string `json:"email"` - Songs []string `json:"songs"` -} - -var Config ConfigType - -func LoadConfig(path string) { - if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { - // File does not exist - Prnt.Println("Config file does not exist! Please make sure that your given path is correct and that it points to a valid JSON file.", pringo.Red) - Prnt.Println("See https://github.com/Stridsvagn69420/Cyrkensia/wiki/Installation#-config-file or the local README.md for more.", pringo.Yellow) - os.Exit(1) - } else { - // Load config to config.Config from given json file in path - jsonTxt, _ := os.ReadFile(path) - tmpConfig := ConfigType{} - json.Unmarshal([]byte(jsonTxt), &tmpConfig) - - // Assign values if empty - assignIfEmpty(&Config.BindAddr, tmpConfig.BindAddr) - assignIfEmpty(&Config.CDNpath, tmpConfig.CDNpath) - assignIfEmpty(&Config.Icon, tmpConfig.Icon) - assignIfEmpty(&Config.Uuid, tmpConfig.Uuid) - assignIfEmpty(&Config.Name, tmpConfig.Name) - assignIfEmpty(&Config.Access, tmpConfig.Access) - assignIfEmpty(&Config.Pem, tmpConfig.Pem) - assignIfEmpty(&Config.Key, tmpConfig.Key) - assignIfEmptyArray(&Config.Owners, tmpConfig.Owners) - - // Special case for Locked and Port - if Config.Port == 0 { - Config.Port = tmpConfig.Port - } - if Config.Access == "" { - Config.Locked = false - } else { - Config.Locked = true - } - } -} - -func assignIfEmpty(variable *string, value string) { - if *variable == "" { - *variable = value - } -} - -func assignIfEmptyArray(variable *[]Owner, value []Owner) { - if len(value) > 0 { - *variable = value - } else { - *variable = make([]Owner, 0) - } -} diff --git a/utils/filesystem.go b/utils/filesystem.go deleted file mode 100644 index 295a125..0000000 --- a/utils/filesystem.go +++ /dev/null @@ -1,44 +0,0 @@ -package utils - -import ( - "errors" - "log" - "os" - "strings" -) - -func GetHomeDir() string { - dirname, err := os.UserHomeDir() - if err != nil { - log.Fatal(err) - } - return dirname -} - -func FileExists(path string) bool { - if _, err := os.Stat(path); errors.Is(err, os.ErrNotExist) { - return false - } else { - return true - } -} - -func ListFiles(path string) []string { - files, _ := os.ReadDir(path) - var fileList []string - for _, f := range files { - if !strings.HasPrefix(f.Name(), ".") && !f.IsDir() { - fileList = append(fileList, f.Name()) - } - } - return fileList -} - -func ArrayContains(arr []string, str string) bool { - for _, a := range arr { - if a == str { - return true - } - } - return false -} diff --git a/utils/printer.go b/utils/printer.go deleted file mode 100644 index 802353a..0000000 --- a/utils/printer.go +++ /dev/null @@ -1,7 +0,0 @@ -package utils - -import ( - "github.com/Stridsvagn69420/pringo" -) - -var Prnt *pringo.Printer = pringo.NewDefault() From 610fa1bca2f68c49a45587df8e53cd7e5da17318 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 25 Oct 2022 01:13:01 +0200 Subject: [PATCH 02/36] Lib files WIP. Will add private submodule for the server. --- Cargo.lock | 2 +- Cargo.toml | 13 +++++++++++-- src/album.rs | 1 + src/author.rs | 1 + src/bin/cyrkensia-cfg.rs | 3 +++ src/bin/cyrkensia.rs | 3 +++ src/config.rs | 1 + src/hostinfo.rs | 1 + src/lib.rs | 1 + src/main.rs | 3 --- src/metadata.rs | 1 + src/owner.rs | 1 + 12 files changed, 25 insertions(+), 6 deletions(-) create mode 100644 src/album.rs create mode 100644 src/author.rs create mode 100644 src/bin/cyrkensia-cfg.rs create mode 100644 src/bin/cyrkensia.rs create mode 100644 src/config.rs create mode 100644 src/hostinfo.rs create mode 100644 src/lib.rs delete mode 100644 src/main.rs create mode 100644 src/metadata.rs create mode 100644 src/owner.rs diff --git a/Cargo.lock b/Cargo.lock index 3dc628e..b140288 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4,4 +4,4 @@ version = 3 [[package]] name = "cyrkensia" -version = "0.1.0" +version = "1.2.0" diff --git a/Cargo.toml b/Cargo.toml index 2e67f24..dd4a12e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,15 @@ version = "1.2.0" edition = "2021" license = "EUPL-1.2" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html - [dependencies] + + +[[bin]] +name = "cyrkensia" +path = "src/bin/cyrkensia.rs" +required-features = [] + +[[bin]] +name = "cyrkensia-cfg" +path = "src/bin/cyrkensia-cfg.rs" +required-features = [] \ No newline at end of file diff --git a/src/album.rs b/src/album.rs new file mode 100644 index 0000000..d24935d --- /dev/null +++ b/src/album.rs @@ -0,0 +1 @@ +// TODO: Add description here and Album datatype \ No newline at end of file diff --git a/src/author.rs b/src/author.rs new file mode 100644 index 0000000..94dc7a4 --- /dev/null +++ b/src/author.rs @@ -0,0 +1 @@ +// TODO: Add description here and Author datatype \ No newline at end of file diff --git a/src/bin/cyrkensia-cfg.rs b/src/bin/cyrkensia-cfg.rs new file mode 100644 index 0000000..8a55e80 --- /dev/null +++ b/src/bin/cyrkensia-cfg.rs @@ -0,0 +1,3 @@ +fn main() { + +} \ No newline at end of file diff --git a/src/bin/cyrkensia.rs b/src/bin/cyrkensia.rs new file mode 100644 index 0000000..8a55e80 --- /dev/null +++ b/src/bin/cyrkensia.rs @@ -0,0 +1,3 @@ +fn main() { + +} \ No newline at end of file diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..b0e1e90 --- /dev/null +++ b/src/config.rs @@ -0,0 +1 @@ +// TODO: Add description here and server config type and functions \ No newline at end of file diff --git a/src/hostinfo.rs b/src/hostinfo.rs new file mode 100644 index 0000000..a3f1c02 --- /dev/null +++ b/src/hostinfo.rs @@ -0,0 +1 @@ +// TODO: Add description here and hostinfo type \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..71bf9ed --- /dev/null +++ b/src/lib.rs @@ -0,0 +1 @@ +// TODO: Add description here and exports and crate metadata (from build.rs) \ No newline at end of file diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index e7a11a9..0000000 --- a/src/main.rs +++ /dev/null @@ -1,3 +0,0 @@ -fn main() { - println!("Hello, world!"); -} diff --git a/src/metadata.rs b/src/metadata.rs new file mode 100644 index 0000000..c7457de --- /dev/null +++ b/src/metadata.rs @@ -0,0 +1 @@ +// TODO: Add description here and metadata.json datatype \ No newline at end of file diff --git a/src/owner.rs b/src/owner.rs new file mode 100644 index 0000000..3167016 --- /dev/null +++ b/src/owner.rs @@ -0,0 +1 @@ +// TODO: Add description here and Owner datatype \ No newline at end of file From 174cb79e1242943a5bddb09fbdf204c03d4a9fa0 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 25 Oct 2022 12:49:18 +0200 Subject: [PATCH 03/36] More basic files and a lot of TODOs --- .vscode/extensions.json | 6 + Cargo.lock | 1541 ++++++++++++++++++++++++++++++++++++++ Cargo.toml | 44 +- build.rs | 21 + src/bin/cyrkensia-cfg.rs | 2 +- src/bin/cyrkensia.rs | 14 +- src/lib.rs | 38 +- src/server/endpoints.rs | 1 + src/server/mod.rs | 1 + src/server/redirects.rs | 1 + 10 files changed, 1664 insertions(+), 5 deletions(-) create mode 100644 .vscode/extensions.json create mode 100644 build.rs create mode 100644 src/server/endpoints.rs create mode 100644 src/server/mod.rs create mode 100644 src/server/redirects.rs diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 0000000..9c853c3 --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,6 @@ +{ + "recommendations": [ + "rust-lang.rust-analyzer", + "bungcip.better-toml" + ] +} \ No newline at end of file diff --git a/Cargo.lock b/Cargo.lock index b140288..618ea74 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,1547 @@ # It is not intended for manual editing. version = 3 +[[package]] +name = "actix-codec" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57a7559404a7f3573127aab53c08ce37a6c6a315c374a31070f3c91cd1b4a7fe" +dependencies = [ + "bitflags", + "bytes", + "futures-core", + "futures-sink", + "log", + "memchr", + "pin-project-lite", + "tokio", + "tokio-util", +] + +[[package]] +name = "actix-cors" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "684a6ce1562a5fcca49bc9302896c63547eea78a1e405e837e7416affd8b6eb9" +dependencies = [ + "actix-utils", + "actix-web", + "derive_more", + "futures-util", + "log", + "once_cell", + "smallvec", +] + +[[package]] +name = "actix-http" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c83abf9903e1f0ad9973cc4f7b9767fd5a03a583f51a5b7a339e07987cd2724" +dependencies = [ + "actix-codec", + "actix-rt", + "actix-service", + "actix-tls", + "actix-utils", + "ahash", + "base64", + "bitflags", + "brotli", + "bytes", + "bytestring", + "derive_more", + "encoding_rs", + "flate2", + "futures-core", + "h2", + "http", + "httparse", + "httpdate", + "itoa", + "language-tags", + "local-channel", + "mime", + "percent-encoding", + "pin-project-lite", + "rand", + "sha1", + "smallvec", + "tracing", + "zstd", +] + +[[package]] +name = "actix-macros" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465a6172cf69b960917811022d8f29bc0b7fa1398bc4f78b3c466673db1213b6" +dependencies = [ + "quote", + "syn", +] + +[[package]] +name = "actix-router" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d66ff4d247d2b160861fa2866457e85706833527840e4133f8f49aa423a38799" +dependencies = [ + "bytestring", + "http", + "regex", + "serde", + "tracing", +] + +[[package]] +name = "actix-rt" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ea16c295198e958ef31930a6ef37d0fb64e9ca3b6116e6b93a8bdae96ee1000" +dependencies = [ + "futures-core", + "tokio", +] + +[[package]] +name = "actix-server" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0da34f8e659ea1b077bb4637948b815cd3768ad5a188fdcd74ff4d84240cd824" +dependencies = [ + "actix-rt", + "actix-service", + "actix-utils", + "futures-core", + "futures-util", + "mio", + "num_cpus", + "socket2", + "tokio", + "tracing", +] + +[[package]] +name = "actix-service" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b894941f818cfdc7ccc4b9e60fa7e53b5042a2e8567270f9147d5591893373a" +dependencies = [ + "futures-core", + "paste", + "pin-project-lite", +] + +[[package]] +name = "actix-tls" +version = "3.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fde0cf292f7cdc7f070803cb9a0d45c018441321a78b1042ffbbb81ec333297" +dependencies = [ + "actix-codec", + "actix-rt", + "actix-service", + "actix-utils", + "futures-core", + "log", + "pin-project-lite", + "tokio-rustls", + "tokio-util", + "webpki-roots", +] + +[[package]] +name = "actix-utils" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a1dcdff1466e3c2488e1cb5c36a71822750ad43839937f85d2f4d9f8b705d8" +dependencies = [ + "local-waker", + "pin-project-lite", +] + +[[package]] +name = "actix-web" +version = "4.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d48f7b6534e06c7bfc72ee91db7917d4af6afe23e7d223b51e68fffbb21e96b9" +dependencies = [ + "actix-codec", + "actix-http", + "actix-macros", + "actix-router", + "actix-rt", + "actix-server", + "actix-service", + "actix-tls", + "actix-utils", + "actix-web-codegen", + "ahash", + "bytes", + "bytestring", + "cfg-if", + "cookie", + "derive_more", + "encoding_rs", + "futures-core", + "futures-util", + "http", + "itoa", + "language-tags", + "log", + "mime", + "once_cell", + "pin-project-lite", + "regex", + "serde", + "serde_json", + "serde_urlencoded", + "smallvec", + "socket2", + "time 0.3.16", + "url", +] + +[[package]] +name = "actix-web-codegen" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa9362663c8643d67b2d5eafba49e4cb2c8a053a29ed00a0bea121f17c76b13" +dependencies = [ + "actix-router", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "adler" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" + +[[package]] +name = "ahash" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fcb51a0695d8f838b1ee009b3fbf66bda078cd64590202a864a8f3e8c4315c47" +dependencies = [ + "getrandom", + "once_cell", + "version_check", +] + +[[package]] +name = "aho-corasick" +version = "0.7.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4f55bd91a0978cbfd91c457a164bab8b4001c833b7f323132c0a4e1922dd44e" +dependencies = [ + "memchr", +] + +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece" +dependencies = [ + "alloc-no-stdlib", +] + +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "base64" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "block-buffer" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e" +dependencies = [ + "generic-array", +] + +[[package]] +name = "brotli" +version = "3.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a0b1dbcc8ae29329621f8d4f0d835787c1c38bb1401979b49d13b0b305ff68" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ad2d4653bf5ca36ae797b1f4bb4dbddb60ce49ca4aed8a2ce4829f60425b80" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + +[[package]] +name = "bumpalo" +version = "3.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "572f695136211188308f16ad2ca5c851a712c464060ae6974944458eb83880ba" + +[[package]] +name = "bytes" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db" + +[[package]] +name = "bytestring" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86b6a75fd3048808ef06af5cd79712be8111960adaf89d90250974b38fc3928a" +dependencies = [ + "bytes", +] + +[[package]] +name = "cc" +version = "1.0.73" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" +dependencies = [ + "jobserver", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chrono" +version = "0.4.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfd4d1b31faaa3a89d7934dbded3111da0d2ef28e3ebccdb4f0179f5929d1ef1" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-integer", + "num-traits", + "time 0.1.44", + "wasm-bindgen", + "winapi", +] + +[[package]] +name = "codespan-reporting" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3538270d33cc669650c4b093848450d380def10c331d38c768e34cac80576e6e" +dependencies = [ + "termcolor", + "unicode-width", +] + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "cookie" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "344adc371239ef32293cb1c4fe519592fcf21206c79c02854320afcdf3ab4917" +dependencies = [ + "percent-encoding", + "time 0.3.16", + "version_check", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc" + +[[package]] +name = "cpufeatures" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d997bd5e24a5928dd43e46dc529867e207907fe0b239c3477d924f7f2ca320" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b540bd8bc810d3885c6ea91e2018302f68baba2129ab3e88f32389ee9370880d" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cxx" +version = "1.0.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b7d4e43b25d3c994662706a1d4fcfc32aaa6afd287502c111b237093bb23f3a" +dependencies = [ + "cc", + "cxxbridge-flags", + "cxxbridge-macro", + "link-cplusplus", +] + +[[package]] +name = "cxx-build" +version = "1.0.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84f8829ddc213e2c1368e51a2564c552b65a8cb6a28f31e576270ac81d5e5827" +dependencies = [ + "cc", + "codespan-reporting", + "once_cell", + "proc-macro2", + "quote", + "scratch", + "syn", +] + +[[package]] +name = "cxxbridge-flags" +version = "1.0.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e72537424b474af1460806647c41d4b6d35d09ef7fe031c5c2fa5766047cc56a" + +[[package]] +name = "cxxbridge-macro" +version = "1.0.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "309e4fb93eed90e1e14bea0da16b209f81813ba9fc7830c20ed151dd7bc0a4d7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "cyrkensia" version = "1.2.0" +dependencies = [ + "actix-cors", + "actix-web", + "chrono", + "serde", + "serde_json", +] + +[[package]] +name = "derive_more" +version = "0.99.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn", +] + +[[package]] +name = "digest" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adfbc57365a37acbd2ebf2b64d7e69bb766e2fea813521ed536f5d0520dcf86c" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "encoding_rs" +version = "0.8.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9852635589dc9f9ea1b6fe9f05b50ef208c85c834a562f0c6abb1c475736ec2b" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "flate2" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f82b0f4c27ad9f8bfd1f3208d882da2b09c301bc1c828fd3a00d0216d2fbbff6" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "form_urlencoded" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9c384f161156f5260c24a097c56119f9be8c798586aecc13afbcbe7b7e26bf8" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04909a7a7e4633ae6c4a9ab280aeb86da1236243a77b694a49eacd659a4bd3ac" + +[[package]] +name = "futures-sink" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39c15cf1a4aa79df40f1bb462fb39676d0ad9e366c2a33b590d7c66f4f81fcf9" + +[[package]] +name = "futures-task" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ffb393ac5d9a6eaa9d3fdf37ae2776656b706e200c8e16b1bdb227f5198e6ea" + +[[package]] +name = "futures-util" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "197676987abd2f9cadff84926f410af1c183608d36641465df73ae8211dc65d6" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "pin-utils", +] + +[[package]] +name = "generic-array" +version = "0.14.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bff49e947297f3312447abdca79f45f4738097cc82b06e72054d2223f601f1b9" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c05aeb6a22b8f62540c194aac980f2115af067bfe15a0734d7277a768d396b31" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.11.0+wasi-snapshot-preview1", +] + +[[package]] +name = "h2" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f9f29bc9dda355256b2916cf526ab02ce0aeaaaf2bad60d65ef3f12f11dd0f4" +dependencies = [ + "bytes", + "fnv", + "futures-core", + "futures-sink", + "futures-util", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "hashbrown" +version = "0.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "http" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75f43d41e26995c17e71ee126451dd3941010b0514a81a9d11f3b341debc2399" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d897f394bad6a705d5f4104762e116a75639e470d80901eed05a860a95cb1904" + +[[package]] +name = "httpdate" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" + +[[package]] +name = "iana-time-zone" +version = "0.1.51" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5a6ef98976b22b3b7f2f3a806f858cb862044cfa66805aa3ad84cb3d3b785ed" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "wasm-bindgen", + "winapi", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0703ae284fc167426161c2e3f1da3ea71d94b21bedbcc9494e92b28e334e3dca" +dependencies = [ + "cxx", + "cxx-build", +] + +[[package]] +name = "idna" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e14ddfc70884202db2244c223200c204c2bda1bc6e0998d11b5e024d657209e6" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + +[[package]] +name = "indexmap" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e" +dependencies = [ + "autocfg", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4217ad341ebadf8d8e724e264f13e593e0648f5b3e94b3896a5df283be015ecc" + +[[package]] +name = "jobserver" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "068b1ee6743e4d11fb9c6a1e6064b3693a1b600e7f5f5988047d98b3dc9fb90b" +dependencies = [ + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49409df3e3bf0856b916e2ceaca09ee28e6871cf7d9ce97a692cacfdb2a25a47" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "language-tags" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388" + +[[package]] +name = "libc" +version = "0.2.136" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55edcf6c0bb319052dea84732cf99db461780fd5e8d3eb46ab6ff312ab31f197" + +[[package]] +name = "link-cplusplus" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9272ab7b96c9046fbc5bc56c06c117cb639fe2d509df0c421cad82d2915cf369" +dependencies = [ + "cc", +] + +[[package]] +name = "local-channel" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f303ec0e94c6c54447f84f3b0ef7af769858a9c4ef56ef2a986d3dcd4c3fc9c" +dependencies = [ + "futures-core", + "futures-sink", + "futures-util", + "local-waker", +] + +[[package]] +name = "local-waker" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e34f76eb3611940e0e7d53a9aaa4e6a3151f69541a282fd0dad5571420c53ff1" + +[[package]] +name = "lock_api" +version = "0.4.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" +dependencies = [ + "autocfg", + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "mime" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" + +[[package]] +name = "miniz_oxide" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96590ba8f175222643a85693f33d26e9c8a015f599c216509b1a6894af675d34" +dependencies = [ + "adler", +] + +[[package]] +name = "mio" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5d732bc30207a6423068df043e3d02e0735b155ad7ce1a6f76fe2baa5b158de" +dependencies = [ + "libc", + "log", + "wasi 0.11.0+wasi-snapshot-preview1", + "windows-sys", +] + +[[package]] +name = "num-integer" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "225d3389fb3509a24c93f5c29eb6bde2586b98d9f016636dff58d7c6f7569cd9" +dependencies = [ + "autocfg", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +dependencies = [ + "autocfg", +] + +[[package]] +name = "num_cpus" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "num_threads" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" +dependencies = [ + "libc", +] + +[[package]] +name = "once_cell" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e82dad04139b71a90c080c8463fe0dc7902db5192d939bd0950f074d014339e1" + +[[package]] +name = "parking_lot" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dc9e0dc2adc1c69d09143aff38d3d30c5c3f0df0dad82e6d25547af174ebec0" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-sys", +] + +[[package]] +name = "paste" +version = "1.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1de2e551fb905ac83f73f7aedf2f0cb4a0da7e35efa24a202a936269f1f18e1" + +[[package]] +name = "percent-encoding" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e" + +[[package]] +name = "pin-project-lite" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "ppv-lite86" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" + +[[package]] +name = "proc-macro2" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "redox_syscall" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4eb3267174b8c6c2f654116623910a0fef09c4753f8dd83db29c48a0df988b" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.6.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244" + +[[package]] +name = "ring" +version = "0.16.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" +dependencies = [ + "cc", + "libc", + "once_cell", + "spin", + "untrusted", + "web-sys", + "winapi", +] + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver", +] + +[[package]] +name = "rustls" +version = "0.20.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "539a2bfe908f471bfa933876bd1eb6a19cf2176d375f82ef7f99530a40e48c2c" +dependencies = [ + "log", + "ring", + "sct", + "webpki", +] + +[[package]] +name = "ryu" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" + +[[package]] +name = "scopeguard" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" + +[[package]] +name = "scratch" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8132065adcfd6e02db789d9285a0deb2f3fcb04002865ab67d5fb103533898" + +[[package]] +name = "sct" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "semver" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e25dfac463d778e353db5be2449d1cce89bd6fd23c9f1ea21310ce6e5a1b29c4" + +[[package]] +name = "serde" +version = "1.0.147" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d193d69bae983fc11a79df82342761dfbf28a99fc8d203dca4c3c1b590948965" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.147" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f1d362ca8fc9c3e3a7484440752472d68a6caa98f1ab81d99b5dfe517cec852" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.87" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce777b7b150d76b9cf60d28b55f5847135a003f7d7350c6be7a773508ce7d45" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha1" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f04293dc80c3993519f2d7f6f511707ee7094fe0c6d3406feb330cdb3540eba3" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0" +dependencies = [ + "libc", +] + +[[package]] +name = "slab" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4614a76b2a8be0058caa9dbbaf66d988527d86d003c11a94fbd335d7661edcef" +dependencies = [ + "autocfg", +] + +[[package]] +name = "smallvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" + +[[package]] +name = "socket2" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "spin" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" + +[[package]] +name = "syn" +version = "1.0.103" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "termcolor" +version = "1.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "time" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" +dependencies = [ + "libc", + "wasi 0.10.0+wasi-snapshot-preview1", + "winapi", +] + +[[package]] +name = "time" +version = "0.3.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fab5c8b9980850e06d92ddbe3ab839c062c801f3927c0fb8abd6fc8e918fbca" +dependencies = [ + "itoa", + "libc", + "num_threads", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" + +[[package]] +name = "time-macros" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65bb801831d812c562ae7d2bfb531f26e66e4e1f6b17307ba4149c5064710e5b" +dependencies = [ + "time-core", +] + +[[package]] +name = "tinyvec" +version = "1.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87cc5ceb3875bb20c2890005a4e226a4651264a5c75edb2421b52861a0a0cb50" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" + +[[package]] +name = "tokio" +version = "1.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9e03c497dc955702ba729190dc4aac6f2a0ce97f913e5b1b5912fc5039d9099" +dependencies = [ + "autocfg", + "bytes", + "libc", + "memchr", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "winapi", +] + +[[package]] +name = "tokio-rustls" +version = "0.23.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" +dependencies = [ + "rustls", + "tokio", + "webpki", +] + +[[package]] +name = "tokio-util" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb2e075f03b3d66d8d8785356224ba688d2906a371015e225beeb65ca92c740" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", + "tracing", +] + +[[package]] +name = "tracing" +version = "0.1.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ce8c33a8d48bd45d624a6e523445fd21ec13d3653cd51f681abf67418f54eb8" +dependencies = [ + "cfg-if", + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24eb03ba0eab1fd845050058ce5e616558e8f8d8fca633e6b163fe25c797213a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "typenum" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" + +[[package]] +name = "unicode-bidi" +version = "0.3.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" + +[[package]] +name = "unicode-ident" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" + +[[package]] +name = "unicode-normalization" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c5713f0fc4b5db668a2ac63cdb7bb4469d8c9fed047b1d0292cc7b0ce2ba921" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-width" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + +[[package]] +name = "url" +version = "2.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d68c799ae75762b8c3fe375feb6600ef5602c883c5d21eb51c09f22b83c4643" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", +] + +[[package]] +name = "version_check" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" + +[[package]] +name = "wasi" +version = "0.10.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a143597ca7c7793eff794def352d41792a93c481eb1042423ff7ff72ba2c31f" + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "wasm-bindgen" +version = "0.2.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaf9f5aceeec8be17c128b2e93e031fb8a4d469bb9c4ae2d7dc1888b26887268" +dependencies = [ + "cfg-if", + "wasm-bindgen-macro", +] + +[[package]] +name = "wasm-bindgen-backend" +version = "0.2.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c8ffb332579b0557b52d268b91feab8df3615f265d5270fec2a8c95b17c1142" +dependencies = [ + "bumpalo", + "log", + "once_cell", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052be0f94026e6cbc75cdefc9bae13fd6052cdcaf532fa6c45e7ae33a1e6c810" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bc0c051dc5f23e307b13285f9d75df86bfdf816c5721e573dec1f9b8aa193c" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-backend", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.83" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f" + +[[package]] +name = "web-sys" +version = "0.3.60" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bcda906d8be16e728fd5adc5b729afad4e444e106ab28cd1c7256e54fa61510f" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd" +dependencies = [ + "ring", + "untrusted", +] + +[[package]] +name = "webpki-roots" +version = "0.22.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "368bfe657969fb01238bb756d351dcade285e0f6fcbd36dcb23359a5169975be" +dependencies = [ + "webpki", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" +dependencies = [ + "winapi", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" + +[[package]] +name = "zstd" +version = "0.11.2+zstd.1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20cc960326ece64f010d2d2107537f26dc589a6573a316bd5b1dba685fa5fde4" +dependencies = [ + "zstd-safe", +] + +[[package]] +name = "zstd-safe" +version = "5.0.2+zstd.1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d2a5585e04f9eea4b2a3d1eca508c4dee9592a89ef6f450c11719da0726f4db" +dependencies = [ + "libc", + "zstd-sys", +] + +[[package]] +name = "zstd-sys" +version = "2.0.1+zstd.1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fd07cbbc53846d9145dbffdf6dd09a7a0aa52be46741825f5c97bdd4f73f12b" +dependencies = [ + "cc", + "libc", +] diff --git a/Cargo.toml b/Cargo.toml index dd4a12e..d31e58a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,18 +1,58 @@ [package] name = "cyrkensia" +description = "Server for Azura and Shigure music repositories" version = "1.2.0" edition = "2021" license = "EUPL-1.2" +readme = "README.md" +build = "build.rs" +repository = "https://github.com/Stridsvagn69420/Cyrkensia" +homepage = "https://github.com/Stridsvagn69420/Cyrkensia" +documentation = "https://docs.rs/cyrkensia" +categories = [] +keywords = [] [dependencies] +# Main crate +serde = { version = "1", features = ["derive"], optional = true } +serde_json = { version = "1", optional = true } +# Server only +actix-web = { version = "4", optional = true, features = ["rustls"] } +actix-cors = { version = "0.6", optional = true} +[features] +# Default +default = ["meta", "server"] +# Metadata +meta = ["serde"] +# Webserver +server = ["actix-web", "actix-cors"] + +[build-dependencies] +chrono = "0.4" [[bin]] name = "cyrkensia" path = "src/bin/cyrkensia.rs" -required-features = [] +required-features = ["server", "meta"] [[bin]] name = "cyrkensia-cfg" path = "src/bin/cyrkensia-cfg.rs" -required-features = [] \ No newline at end of file +required-features = ["meta"] + +[profile.release] +lto = true +strip = true +debug = true + +[package.metadata.docs.rs] +targets = [ + "x86_64-unknown-linux-gnu", + "x86_64-pc-windows-msvc", + "x86_64-pc-windows-gnu", + "aarch64-unknown-linux-gnu", + "x86_64-unknown-openbsd", + "x86_64-unknown-freebsd", + "x86_64-apple-darwin" +] \ No newline at end of file diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..2cd08d5 --- /dev/null +++ b/build.rs @@ -0,0 +1,21 @@ +use std::process::Command; +use std::env; +use chrono::Utc; + +fn version(name: &str) -> String { + let output = Command::new(name).arg("--version").output().unwrap(); + let raw = String::from_utf8(output.stdout).unwrap(); + raw.replace(&format!("{} ", name), "") +} + +fn main() { + // ----- Target Triple ----- + println!("cargo:rustc-env=TARGET={}", env::var("TARGET").unwrap()); + + // ----- Rust Version ----- + println!("cargo:rustc-env=CARGO_VERSION={}", version("cargo")); + println!("cargo:rustc-env=RUSTC_VERSION={}", version("rustc")); + + // ----- Compile Date ----- + println!("cargo:rustc-env=COMPILE_DATE={}", Utc::now().format("%Y-%m-%d")); +} \ No newline at end of file diff --git a/src/bin/cyrkensia-cfg.rs b/src/bin/cyrkensia-cfg.rs index 8a55e80..6d4d05e 100644 --- a/src/bin/cyrkensia-cfg.rs +++ b/src/bin/cyrkensia-cfg.rs @@ -1,3 +1,3 @@ fn main() { - + println!("This is still WIP!!!"); } \ No newline at end of file diff --git a/src/bin/cyrkensia.rs b/src/bin/cyrkensia.rs index 8a55e80..d4c072d 100644 --- a/src/bin/cyrkensia.rs +++ b/src/bin/cyrkensia.rs @@ -1,3 +1,15 @@ +//use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder}; + +/*#[actix_web::main] +async fn main() -> std::io::Result<()> { + HttpServer::new(|| { + App::new() + }) + .bind(("127.0.0.1", 8080))? + .run() + .await +}*/ + fn main() { - + println!("This is still WIP!!!"); } \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 71bf9ed..d0ef248 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1 +1,37 @@ -// TODO: Add description here and exports and crate metadata (from build.rs) \ No newline at end of file +// TODO: Add description here and instructions for using the library + + + + +// TODO: Add exports (*.rs files) + + + + +/// Metadata about Cyrkensia +/// +/// This little module just contains information about this crate. +pub mod meta { + pub const VERSION: &str = env!("CARGO_PKG_VERSION"); + pub const NAME: &str = env!("CARGO_PKG_NAME"); + pub const NAME_RICH: &str = "Cyrkensia"; + pub const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY"); + pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION"); + pub const LICENSE: &str = "EUPL-1.2"; + pub const LICENSE_RICH: &str = "European Union Public License v1.2"; + pub const LICENSE_URL: &str = "https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12"; + pub const CARGO_VERSION: &str = env!("CARGO_VERSION"); + pub const RUSTC_VERSION: &str = env!("RUSTC_VERSION"); + pub const COMPILE_DATE: &str = env!("COMPILE_DATE"); + pub const TARGET: &str = env!("TARGET"); + pub const USERAGENT: &str = concat!( + env!("CARGO_PKG_NAME"), + "/", + env!("CARGO_PKG_VERSION") + ); +} + +/// Server Routes +/// +/// This submodule (only visible locally) contains routes and other tools needed only for the Cyrkensia server. +pub(crate) mod server; \ No newline at end of file diff --git a/src/server/endpoints.rs b/src/server/endpoints.rs new file mode 100644 index 0000000..5f3a2e8 --- /dev/null +++ b/src/server/endpoints.rs @@ -0,0 +1 @@ +// TODO: Add endpoints \ No newline at end of file diff --git a/src/server/mod.rs b/src/server/mod.rs new file mode 100644 index 0000000..fa87f62 --- /dev/null +++ b/src/server/mod.rs @@ -0,0 +1 @@ +// TODO: Expose submodules \ No newline at end of file diff --git a/src/server/redirects.rs b/src/server/redirects.rs new file mode 100644 index 0000000..8fb80c4 --- /dev/null +++ b/src/server/redirects.rs @@ -0,0 +1 @@ +// TODO: Add redirects \ No newline at end of file From 1032fcfb6b6fe3476eefa146b6d859079f71f8e2 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 25 Oct 2022 13:42:22 +0200 Subject: [PATCH 04/36] Structs added. Trait impls wip. Main library docs wip. --- src/album.rs | 36 ++++++++++++++++++++++++++++++- src/artist.rs | 26 +++++++++++++++++++++++ src/author.rs | 1 - src/config.rs | 56 ++++++++++++++++++++++++++++++++++++++++++++++++- src/hostinfo.rs | 51 +++++++++++++++++++++++++++++++++++++++++++- src/lib.rs | 22 ++++++++++++++++--- src/metadata.rs | 26 ++++++++++++++++++++++- src/owner.rs | 25 +++++++++++++++++++++- 8 files changed, 234 insertions(+), 9 deletions(-) create mode 100644 src/artist.rs delete mode 100644 src/author.rs diff --git a/src/album.rs b/src/album.rs index d24935d..9376985 100644 --- a/src/album.rs +++ b/src/album.rs @@ -1 +1,35 @@ -// TODO: Add description here and Album datatype \ No newline at end of file +use serde::{Serialize, Deserialize}; +use super::Artist; + +/// Album +/// +/// A struct representing an album of the Cyrkensia repository. +#[derive(Debug, Serialize, Deserialize)] +pub struct Album { + /// Name + /// + /// The name of the album. + pub name: String, + + /// Cover + /// + /// The album cover asset key. + pub cover: String, + + /// Path + /// + /// The relative path of the album. + pub path: String, + + /// Artists + /// + /// The Artists of the album. + pub authors: Vec, + + /// Files + /// + /// All files present in the album as a relative path. + pub files: Vec +} + +// TODO: Add trait impls and useful functions here \ No newline at end of file diff --git a/src/artist.rs b/src/artist.rs new file mode 100644 index 0000000..02326dd --- /dev/null +++ b/src/artist.rs @@ -0,0 +1,26 @@ +use serde::{Serialize, Deserialize}; + +/// Artist +/// +/// A struct representing an author or artist of a song. +#[derive(Debug, Serialize, Deserialize)] +pub struct Artist { + pub name: String, + + /// Website + /// + /// The website of the artist. + pub website: Option, + + /// Own music + /// + /// List of files (music) that the artist made. + pub music: Vec, + + /// Features + /// + /// List of files (music) that the artist was featured in. + pub features: Vec +} + +// TODO: Add trait impls here and other useful functions \ No newline at end of file diff --git a/src/author.rs b/src/author.rs deleted file mode 100644 index 94dc7a4..0000000 --- a/src/author.rs +++ /dev/null @@ -1 +0,0 @@ -// TODO: Add description here and Author datatype \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index b0e1e90..1ac4f5a 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1 +1,55 @@ -// TODO: Add description here and server config type and functions \ No newline at end of file +use serde::{Serialize, Deserialize}; +use super::Owner; + +/// Configuration +/// +/// The server configuration used for Cyrkensia. +#[derive(Serialize, Deserialize, Debug)] +pub struct Config { + /// Name + /// + /// The display name of the repository. + pub name: String, + + /// File root + /// + /// The file root where all albums are stored. + pub root: String, + + /// UUIDv4 + /// + /// The UUID of the repository. + pub uuid: String, + + /// Icon + /// + /// The Rich Presence asset key used for displaying the server. + pub icon: String, + + /// Htpasswd file + /// + /// The path to the .htpasswd file for HTTP-Basic Authentication. If none is present, HTTP Basic Auth will be disabled. + pub htpasswd: Option, + + /// Bind address + /// + /// The IP address to bind to, e.g. `127.0.0.1`, `0.0.0.0:80` or a Unix socket (Unix only). + pub bindaddr: String, + + /// TLS Certificate (Optional) + /// + /// The Path to the TLS certificate. TLS will only be activated if both certificate and key are provided. + pub tlscert: Option, + + /// TLS Key (Optional) + /// + /// The path to the TLS key. TLS will only be activated if both certificate and key are provided. + pub tlskey: Option, + + /// Owners + /// + /// List of repository [maintainers](Owner) + pub owners: Vec +} + +// TODO: Add trait implementations and other useful functions to the struct \ No newline at end of file diff --git a/src/hostinfo.rs b/src/hostinfo.rs index a3f1c02..c2eda8e 100644 --- a/src/hostinfo.rs +++ b/src/hostinfo.rs @@ -1 +1,50 @@ -// TODO: Add description here and hostinfo type \ No newline at end of file +use serde::{Serialize, Deserialize}; +use super::{Owner, Album}; + +/// Hostinfo +/// +/// A struct representing the metadata or hostinfo and index of a Cyrkensia repository. +#[derive(Debug, Serialize, Deserialize)] +pub struct Hostinfo { + /// Name + /// + /// The name of the Cyrkensia repository. + pub name: String, + + /// Icon + /// + /// The icon representing the Cyrkensia repo. + pub icon: String, + + /// UUID + /// + /// The UUIDv4 of the repository. + pub uuid: String, + + /// Secured + /// + /// Determines whether a repository requires HTTP Basic Auth or not. + pub secured: bool, + + /// Size in bytes + /// + /// The total size of the repository and its music files in bytes. + pub size: u128, + + /// Origin URL + /// + /// The URL to get an updated version of this Hostinfo + pub origin: String, + + /// Albums + /// + /// List of all albums that this Cyrkensia repository provides. + pub albums: Vec, + + /// Maintainers and Owners + /// + /// List of all repository maintainers/owners. + pub owners: Vec +} + +// TODO: Add trait impls and useful functions here \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index d0ef248..5b07610 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,14 +1,30 @@ // TODO: Add description here and instructions for using the library +/// Owner struct +mod owner; +pub use self::owner::Owner; +/// Config struct +mod config; +pub use self::config::Config; +/// Metadata struct +mod metadata; +pub use self::metadata::Metadata; -// TODO: Add exports (*.rs files) +/// Artist struct +mod artist; +pub use self::artist::Artist; +/// Album struct +mod album; +pub use self::album::Album; +/// Hostinfo struct +mod hostinfo; +pub use self::hostinfo::Hostinfo; - -/// Metadata about Cyrkensia +/// Meta about Cyrkensia /// /// This little module just contains information about this crate. pub mod meta { diff --git a/src/metadata.rs b/src/metadata.rs index c7457de..8aea68a 100644 --- a/src/metadata.rs +++ b/src/metadata.rs @@ -1 +1,25 @@ -// TODO: Add description here and metadata.json datatype \ No newline at end of file +use serde::{Serialize, Deserialize}; +use super::Artist; + +/// .metdata.json +/// +/// A struct representing an album's `.metadata.json` file. +#[derive(Debug, Serialize, Deserialize)] +pub struct Metadata { + /// Name + /// + /// The name of the album. + pub name: String, + + /// Cover + /// + /// The asset key representing the album cover art. + pub cover: String, + + /// Authors + /// + /// List of Authors in this album. + pub authors: Vec +} + +// TODO: Add trait impls and other functions \ No newline at end of file diff --git a/src/owner.rs b/src/owner.rs index 3167016..0f90a7e 100644 --- a/src/owner.rs +++ b/src/owner.rs @@ -1 +1,24 @@ -// TODO: Add description here and Owner datatype \ No newline at end of file +use serde::{Serialize, Deserialize}; + +/// Owner +/// +/// The datatype for Cyrkensia owners. +#[derive(Serialize, Deserialize, Debug)] +pub struct Owner { + /// Name + /// + /// The username of the owner. This is optional. + pub name: String, + + /// E-Mail + /// + /// The email address of the owner. This is optional. + pub email: Option, + + /// Website + /// + /// The website or profile of an owner. This is optional. + pub website: String +} + +// TODO: Add traits and other useful functions here \ No newline at end of file From 4bdf5ecbb13975e1c5d621c370a9b595be4bb0e6 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 25 Oct 2022 15:37:20 +0200 Subject: [PATCH 05/36] Workflows and README.md --- .github/workflows/build-linux.yml | 30 +++++++++++++++ .github/workflows/build-windows.yml | 30 +++++++++++++++ .github/workflows/cargo-clippy.yml | 57 +++++++++++++++++++++++++++++ README.md | 9 +++++ 4 files changed, 126 insertions(+) create mode 100644 .github/workflows/build-linux.yml create mode 100644 .github/workflows/build-windows.yml create mode 100644 .github/workflows/cargo-clippy.yml diff --git a/.github/workflows/build-linux.yml b/.github/workflows/build-linux.yml new file mode 100644 index 0000000..6710164 --- /dev/null +++ b/.github/workflows/build-linux.yml @@ -0,0 +1,30 @@ +name: Build (Linux) + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + schedule: + - cron: '20 20 * * 3' + +jobs: + build-linux: + name: x86_64-unknown-linux-gnu + runs-on: ubuntu-latest + permissions: + contents: read + steps: + - name: Checkout Code + uses: actions/checkout@v2 + + - name: Install Rust Toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + components: clippy + override: true + + - name: Compile Cyrkensia on Linux + run: cargo build --release --target=x86_64-unknown-linux-gnu \ No newline at end of file diff --git a/.github/workflows/build-windows.yml b/.github/workflows/build-windows.yml new file mode 100644 index 0000000..87eee0e --- /dev/null +++ b/.github/workflows/build-windows.yml @@ -0,0 +1,30 @@ +name: Build (Windows) + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + schedule: + - cron: '20 20 * * 3' + +jobs: + build-windows: + name: x86_64-pc-windows-msvc + runs-on: windows-latest + permissions: + contents: read + steps: + - name: Checkout Code + uses: actions/checkout@v2 + + - name: Install Rust Toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + components: clippy + override: true + + - name: Compile Cyrkensia on Windows + run: cargo build --release --target=x86_64-pc-windows-msvc \ No newline at end of file diff --git a/.github/workflows/cargo-clippy.yml b/.github/workflows/cargo-clippy.yml new file mode 100644 index 0000000..2212607 --- /dev/null +++ b/.github/workflows/cargo-clippy.yml @@ -0,0 +1,57 @@ +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. +# rust-clippy is a tool that runs a bunch of lints to catch common +# mistakes in your Rust code and help improve your Rust code. +# More details at https://github.com/rust-lang/rust-clippy +# and https://rust-lang.github.io/rust-clippy/ + +name: Clippy Tests + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + schedule: + - cron: '20 20 * * 4' + +jobs: + cargo-clippy: + name: Cargo Clippy + runs-on: ubuntu-latest + permissions: + contents: read + security-events: write + steps: + - name: Checkout Code + uses: actions/checkout@v2 + + - name: Install Rust Toolchain + uses: actions-rs/toolchain@v1 + with: + profile: minimal + toolchain: stable + components: clippy + override: true + + - name: Install clippy-sarif and sarif-fmt + run: cargo install clippy-sarif sarif-fmt + + - name: cargo clippy + run: + cargo clippy + --all-features + --message-format=json -- --deny warnings | clippy-sarif | tee rust-clippy-results.sarif | sarif-fmt + continue-on-error: true + + - name: Upload analysis results to GitHub + uses: github/codeql-action/upload-sarif@v1 + with: + sarif_file: rust-clippy-results.sarif + wait-for-processing: true + + - name: cargo test + run: + cargo test \ No newline at end of file diff --git a/README.md b/README.md index 0548752..58bf6c9 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,13 @@ # Cyrkensia +![Build (Windows)](https://github.com/Stridsvagn69420/Cyrkensia/actions/workflows/build-windows.yml/badge.svg?branch=master) +![Build (Linux)](https://github.com/Stridsvagn69420/Cyrkensia/actions/workflows/build-linux.yml/badge.svg?branch=master) +![Clippy](https://github.com/Stridsvagn69420/Cyrkensia/actions/workflows/cargo-clippy.yml/badge.svg?branch=master) +![docs.rs](https://docs.rs/cyrkensia/badge.svg) +![Version](https://img.shields.io/crates/v/cyrkensia.svg) +![License](https://img.shields.io/crates/l/cyrkensia.svg) +![Stars](https://img.shields.io/github/stars/Stridsvagn69420/Cyrkensia.svg) +![Downloads](https://img.shields.io/crates/d/cyrkensia.svg) + Server for [Azura](https://github.com/Stridsvagn69420/Azura) and [Shigure](https://github.com/Stridsvagn69420/Shigure) music repositories From 739246bbae404ad230f9b3dd7c6583d750758680 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Wed, 26 Oct 2022 10:22:14 +0200 Subject: [PATCH 06/36] Checklist #2 to #5 done --- src/album.rs | 68 +++++++++++++++++++++++++++++++++++++++++-- src/artist.rs | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++- src/lib.rs | 22 +++++++++++++- src/owner.rs | 2 +- 4 files changed, 166 insertions(+), 6 deletions(-) diff --git a/src/album.rs b/src/album.rs index 9376985..e2b64d5 100644 --- a/src/album.rs +++ b/src/album.rs @@ -1,5 +1,6 @@ use serde::{Serialize, Deserialize}; -use super::Artist; +use std::cmp::PartialEq; +use super::{Artist, add_vec, remove_vec}; /// Album /// @@ -24,7 +25,7 @@ pub struct Album { /// Artists /// /// The Artists of the album. - pub authors: Vec, + pub artists: Vec, /// Files /// @@ -32,4 +33,65 @@ pub struct Album { pub files: Vec } -// TODO: Add trait impls and useful functions here \ No newline at end of file +impl Album { + /// New Album + /// + /// Creates a new album. If `artists` or `files` is [None], an empty array will be created for them. + pub fn new(name: String, cover: String, path: String, artists: Option>, files: Option>) -> Album { + Album { + name, + cover, + path, + artists: match artists { + Some(x) => x, + None => Vec::new() + }, + files: match files { + Some(x) => x, + None => Vec::new() + } + } + } + + /// Add [Artist] + /// + /// Adds an [Artist] to the album if they don't exist already. + pub fn add_artist(&mut self, art: Artist) -> &mut Album { + add_vec(&mut self.artists, art); + self + } + + /// Add file + /// + /// Adds a file to the album if it doesn't exist already. + pub fn add_file(&mut self, file: String) -> &mut Album { + add_vec(&mut self.files, file); + self + } + + /// Remove [Artist] + /// + /// Removes an [Artist] from the album if they already exist. + pub fn remove_artist(&mut self, art: Artist) -> &mut Album { + remove_vec(&mut self.artists, art); + self + } + + /// Remove file + /// + /// Removes a file from the album if it already exists. + pub fn remove_file(&mut self, file: String) -> &mut Album { + remove_vec(&mut self.files, file); + self + } +} + +impl PartialEq for Album { + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.cover == other.cover && + self.path == other.path && + self.artists == other.artists && + self.files == other.files + } +} \ No newline at end of file diff --git a/src/artist.rs b/src/artist.rs index 02326dd..b715dfa 100644 --- a/src/artist.rs +++ b/src/artist.rs @@ -1,4 +1,8 @@ use serde::{Serialize, Deserialize}; +use std::fmt::{Display, Result}; +use std::cmp::PartialEq; +use std::convert::From; +use super::{Owner, add_vec, remove_vec}; /// Artist /// @@ -23,4 +27,78 @@ pub struct Artist { pub features: Vec } -// TODO: Add trait impls here and other useful functions \ No newline at end of file +impl Artist { + /// New Artist + /// + /// Creates a new Artist + pub fn new(name: String, website: Option, music: Vec, features: Vec) -> Artist { + Artist { + name, + website, + music, + features + } + } + + /// Add music + /// + /// Adds a new music entry if it doesn't exist already + pub fn add_music(&mut self, music: String) -> &mut Artist { + add_vec(&mut self.music, music); + self + } + + /// Add feature + /// + /// Adds a new featured entry if it doesn't exist already + pub fn add_feature(&mut self, featured: String) -> &mut Artist { + add_vec(&mut self.features, featured); + self + } + + /// Remove music + /// + /// Removes a music entry if it exists + pub fn remove_music(&mut self, music: String) -> &mut Artist { + remove_vec(&mut self.music, music); + self + } + + /// Remove feature + /// + /// Removes a featured entry if it exists + pub fn remove_feature(&mut self, featured: String) -> &mut Artist { + remove_vec(&mut self.features, featured); + self + } +} + +impl From for Artist { + fn from(x: Owner) -> Artist { + Artist { + name: x.name, + website: x.website, + music: Vec::new(), + features: Vec::new() + } + } +} + +impl Display for Artist { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result { + if let Some(web) = self.website.clone() { + write!(f, "{} ({})", self.name, web) + } else { + write!(f, "{}", self.name) + } + } +} + +impl PartialEq for Artist { + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.website == other.website && + self.music == other.music && + self.features == other.features + } +} \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 5b07610..e3320b1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,5 +1,7 @@ // TODO: Add description here and instructions for using the library +use std::cmp::PartialEq; + /// Owner struct mod owner; pub use self::owner::Owner; @@ -50,4 +52,22 @@ pub mod meta { /// Server Routes /// /// This submodule (only visible locally) contains routes and other tools needed only for the Cyrkensia server. -pub(crate) mod server; \ No newline at end of file +pub(crate) mod server; + +/// Remove from [Vec] +/// +/// Removes an element from a [Vec], if it exists already, without returning a new [Vec]. +pub(crate) fn remove_vec(arr: &mut Vec, elm: T) { + if let Some(i) = arr.iter().position(|x| *x == elm) { + arr.remove(i); + } +} + +/// Add to [Vec] +/// +/// Adds an element to a [Vec], if the element doesn't exist yet, without returning a new [Vec]. +pub(crate) fn add_vec(arr: &mut Vec, elm: T) { + if !arr.contains(&elm) { + arr.push(elm); + } +} \ No newline at end of file diff --git a/src/owner.rs b/src/owner.rs index 0f90a7e..650df65 100644 --- a/src/owner.rs +++ b/src/owner.rs @@ -18,7 +18,7 @@ pub struct Owner { /// Website /// /// The website or profile of an owner. This is optional. - pub website: String + pub website: Option } // TODO: Add traits and other useful functions here \ No newline at end of file From 54b2020af9adb4b54ab93a8a7454076921a48c4d Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Wed, 26 Oct 2022 17:06:50 +0200 Subject: [PATCH 07/36] Owner and Metadata finished --- Cargo.lock | 4 +-- src/album.rs | 15 ++++++++++- src/lib.rs | 6 ++++- src/metadata.rs | 69 +++++++++++++++++++++++++++++++++++++++++++++---- src/owner.rs | 58 ++++++++++++++++++++++++++++++++++++++++- 5 files changed, 142 insertions(+), 10 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 618ea74..9ca4144 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -722,9 +722,9 @@ checksum = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388" [[package]] name = "libc" -version = "0.2.136" +version = "0.2.137" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55edcf6c0bb319052dea84732cf99db461780fd5e8d3eb46ab6ff312ab31f197" +checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" [[package]] name = "link-cplusplus" diff --git a/src/album.rs b/src/album.rs index e2b64d5..f44b971 100644 --- a/src/album.rs +++ b/src/album.rs @@ -1,6 +1,7 @@ use serde::{Serialize, Deserialize}; use std::cmp::PartialEq; -use super::{Artist, add_vec, remove_vec}; +use std::convert::From; +use super::{Artist, Metadata, add_vec, remove_vec}; /// Album /// @@ -86,6 +87,18 @@ impl Album { } } +impl From for Album { + fn from(x: Metadata) -> Album { + Album { + name: x.name, + cover: x.cover, + path: "".to_string(), + artists: x.artists, + files: Vec::new() + } + } +} + impl PartialEq for Album { fn eq(&self, other: &Self) -> bool { self.name == other.name && diff --git a/src/lib.rs b/src/lib.rs index e3320b1..4924c32 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,6 +1,10 @@ +use std::cmp::PartialEq; + + + // TODO: Add description here and instructions for using the library -use std::cmp::PartialEq; + /// Owner struct mod owner; diff --git a/src/metadata.rs b/src/metadata.rs index 8aea68a..ec7d4bd 100644 --- a/src/metadata.rs +++ b/src/metadata.rs @@ -1,5 +1,8 @@ use serde::{Serialize, Deserialize}; -use super::Artist; +use std::fmt::{Display, Result}; +use std::cmp::PartialEq; +use std::convert::From; +use super::{Artist, Album, add_vec, remove_vec}; /// .metdata.json /// @@ -16,10 +19,66 @@ pub struct Metadata { /// The asset key representing the album cover art. pub cover: String, - /// Authors + /// Artists /// - /// List of Authors in this album. - pub authors: Vec + /// List of [Artist]s in this album. + pub artists: Vec } -// TODO: Add trait impls and other functions \ No newline at end of file +// TODO: Add trait impls and other functions + +impl Metadata { + /// New Metadata + /// + /// Creates new [Metadata]. Authors can be appended later on. + pub fn new(name: String, cover: String, artists: Option>) -> Metadata { + Metadata { + name, + cover, + artists: match artists { + Some(x) => x, + None => Vec::new() + } + } + } + + /// Add Artist + /// + /// Adds an [Artist], if they don't exist yet. + pub fn add_artist(&mut self, art: Artist) -> &mut Metadata { + add_vec(&mut self.artists, art); + self + } + + /// Remove Artist + /// + /// Removes an [Artist], if they already exist. + pub fn remove_artist(&mut self, art: Artist) -> &mut Metadata { + remove_vec(&mut self.artists, art); + self + } +} + +impl From for Metadata { + fn from(x: Album) -> Metadata { + Metadata { + name: x.name, + cover: x.cover, + artists: x.artists + } + } +} + +impl PartialEq for Metadata { + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.cover == other.cover && + self.artists == other.artists + } +} + +impl Display for Metadata { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result { + write!(f, "{}", self.name) + } +} \ No newline at end of file diff --git a/src/owner.rs b/src/owner.rs index 650df65..3f2f860 100644 --- a/src/owner.rs +++ b/src/owner.rs @@ -1,4 +1,8 @@ use serde::{Serialize, Deserialize}; +use std::fmt::{Display, Result}; +use std::cmp::PartialEq; +use std::convert::From; +use super::Artist; /// Owner /// @@ -21,4 +25,56 @@ pub struct Owner { pub website: Option } -// TODO: Add traits and other useful functions here \ No newline at end of file +impl Owner { + /// New Owner + /// + /// Creates a new owner. E-Mail and Website are optional, though if `email` isn't used, `website` should be, and vice versa. + pub fn new(name: String, email: Option, website: Option) -> Owner { + Owner { + name, + email, + website + } + } +} + +impl From for Owner { + fn from(x: Artist) -> Self { + Owner { + name: x.name, + email: None, + website: x.website + } + } +} + +impl PartialEq for Owner { + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.email == other.email && + self.website == other.website + } +} + +impl Display for Owner { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result { + match (self.email.clone(), self.website.clone()) { + (None, None) => { + // Name only + write!(f, "{}", self.name) + }, + (None, Some(y)) => { + // Name and Website + write!(f, "{} ({})", self.name, y) + }, + (Some(x), None) => { + // Name and E-Mail + write!(f, "{} <{}>", self.name, x) + }, + (Some(x), Some(y)) => { + // Name, E-Mail and Website + write!(f, "{} <{}> ({})", self.name, x, y) + } + } + } +} \ No newline at end of file From 31ab7d958eeb9264ff7ffe8a32408974b2f69ad4 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 1 Nov 2022 02:20:52 +0100 Subject: [PATCH 08/36] Config done basically --- Cargo.lock | 16 +++++++-------- Cargo.toml | 2 +- src/config.rs | 55 +++++++++++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 62 insertions(+), 11 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 9ca4144..55e9253 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -21,9 +21,9 @@ dependencies = [ [[package]] name = "actix-cors" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "684a6ce1562a5fcca49bc9302896c63547eea78a1e405e837e7416affd8b6eb9" +checksum = "b340e9cfa5b08690aae90fb61beb44e9b06f44fe3d0f93781aaa58cfba86245e" dependencies = [ "actix-utils", "actix-web", @@ -337,9 +337,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.73" +version = "1.0.74" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2fff2a6927b3bb87f9595d67196a70493f627687a71d87a0d692242c33f58c11" +checksum = "581f5dba903aac52ea3feb5ec4810848460ee833876f1f9b0fdeab1f19091574" dependencies = [ "jobserver", ] @@ -648,9 +648,9 @@ checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" [[package]] name = "iana-time-zone" -version = "0.1.51" +version = "0.1.53" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5a6ef98976b22b3b7f2f3a806f858cb862044cfa66805aa3ad84cb3d3b785ed" +checksum = "64c122667b287044802d6ce17ee2ddf13207ed924c712de9a66a5814d5b64765" dependencies = [ "android_system_properties", "core-foundation-sys", @@ -845,9 +845,9 @@ dependencies = [ [[package]] name = "once_cell" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e82dad04139b71a90c080c8463fe0dc7902db5192d939bd0950f074d014339e1" +checksum = "86f0b0d4bf799edbc74508c1e8bf170ff5f41238e5f8225603ca7caaae2b7860" [[package]] name = "parking_lot" diff --git a/Cargo.toml b/Cargo.toml index d31e58a..987902c 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,7 +24,7 @@ actix-cors = { version = "0.6", optional = true} # Default default = ["meta", "server"] # Metadata -meta = ["serde"] +meta = ["serde", "serde_json"] # Webserver server = ["actix-web", "actix-cors"] diff --git a/src/config.rs b/src/config.rs index 1ac4f5a..17d9837 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,5 +1,11 @@ use serde::{Serialize, Deserialize}; -use super::Owner; +use serde_json::from_str; +use std::cmp::PartialEq; +use std::convert::From; +use std::io; +use std::fs; +use std::path::Path; +use super::{Owner, Hostinfo}; /// Configuration /// @@ -52,4 +58,49 @@ pub struct Config { pub owners: Vec } -// TODO: Add trait implementations and other useful functions to the struct \ No newline at end of file +impl Config { + /// Load Config File + /// + /// Loads a config from a file in the filesystem. + pub fn load_file(path: impl AsRef) -> io::Result { + let rawfile = fs::read_to_string(path)?; + Ok(from_str(rawfile.as_str())?) + } + + /// Load Config JSON + /// + /// Loads a config from an already existing &[str]. + pub fn load_json(data: &str) -> io::Result { + Ok(from_str(data)?) + } +} + +impl From for Config { + fn from(x: Hostinfo) -> Config { + Config { + name: x.name, + root: "".to_string(), + uuid: x.uuid, + icon: x.icon, + htpasswd: None, + bindaddr: "".to_string(), + tlscert: None, + tlskey: None, + owners: x.owners + } + } +} + +impl PartialEq for Config { + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.root == other.root && + self.uuid == other.uuid && + self.icon == other.icon && + self.htpasswd == other.htpasswd && + self.bindaddr == other.bindaddr && + self.tlscert == other.tlscert && + self.tlskey == other.tlskey && + self.owners == other.owners + } +} \ No newline at end of file From dfae17bb3399f762249263cd1c494c682a157a93 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 1 Nov 2022 03:48:13 +0100 Subject: [PATCH 09/36] Hostinfo done, including generation!! --- src/hostinfo.rs | 161 +++++++++++++++++++++++++++++++++++++++++++++++- src/metadata.rs | 12 ++++ 2 files changed, 171 insertions(+), 2 deletions(-) diff --git a/src/hostinfo.rs b/src/hostinfo.rs index c2eda8e..19e0c75 100644 --- a/src/hostinfo.rs +++ b/src/hostinfo.rs @@ -1,5 +1,10 @@ use serde::{Serialize, Deserialize}; -use super::{Owner, Album}; +use std::cmp::PartialEq; +use std::convert::From; +use std::io; +use std::fs; +use std::path::Path; +use super::{Owner, Album, Config, Metadata}; /// Hostinfo /// @@ -47,4 +52,156 @@ pub struct Hostinfo { pub owners: Vec } -// TODO: Add trait impls and useful functions here \ No newline at end of file +impl Hostinfo { + /// Generate empty Hostinfo + /// + /// Generates an empty Hostinfo. + pub fn empty() -> Hostinfo { + Hostinfo { + name: "".to_string(), + icon: "".to_string(), + uuid: "".to_string(), + secured: false, + size: 0, + origin: "".to_string(), + albums: Vec::new(), + owners: Vec::new() + } + } + + + /// Generate Hostinfo + /// + /// Generates a Hostinfo based on a [Config]. + pub fn generate(cfg: Config) -> io::Result { + let albums = Hostinfo::read_albums(cfg.root.as_str())?; + let mut hostinfo = Hostinfo::from(cfg); + hostinfo.albums = albums.0; + hostinfo.size = albums.1; + Ok(hostinfo) + } + + /// Read Albums + /// + /// Reads a given directory and returns it as a [Vec] of [Album]s + pub fn read_albums(path: impl AsRef) -> io::Result<(Vec, u128)> { + // Total Size of Albums + let mut totsize: u128 = 0; + + // Read given Cyrkensia root + let albums: Vec = fs::read_dir(path.as_ref())? + + // Only use working entries and get directory path and name + .filter_map(|x| { + if let Ok(dir) = x { + if dir.path().is_dir() { + return Some((dir.path(), dir.file_name())); + } + } + None + }) + + // Create Album instances + .filter_map(|y| { + // Load Metadata + if let Ok(meta) = Metadata::load(y.0.join(".metadata.json")) { + + // Just for safety. Safely converts the OsString to a String. + if let Some(fname) = y.1.to_str() { + + // Read files and total size + if let Ok(res) = Hostinfo::list_files(fname) { + + // Add size and return Album + totsize += res.1; + return Some(Album { + name: meta.name, + cover: meta.cover, + path: fname.to_string(), + artists: meta.artists, + files: res.0 + }); + } + } + } + None + }) + + // Collect and Return + .collect(); + Ok((albums, totsize)) + } + + + /// List files + /// + /// Lists all files in a given directory and their total size + pub fn list_files(path: impl AsRef) -> io::Result<(Vec, u128)> { + let mut allsize: u128 = 0; + + // Read Dir + let file_entries = fs::read_dir(path)? + + // Only files and with successful metadata + .filter_map(|x| { + + // Get successful DirEntries + if let Ok(entry) = x { + + // Filter out non-files + if entry.path().is_file() { + + // Get successful Metadata + if let Ok(fmeta) = entry.metadata() { + + // Return Path and Length + return Some((entry.path(), fmeta.len())); + } + } + } + None + }) + + // Convert PathBuf to String + .filter_map(|y| { + if let Ok(pathstr) = y.0.into_os_string().into_string() { + // Add filesize to total buffer + allsize += y.1 as u128; + return Some(pathstr); + } + None + }) + + // Collect to Vec and return result + .collect(); + Ok((file_entries, allsize)) + } +} + +impl From for Hostinfo { + fn from(x: Config) -> Hostinfo { + Hostinfo { + name: x.name, + icon: x.icon, + uuid: x.uuid, + secured: x.htpasswd.is_some(), + size: 0, + origin: "".to_string(), + albums: Vec::new(), + owners: x.owners, + } + } +} + +impl PartialEq for Hostinfo { + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.icon == other.icon && + self.uuid == other.uuid && + self.secured == other.secured && + self.size == other.size && + self.origin == other.origin && + self.albums == other.albums && + self.owners == other.owners + } +} \ No newline at end of file diff --git a/src/metadata.rs b/src/metadata.rs index ec7d4bd..2b7f55d 100644 --- a/src/metadata.rs +++ b/src/metadata.rs @@ -1,7 +1,11 @@ use serde::{Serialize, Deserialize}; +use serde_json::from_str; use std::fmt::{Display, Result}; use std::cmp::PartialEq; use std::convert::From; +use std::path::Path; +use std::fs; +use std::io; use super::{Artist, Album, add_vec, remove_vec}; /// .metdata.json @@ -42,6 +46,14 @@ impl Metadata { } } + /// Load .metadata.json + /// + /// Loads a `.metadata.json` file into a [Metadata] instance. + pub fn load(path: impl AsRef) -> io::Result { + let data = fs::read_to_string(path)?; + Ok(from_str(data.as_str())?) + } + /// Add Artist /// /// Adds an [Artist], if they don't exist yet. From a4b1a4000b0bae6578d6e82cb1d55b682785d260 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 1 Nov 2022 13:35:15 +0100 Subject: [PATCH 10/36] Cleaner Hostinfo code and docs --- src/album.rs | 18 ++++++++--- src/hostinfo.rs | 84 +++++++++++++++++++++++++++---------------------- src/lib.rs | 41 ++++++++++++++++++++---- src/metadata.rs | 2 -- 4 files changed, 95 insertions(+), 50 deletions(-) diff --git a/src/album.rs b/src/album.rs index f44b971..5357411 100644 --- a/src/album.rs +++ b/src/album.rs @@ -31,14 +31,19 @@ pub struct Album { /// Files /// /// All files present in the album as a relative path. - pub files: Vec + pub files: Vec, + + /// Size + /// + /// The size of the Album. + pub size: u128 } impl Album { /// New Album /// /// Creates a new album. If `artists` or `files` is [None], an empty array will be created for them. - pub fn new(name: String, cover: String, path: String, artists: Option>, files: Option>) -> Album { + pub fn new(name: String, cover: String, path: String, artists: Option>, files: Option>, size: u128) -> Album { Album { name, cover, @@ -50,7 +55,8 @@ impl Album { files: match files { Some(x) => x, None => Vec::new() - } + }, + size } } @@ -94,7 +100,8 @@ impl From for Album { cover: x.cover, path: "".to_string(), artists: x.artists, - files: Vec::new() + files: Vec::new(), + size: 0 } } } @@ -105,6 +112,7 @@ impl PartialEq for Album { self.cover == other.cover && self.path == other.path && self.artists == other.artists && - self.files == other.files + self.files == other.files && + self.size == other.size } } \ No newline at end of file diff --git a/src/hostinfo.rs b/src/hostinfo.rs index 19e0c75..959596a 100644 --- a/src/hostinfo.rs +++ b/src/hostinfo.rs @@ -1,9 +1,10 @@ use serde::{Serialize, Deserialize}; use std::cmp::PartialEq; use std::convert::From; +use std::ffi::OsString; use std::io; use std::fs; -use std::path::Path; +use std::path::{Path, PathBuf}; use super::{Owner, Album, Config, Metadata}; /// Hostinfo @@ -53,6 +54,13 @@ pub struct Hostinfo { } impl Hostinfo { + /// Set Origin + /// + /// Sets the origin of the Hostinfo. This function solely exists to remind library users to swap out the empty default origin. + pub fn set_origin(&mut self, org: String) { + self.origin = org + } + /// Generate empty Hostinfo /// /// Generates an empty Hostinfo. @@ -69,25 +77,21 @@ impl Hostinfo { } } - /// Generate Hostinfo /// /// Generates a Hostinfo based on a [Config]. pub fn generate(cfg: Config) -> io::Result { let albums = Hostinfo::read_albums(cfg.root.as_str())?; let mut hostinfo = Hostinfo::from(cfg); - hostinfo.albums = albums.0; - hostinfo.size = albums.1; + hostinfo.size = albums.iter().map(|x| x.size).sum(); + hostinfo.albums = albums; Ok(hostinfo) } /// Read Albums /// - /// Reads a given directory and returns it as a [Vec] of [Album]s - pub fn read_albums(path: impl AsRef) -> io::Result<(Vec, u128)> { - // Total Size of Albums - let mut totsize: u128 = 0; - + /// Reads a given directory and returns it as a [Vec] of [Album]s. + pub fn read_albums(path: impl AsRef) -> io::Result> { // Read given Cyrkensia root let albums: Vec = fs::read_dir(path.as_ref())? @@ -103,35 +107,37 @@ impl Hostinfo { // Create Album instances .filter_map(|y| { - // Load Metadata - if let Ok(meta) = Metadata::load(y.0.join(".metadata.json")) { - - // Just for safety. Safely converts the OsString to a String. - if let Some(fname) = y.1.to_str() { - - // Read files and total size - if let Ok(res) = Hostinfo::list_files(fname) { - - // Add size and return Album - totsize += res.1; - return Some(Album { - name: meta.name, - cover: meta.cover, - path: fname.to_string(), - artists: meta.artists, - files: res.0 - }); - } - } - } - None + Hostinfo::parse_album(&y.0, &y.1).ok() }) // Collect and Return .collect(); - Ok((albums, totsize)) + Ok(albums) } + /// Parse album + /// + /// This is a wrapper for the second `.filter_map()` in [read_albums](Hostinfo::read_albums) since clojures don't allow the `?`. + /// You can of course also use it if you desire. + pub fn parse_album(path: &PathBuf, name: &OsString) -> io::Result { + if let Some(fname) = name.to_str() { + // Read data + let m = Metadata::load(path.join(".metadata.json"))?; + let c = Hostinfo::list_files(path)?; + + // Create Album + return Ok(Album { + name: m.name, + cover: m.cover, + artists: m.artists, + path: fname.to_string(), + files: c.0, + size: c.1, + }); + } + // Return NotFound error by default + Err(io::Error::new(io::ErrorKind::NotFound, "The OsString could not be parsed to a String")) + } /// List files /// @@ -162,12 +168,16 @@ impl Hostinfo { None }) - // Convert PathBuf to String + // Return only the filename and not the entire path .filter_map(|y| { - if let Ok(pathstr) = y.0.into_os_string().into_string() { - // Add filesize to total buffer - allsize += y.1 as u128; - return Some(pathstr); + if let Some(filename) = y.0.file_name() { + if let Some(fname) = filename.to_str() { + // Filter out dotfiles + if !fname.starts_with('.') { + allsize += y.1 as u128; + return Some(fname.to_string()); + } + } } None }) diff --git a/src/lib.rs b/src/lib.rs index 4924c32..1a9c471 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,10 +1,39 @@ -use std::cmp::PartialEq; - - - -// TODO: Add description here and instructions for using the library - +//! # Cyrkensia +//! ![Build (Windows)](https://github.com/Stridsvagn69420/Cyrkensia/actions/workflows/build-windows.yml/badge.svg?branch=master) +//! ![Build (Linux)](https://github.com/Stridsvagn69420/Cyrkensia/actions/workflows/build-linux.yml/badge.svg?branch=master) +//! ![Clippy](https://github.com/Stridsvagn69420/Cyrkensia/actions/workflows/cargo-clippy.yml/badge.svg?branch=master) +//! ![docs.rs](https://docs.rs/cyrkensia/badge.svg) +//! ![Version](https://img.shields.io/crates/v/cyrkensia.svg) +//! ![License](https://img.shields.io/crates/l/cyrkensia.svg) +//! ![Stars](https://img.shields.io/github/stars/Stridsvagn69420/Cyrkensia.svg) +//! ![Downloads](https://img.shields.io/crates/d/cyrkensia.svg) +//! +//! NOTE: This documentation focuses on Cyrkensia as a library. +//! If you're searching for Cyrkensia as a binary, see the [crates.io](https://crates.io/crates/cyrkensia) or [GitHub](https://github.com/Stridsvagn69420/Cyrkensia) page for more. +//! +//! ## Features +//! By default, both the `meta` and the `server` features are enabled. The latter is only relevant for people who write a custom Cyrkensia server. +//! The `meta` feature exposes the custom structs used in this project and is probably what you want. You can disable `server` and enable `meta` with this: +//! +//! ```toml +//! cyrkensia = { version = "1", default-features = false, features = ["meta"] } +//! ``` +//! +//! ## Examples +//! +//! Reading a Config and generating its Hostinfo +//! ```no_run +//! use cyrkensia::{Hostinfo, Config}; +//! +//! // Load the config file +//! let config = Config::load_file("config.json").unwrap(); +//! // Generate the corresponding Hostinfo +//! let mut hostinfo = Hostinfo::generate(config).unwrap(); +//! // Optionally set the origin +//! hostinfo.set_origin("https://foo.bar/my-hostinfo.json".to_string()); +//! ``` +use std::cmp::PartialEq; /// Owner struct mod owner; diff --git a/src/metadata.rs b/src/metadata.rs index 2b7f55d..66cc31d 100644 --- a/src/metadata.rs +++ b/src/metadata.rs @@ -29,8 +29,6 @@ pub struct Metadata { pub artists: Vec } -// TODO: Add trait impls and other functions - impl Metadata { /// New Metadata /// From faf564e760991beee0f9cb76c43ed3de41a5b6dd Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 1 Nov 2022 19:39:42 +0100 Subject: [PATCH 11/36] Middleware and redirects --- Cargo.toml | 15 ++++++--------- src/lib.rs | 13 +++++++------ src/server/endpoints.rs | 1 - src/server/middleware.rs | 22 ++++++++++++++++++++++ src/server/mod.rs | 15 ++++++++++++++- src/server/redirect.rs | 25 +++++++++++++++++++++++++ src/server/redirects.rs | 1 - src/server/route.rs | 1 + 8 files changed, 75 insertions(+), 18 deletions(-) delete mode 100644 src/server/endpoints.rs create mode 100644 src/server/middleware.rs create mode 100644 src/server/redirect.rs delete mode 100644 src/server/redirects.rs create mode 100644 src/server/route.rs diff --git a/Cargo.toml b/Cargo.toml index 987902c..62b8ae1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,23 +9,20 @@ build = "build.rs" repository = "https://github.com/Stridsvagn69420/Cyrkensia" homepage = "https://github.com/Stridsvagn69420/Cyrkensia" documentation = "https://docs.rs/cyrkensia" +authors = ["Stridsvagn69420"] categories = [] keywords = [] [dependencies] # Main crate -serde = { version = "1", features = ["derive"], optional = true } -serde_json = { version = "1", optional = true } +serde = { version = "1", features = ["derive"] } +serde_json = "1" # Server only actix-web = { version = "4", optional = true, features = ["rustls"] } actix-cors = { version = "0.6", optional = true} [features] -# Default -default = ["meta", "server"] -# Metadata -meta = ["serde", "serde_json"] -# Webserver +default = ["server"] server = ["actix-web", "actix-cors"] [build-dependencies] @@ -34,12 +31,12 @@ chrono = "0.4" [[bin]] name = "cyrkensia" path = "src/bin/cyrkensia.rs" -required-features = ["server", "meta"] +required-features = ["server"] [[bin]] name = "cyrkensia-cfg" path = "src/bin/cyrkensia-cfg.rs" -required-features = ["meta"] +required-features = [] [profile.release] lto = true diff --git a/src/lib.rs b/src/lib.rs index 1a9c471..ea1757f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,11 +12,10 @@ //! If you're searching for Cyrkensia as a binary, see the [crates.io](https://crates.io/crates/cyrkensia) or [GitHub](https://github.com/Stridsvagn69420/Cyrkensia) page for more. //! //! ## Features -//! By default, both the `meta` and the `server` features are enabled. The latter is only relevant for people who write a custom Cyrkensia server. -//! The `meta` feature exposes the custom structs used in this project and is probably what you want. You can disable `server` and enable `meta` with this: -//! +//! By default, the `server` feature is enabled. The latter is only relevant for people who write a custom Cyrkensia server. +//! You can disable `server` with this: //! ```toml -//! cyrkensia = { version = "1", default-features = false, features = ["meta"] } +//! cyrkensia = { version = "1", default-features = false } //! ``` //! //! ## Examples @@ -66,6 +65,7 @@ pub mod meta { pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const NAME: &str = env!("CARGO_PKG_NAME"); pub const NAME_RICH: &str = "Cyrkensia"; + pub const AUTHORS: &str = env!("CARGO_PKG_AUTHORS"); pub const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY"); pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION"); pub const LICENSE: &str = "EUPL-1.2"; @@ -82,10 +82,11 @@ pub mod meta { ); } +#[cfg(feature = "server")] /// Server Routes /// -/// This submodule (only visible locally) contains routes and other tools needed only for the Cyrkensia server. -pub(crate) mod server; +/// This submodule contains routes and other tools needed only for the Cyrkensia server. +pub mod server; /// Remove from [Vec] /// diff --git a/src/server/endpoints.rs b/src/server/endpoints.rs deleted file mode 100644 index 5f3a2e8..0000000 --- a/src/server/endpoints.rs +++ /dev/null @@ -1 +0,0 @@ -// TODO: Add endpoints \ No newline at end of file diff --git a/src/server/middleware.rs b/src/server/middleware.rs new file mode 100644 index 0000000..adadf21 --- /dev/null +++ b/src/server/middleware.rs @@ -0,0 +1,22 @@ +use actix_web::middleware::DefaultHeaders; +use crate::meta; + +/// License Headers +/// +/// Appends the license headers (`X-License`, `X-License-SPDX` and `X-License-URL`) to every HTTP Response. +pub fn license_headers() -> DefaultHeaders { + DefaultHeaders::new() + .add(("X-License", meta::LICENSE_RICH)) + .add(("X-License-SPDX", meta::LICENSE)) + .add(("X-License-URL", meta::LICENSE_URL)) +} + +/// Owner and Source Code Headers +/// +/// Appends the `X-Authors` and `X-Repository` headers to every HTTP Response. +pub fn source_headers() -> DefaultHeaders { + DefaultHeaders::new() + .add(("Server", meta::USERAGENT)) + .add(("X-Authors", meta::AUTHORS.replace(':', ", "))) + .add(("X-Repository", meta::REPOSITORY)) +} \ No newline at end of file diff --git a/src/server/mod.rs b/src/server/mod.rs index fa87f62..bdcf743 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1 +1,14 @@ -// TODO: Expose submodules \ No newline at end of file +/// Middlewares +/// +/// Submodule containing Cyrkensia middlewares. +pub mod middleware; + +/// Redirects +/// +/// Submodule containing Cyrkensia redirects. +pub mod redirect; + +/// Routes +/// +/// Submodule containing Cyrkensia routes. +pub mod route; \ No newline at end of file diff --git a/src/server/redirect.rs b/src/server/redirect.rs new file mode 100644 index 0000000..76e009a --- /dev/null +++ b/src/server/redirect.rs @@ -0,0 +1,25 @@ +use actix_web::{HttpResponse, Responder, http::header::LOCATION}; +use crate::meta; + +/// Redirect +/// +/// Creates a new 301 Moved Permanently redirect with the given Url. +pub fn redirect(url: &str) -> impl Responder { + HttpResponse::MovedPermanently() + .append_header((LOCATION, url)) + .finish() +} + +/// Repository redirect +/// +/// Redirects to the source code repository. +pub async fn repository() -> impl Responder { + redirect(meta::REPOSITORY) +} + +/// License redirect +/// +/// Redirects to the license text. +pub async fn license() -> impl Responder { + redirect(meta::LICENSE_URL) +} \ No newline at end of file diff --git a/src/server/redirects.rs b/src/server/redirects.rs deleted file mode 100644 index 8fb80c4..0000000 --- a/src/server/redirects.rs +++ /dev/null @@ -1 +0,0 @@ -// TODO: Add redirects \ No newline at end of file diff --git a/src/server/route.rs b/src/server/route.rs new file mode 100644 index 0000000..7784153 --- /dev/null +++ b/src/server/route.rs @@ -0,0 +1 @@ +// TODO: Add fileserver routes \ No newline at end of file From 7fd6412d209c27c836ef1f09a2b51f80fad8115d Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Thu, 3 Nov 2022 23:58:06 +0100 Subject: [PATCH 12/36] Lib part basically done. Routes can only be set in the binary itself. --- src/lib.rs | 3 ++- src/server/mod.rs | 7 +------ src/server/route.rs | 1 - 3 files changed, 3 insertions(+), 8 deletions(-) delete mode 100644 src/server/route.rs diff --git a/src/lib.rs b/src/lib.rs index ea1757f..16f92d3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -85,7 +85,8 @@ pub mod meta { #[cfg(feature = "server")] /// Server Routes /// -/// This submodule contains routes and other tools needed only for the Cyrkensia server. +/// This submodule contains middlewares and other tools needed only for the Cyrkensia server. +/// Note that the routes that Cyrkensia uses are directly in the `cyrkensia` binary due to technical obstacles. pub mod server; /// Remove from [Vec] diff --git a/src/server/mod.rs b/src/server/mod.rs index bdcf743..ad6d2c0 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -6,9 +6,4 @@ pub mod middleware; /// Redirects /// /// Submodule containing Cyrkensia redirects. -pub mod redirect; - -/// Routes -/// -/// Submodule containing Cyrkensia routes. -pub mod route; \ No newline at end of file +pub mod redirect; \ No newline at end of file diff --git a/src/server/route.rs b/src/server/route.rs deleted file mode 100644 index 7784153..0000000 --- a/src/server/route.rs +++ /dev/null @@ -1 +0,0 @@ -// TODO: Add fileserver routes \ No newline at end of file From 31461bcac13caa1cbb59328b0ece7e96025c2fe8 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Sun, 6 Nov 2022 22:03:01 +0100 Subject: [PATCH 13/36] Rust 1.65 and let-else is awesome --- Cargo.toml | 1 + src/hostinfo.rs | 63 +++++++++++++++++++++++++++---------------------- 2 files changed, 36 insertions(+), 28 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 62b8ae1..6727c0f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,6 +3,7 @@ name = "cyrkensia" description = "Server for Azura and Shigure music repositories" version = "1.2.0" edition = "2021" +rust-version = "1.65" license = "EUPL-1.2" readme = "README.md" build = "build.rs" diff --git a/src/hostinfo.rs b/src/hostinfo.rs index 959596a..6afa4ed 100644 --- a/src/hostinfo.rs +++ b/src/hostinfo.rs @@ -97,12 +97,16 @@ impl Hostinfo { // Only use working entries and get directory path and name .filter_map(|x| { - if let Ok(dir) = x { - if dir.path().is_dir() { - return Some((dir.path(), dir.file_name())); - } + // Try getting the DirEntry + let Ok(dir) = x else { + return None; + }; + // Filter out non-dirs + if !dir.path().is_dir() { + return None; } - None + // Return path and filename + Some((dir.path(), dir.file_name())) }) // Create Album instances @@ -150,36 +154,39 @@ impl Hostinfo { // Only files and with successful metadata .filter_map(|x| { - // Get successful DirEntries - if let Ok(entry) = x { - - // Filter out non-files - if entry.path().is_file() { - - // Get successful Metadata - if let Ok(fmeta) = entry.metadata() { - - // Return Path and Length - return Some((entry.path(), fmeta.len())); - } - } + let Ok(entry) = x else { + return None; + }; + // Filter out non-files + if !entry.path().is_file() { + return None; } - None + // Get successful Metadata + let Ok(fmeta) = entry.metadata() else { + return None; + }; + // Return Path and Length + Some((entry.path(), fmeta.len())) }) // Return only the filename and not the entire path .filter_map(|y| { - if let Some(filename) = y.0.file_name() { - if let Some(fname) = filename.to_str() { - // Filter out dotfiles - if !fname.starts_with('.') { - allsize += y.1 as u128; - return Some(fname.to_string()); - } - } + // Get OS filename + let Some(filename) = y.0.file_name() else { + return None; + }; + // Get filename as &str + let Some(fname) = filename.to_str() else { + return None; + }; + // Filter out dotfiles + if fname.starts_with('.') { + return None; } - None + // Append to size and return filename + allsize += y.1 as u128; + Some(fname.to_string()) }) // Collect to Vec and return result From c08a02b1f6faf630fbf7509471e507c9f8c82727 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Mon, 14 Nov 2022 00:09:13 +0100 Subject: [PATCH 14/36] Add shared state for Actix-Web routes --- src/config.rs | 13 +++++++--- src/owner.rs | 2 +- src/server/mod.rs | 60 +++++++++++++++++++++++++++++++++++++++++++- src/server/routes.rs | 0 4 files changed, 70 insertions(+), 5 deletions(-) create mode 100644 src/server/routes.rs diff --git a/src/config.rs b/src/config.rs index 17d9837..e4642c3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -10,7 +10,7 @@ use super::{Owner, Hostinfo}; /// Configuration /// /// The server configuration used for Cyrkensia. -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Clone)] pub struct Config { /// Name /// @@ -55,7 +55,13 @@ pub struct Config { /// Owners /// /// List of repository [maintainers](Owner) - pub owners: Vec + pub owners: Vec, + + /// Maximum Age + /// + /// The maximum age of the [Hostinfo] in milliseconds as a [u32]. If [None], the Hostinfo will always be regenerated when its route is accessed. + /// This basically activates caching. + pub max_age: Option } impl Config { @@ -86,7 +92,8 @@ impl From for Config { bindaddr: "".to_string(), tlscert: None, tlskey: None, - owners: x.owners + owners: x.owners, + max_age: None } } } diff --git a/src/owner.rs b/src/owner.rs index 3f2f860..b6d7346 100644 --- a/src/owner.rs +++ b/src/owner.rs @@ -7,7 +7,7 @@ use super::Artist; /// Owner /// /// The datatype for Cyrkensia owners. -#[derive(Serialize, Deserialize, Debug)] +#[derive(Serialize, Deserialize, Debug, Clone)] pub struct Owner { /// Name /// diff --git a/src/server/mod.rs b/src/server/mod.rs index ad6d2c0..4f83728 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,3 +1,8 @@ +use crate::{Hostinfo, Config}; +use std::sync::Mutex; +use std::time::Instant; +use std::io; + /// Middlewares /// /// Submodule containing Cyrkensia middlewares. @@ -6,4 +11,57 @@ pub mod middleware; /// Redirects /// /// Submodule containing Cyrkensia redirects. -pub mod redirect; \ No newline at end of file +pub mod redirect; + + +/// Routes +/// +/// Submodule containing Cyrkensia routes. +pub mod routes; + +/// Cyrkensia State +/// +/// State for the Actix-Web server. Used in [routes]. +pub struct CyrkensiaState { + /// Config + /// + /// The loaded Config (read-only) + pub config: Config, + + /// Hostinfo + /// + /// The latest generated [Hostinfo]. + /// Only used if caching is activated. + pub hostinfo: Mutex>, + + /// Last Hostinfo Update + /// + /// The [timestamp](Instant) when the [hostinfo] was last updated. + /// `.elapsed().as_secs()` will be used to compare it with the `max_age` in the [Config]. + /// Only used if caching is activated. + pub last_updated: Mutex> +} + +impl CyrkensiaState { + /// Constructur + /// + /// Creates a new [CyrkensiaState] with given [Config]. + pub fn new(cfg: Config) -> io::Result { + if cfg.max_age.is_some() { + // State with caching + let hostinfo = Hostinfo::generate(cfg.clone())?; + return Ok(CyrkensiaState { + last_updated: Mutex::new(Some(Instant::now())), + hostinfo: Mutex::new(Some(hostinfo)), + config: cfg + }); + } + + // State without caching + Ok(CyrkensiaState { + hostinfo: Mutex::new(None), + last_updated: Mutex::new(None), + config: cfg, + }) + } +} \ No newline at end of file diff --git a/src/server/routes.rs b/src/server/routes.rs new file mode 100644 index 0000000..e69de29 From a6fdf19fb9ad2044290aecc645519222cb4e51fa Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Mon, 14 Nov 2022 21:15:32 +0100 Subject: [PATCH 15/36] Add multi-root option --- src/config.rs | 8 ++++---- src/hostinfo.rs | 6 +++++- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/src/config.rs b/src/config.rs index e4642c3..2215eb3 100644 --- a/src/config.rs +++ b/src/config.rs @@ -17,10 +17,10 @@ pub struct Config { /// The display name of the repository. pub name: String, - /// File root + /// File roots /// - /// The file root where all albums are stored. - pub root: String, + /// The file roots where all albums are stored. + pub root: Vec, /// UUIDv4 /// @@ -85,7 +85,7 @@ impl From for Config { fn from(x: Hostinfo) -> Config { Config { name: x.name, - root: "".to_string(), + root: Vec::new(), uuid: x.uuid, icon: x.icon, htpasswd: None, diff --git a/src/hostinfo.rs b/src/hostinfo.rs index 6afa4ed..1c40524 100644 --- a/src/hostinfo.rs +++ b/src/hostinfo.rs @@ -81,7 +81,11 @@ impl Hostinfo { /// /// Generates a Hostinfo based on a [Config]. pub fn generate(cfg: Config) -> io::Result { - let albums = Hostinfo::read_albums(cfg.root.as_str())?; + let mut albums: Vec = Vec::new(); + for rootpath in &cfg.root { + let album_slice = Hostinfo::read_albums(rootpath)?; + albums.extend(album_slice); + } let mut hostinfo = Hostinfo::from(cfg); hostinfo.size = albums.iter().map(|x| x.size).sum(); hostinfo.albums = albums; From 4bafa1eb75eea0a105cd7b3ef3ec9a2f80c13cc5 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 15 Nov 2022 22:44:07 +0100 Subject: [PATCH 16/36] Added hostinfo route and route utils --- src/album.rs | 2 +- src/artist.rs | 2 +- src/config.rs | 4 ++-- src/hostinfo.rs | 6 +++--- src/server/mod.rs | 43 ++++++++++++++++++++++++++++++------- src/server/responses.rs | 41 +++++++++++++++++++++++++++++++++++ src/server/routes.rs | 47 +++++++++++++++++++++++++++++++++++++++++ 7 files changed, 130 insertions(+), 15 deletions(-) create mode 100644 src/server/responses.rs diff --git a/src/album.rs b/src/album.rs index 5357411..dce30b8 100644 --- a/src/album.rs +++ b/src/album.rs @@ -6,7 +6,7 @@ use super::{Artist, Metadata, add_vec, remove_vec}; /// Album /// /// A struct representing an album of the Cyrkensia repository. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct Album { /// Name /// diff --git a/src/artist.rs b/src/artist.rs index b715dfa..fffef9e 100644 --- a/src/artist.rs +++ b/src/artist.rs @@ -7,7 +7,7 @@ use super::{Owner, add_vec, remove_vec}; /// Artist /// /// A struct representing an author or artist of a song. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct Artist { pub name: String, diff --git a/src/config.rs b/src/config.rs index 2215eb3..0903cba 100644 --- a/src/config.rs +++ b/src/config.rs @@ -59,9 +59,9 @@ pub struct Config { /// Maximum Age /// - /// The maximum age of the [Hostinfo] in milliseconds as a [u32]. If [None], the Hostinfo will always be regenerated when its route is accessed. + /// The maximum age of the [Hostinfo] in milliseconds as a [u64]. If [None], the Hostinfo will always be regenerated when its route is accessed. /// This basically activates caching. - pub max_age: Option + pub max_age: Option } impl Config { diff --git a/src/hostinfo.rs b/src/hostinfo.rs index 1c40524..1ea45e6 100644 --- a/src/hostinfo.rs +++ b/src/hostinfo.rs @@ -10,7 +10,7 @@ use super::{Owner, Album, Config, Metadata}; /// Hostinfo /// /// A struct representing the metadata or hostinfo and index of a Cyrkensia repository. -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Serialize, Deserialize, Clone)] pub struct Hostinfo { /// Name /// @@ -80,13 +80,13 @@ impl Hostinfo { /// Generate Hostinfo /// /// Generates a Hostinfo based on a [Config]. - pub fn generate(cfg: Config) -> io::Result { + pub fn generate(cfg: &Config) -> io::Result { let mut albums: Vec = Vec::new(); for rootpath in &cfg.root { let album_slice = Hostinfo::read_albums(rootpath)?; albums.extend(album_slice); } - let mut hostinfo = Hostinfo::from(cfg); + let mut hostinfo = Hostinfo::from(cfg.clone()); hostinfo.size = albums.iter().map(|x| x.size).sum(); hostinfo.albums = albums; Ok(hostinfo) diff --git a/src/server/mod.rs b/src/server/mod.rs index 4f83728..a773f24 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,4 +1,6 @@ +use actix_web::http::Uri; use crate::{Hostinfo, Config}; +use std::fmt::Write; use std::sync::Mutex; use std::time::Instant; use std::io; @@ -19,6 +21,11 @@ pub mod redirect; /// Submodule containing Cyrkensia routes. pub mod routes; +/// Responses +/// +/// Submodue containing Cyrkensia responses. +pub mod responses; + /// Cyrkensia State /// /// State for the Actix-Web server. Used in [routes]. @@ -32,14 +39,14 @@ pub struct CyrkensiaState { /// /// The latest generated [Hostinfo]. /// Only used if caching is activated. - pub hostinfo: Mutex>, + pub hostinfo: Mutex, /// Last Hostinfo Update /// /// The [timestamp](Instant) when the [hostinfo] was last updated. /// `.elapsed().as_secs()` will be used to compare it with the `max_age` in the [Config]. /// Only used if caching is activated. - pub last_updated: Mutex> + pub last_updated: Mutex } impl CyrkensiaState { @@ -47,21 +54,41 @@ impl CyrkensiaState { /// /// Creates a new [CyrkensiaState] with given [Config]. pub fn new(cfg: Config) -> io::Result { + // State with caching if cfg.max_age.is_some() { - // State with caching - let hostinfo = Hostinfo::generate(cfg.clone())?; + let hostinfo = Hostinfo::generate(&cfg)?; return Ok(CyrkensiaState { - last_updated: Mutex::new(Some(Instant::now())), - hostinfo: Mutex::new(Some(hostinfo)), + last_updated: Mutex::new(Instant::now()), + hostinfo: Mutex::new(hostinfo), config: cfg }); } // State without caching Ok(CyrkensiaState { - hostinfo: Mutex::new(None), - last_updated: Mutex::new(None), + hostinfo: Mutex::new(Hostinfo::empty()), + last_updated: Mutex::new(Instant::now()), config: cfg, }) } +} + +/// Uri Display without Query +/// +/// Displays a Uri without the query parameters +pub fn uri_noquery(uri: &Uri) -> String { + let mut f = String::new(); + + // Protocol + if let Some(scheme) = uri.scheme() { + let _ = write!(&mut f, "{}://", scheme); + } + // Server + if let Some(authority) = uri.authority() { + let _ = write!(&mut f, "{}", authority); + } + // Path + let _ = write!(&mut f, "{}", uri.path()); + + f } \ No newline at end of file diff --git a/src/server/responses.rs b/src/server/responses.rs new file mode 100644 index 0000000..cd628ab --- /dev/null +++ b/src/server/responses.rs @@ -0,0 +1,41 @@ +use std::io; +use actix_web::{HttpResponse, body::MessageBody}; +use actix_web::http::header::{ContentType, CONTENT_LENGTH}; +use crate::{Config, Hostinfo}; + +/// Hostinfo from Config +/// +/// Attempts to create a [HttpResponse] from a generated [Hostinfo] by a [Config]. +pub fn hostinfo_json(cfg: &Config) -> io::Result { + // Generate Hostinfo + let hostinfo = Hostinfo::generate(cfg)?; + hostinfo_data(&hostinfo) +} + +/// Hostinfo from Data +/// +/// Attempts to create a [HttpResponse] from a [Hostinfo] struct. +pub fn hostinfo_data(hstinfo: &Hostinfo) -> io::Result { + // Convert to String + let raw_json = serde_json::to_string(hstinfo)?; + + // Return HttpReponse + Ok(HttpResponse::Ok() + .content_type(ContentType::json()) + .append_header( + (CONTENT_LENGTH, raw_json.len()) + ) + .body(raw_json)) +} + +/// HTTP Status 500 +/// +/// Returns a 500 Error with an optional body message +pub fn server_500(msg: Option) -> HttpResponse { + if let Some(message) = msg { + return HttpResponse::InternalServerError() + .body(message) + } + HttpResponse::InternalServerError() + .finish() +} \ No newline at end of file diff --git a/src/server/routes.rs b/src/server/routes.rs index e69de29..ab5d842 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -0,0 +1,47 @@ +use std::time::Instant; +use actix_web::{web, Responder, HttpRequest}; +use super::{CyrkensiaState, responses, uri_noquery}; +use crate::Hostinfo; + +/// Hostinfo Route +/// +/// Route for serving a [Hostinfo]. Server needs [CyrkensiaState] in `.app_data()` for this. +pub async fn hostinfo(req: HttpRequest, data: web::Data) -> impl Responder { + // Get config + let Some(delay) = data.config.max_age else { + // Ad hoch Hostinfo + let Ok(resp) = responses::hostinfo_json(&data.config) else { + return responses::server_500(Some("Failed to generate hostinfo")); + }; + return resp; + }; + + // Get last update timestamp and cached hostinfo + let Ok(mut last_updated) = data.last_updated.lock() else { + return responses::server_500(None::); + }; + let Ok(mut hostinfo) = data.hostinfo.lock() else { + return responses::server_500(None::); + }; + + if last_updated.elapsed().as_secs() >= delay { + // Generate new Hostinfo if expired + let Ok(new_hostinfo) = Hostinfo::generate(&data.config) else { + return responses::server_500(Some("Failed to update hostinfo")); + }; + + // Update Hostinfo and Timestamp + *hostinfo = new_hostinfo; + *last_updated = Instant::now(); + } + + // Set Origin URL + let mut final_hostinfo = hostinfo.clone(); + final_hostinfo.set_origin(uri_noquery(req.uri())); + + // Return final result + let Ok(finalres) = responses::hostinfo_data(&final_hostinfo) else { + return responses::server_500(Some("Failed to generate hostinfo")); + }; + finalres +} \ No newline at end of file From ee9b9cde51e96fe6ee1c5354087d8c8ac8864d84 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 15 Nov 2022 22:51:27 +0100 Subject: [PATCH 17/36] Version bump --- Cargo.lock | 67 ++++++++++++++++++++--------------------------- src/lib.rs | 1 - src/server/mod.rs | 2 +- 3 files changed, 29 insertions(+), 41 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 55e9253..0918e86 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -200,7 +200,7 @@ dependencies = [ "serde_urlencoded", "smallvec", "socket2", - "time 0.3.16", + "time 0.3.17", "url", ] @@ -328,18 +328,18 @@ checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db" [[package]] name = "bytestring" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "86b6a75fd3048808ef06af5cd79712be8111960adaf89d90250974b38fc3928a" +checksum = "f7f83e57d9154148e355404702e2694463241880b939570d7c97c014da7a69a1" dependencies = [ "bytes", ] [[package]] name = "cc" -version = "1.0.74" +version = "1.0.76" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "581f5dba903aac52ea3feb5ec4810848460ee833876f1f9b0fdeab1f19091574" +checksum = "76a284da2e6fe2092f2353e51713435363112dfd60030e22add80be333fb928f" dependencies = [ "jobserver", ] @@ -352,9 +352,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" -version = "0.4.22" +version = "0.4.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bfd4d1b31faaa3a89d7934dbded3111da0d2ef28e3ebccdb4f0179f5929d1ef1" +checksum = "16b0a3d9ed01224b22057780a37bb8c5dbfe1be8ba48678e7bf57ec4b385411f" dependencies = [ "iana-time-zone", "js-sys", @@ -388,7 +388,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "344adc371239ef32293cb1c4fe519592fcf21206c79c02854320afcdf3ab4917" dependencies = [ "percent-encoding", - "time 0.3.16", + "time 0.3.17", "version_check", ] @@ -428,9 +428,9 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.80" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b7d4e43b25d3c994662706a1d4fcfc32aaa6afd287502c111b237093bb23f3a" +checksum = "97abf9f0eca9e52b7f81b945524e76710e6cb2366aead23b7d4fbf72e281f888" dependencies = [ "cc", "cxxbridge-flags", @@ -440,9 +440,9 @@ dependencies = [ [[package]] name = "cxx-build" -version = "1.0.80" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "84f8829ddc213e2c1368e51a2564c552b65a8cb6a28f31e576270ac81d5e5827" +checksum = "7cc32cc5fea1d894b77d269ddb9f192110069a8a9c1f1d441195fba90553dea3" dependencies = [ "cc", "codespan-reporting", @@ -455,15 +455,15 @@ dependencies = [ [[package]] name = "cxxbridge-flags" -version = "1.0.80" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e72537424b474af1460806647c41d4b6d35d09ef7fe031c5c2fa5766047cc56a" +checksum = "8ca220e4794c934dc6b1207c3b42856ad4c302f2df1712e9f8d2eec5afaacf1f" [[package]] name = "cxxbridge-macro" -version = "1.0.80" +version = "1.0.81" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "309e4fb93eed90e1e14bea0da16b209f81813ba9fc7830c20ed151dd7bc0a4d7" +checksum = "b846f081361125bfc8dc9d3940c84e1fd83ba54bbca7b17cd29483c828be0704" dependencies = [ "proc-macro2", "quote", @@ -826,23 +826,14 @@ dependencies = [ [[package]] name = "num_cpus" -version = "1.13.1" +version = "1.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" +checksum = "f6058e64324c71e02bc2b150e4f3bc8286db6c83092132ffa3f6b1eab0f9def5" dependencies = [ "hermit-abi", "libc", ] -[[package]] -name = "num_threads" -version = "0.1.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" -dependencies = [ - "libc", -] - [[package]] name = "once_cell" version = "1.16.0" @@ -898,9 +889,9 @@ checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "ppv-lite86" -version = "0.2.16" +version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872" +checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "proc-macro2" @@ -961,9 +952,9 @@ dependencies = [ [[package]] name = "regex" -version = "1.6.0" +version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c4eb3267174b8c6c2f654116623910a0fef09c4753f8dd83db29c48a0df988b" +checksum = "e076559ef8e241f2ae3479e36f97bd5741c0330689e217ad51ce2c76808b868a" dependencies = [ "aho-corasick", "memchr", @@ -972,9 +963,9 @@ dependencies = [ [[package]] name = "regex-syntax" -version = "0.6.27" +version = "0.6.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3f87b73ce11b1619a3c6332f45341e0047173771e8b8b73f87bfeefb7b56244" +checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" [[package]] name = "ring" @@ -1173,13 +1164,11 @@ dependencies = [ [[package]] name = "time" -version = "0.3.16" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fab5c8b9980850e06d92ddbe3ab839c062c801f3927c0fb8abd6fc8e918fbca" +checksum = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376" dependencies = [ "itoa", - "libc", - "num_threads", "serde", "time-core", "time-macros", @@ -1193,9 +1182,9 @@ checksum = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd" [[package]] name = "time-macros" -version = "0.2.5" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "65bb801831d812c562ae7d2bfb531f26e66e4e1f6b17307ba4149c5064710e5b" +checksum = "d967f99f534ca7e495c575c62638eebc2898a8c84c119b89e250477bc4ba16b2" dependencies = [ "time-core", ] diff --git a/src/lib.rs b/src/lib.rs index 16f92d3..5e3f264 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -86,7 +86,6 @@ pub mod meta { /// Server Routes /// /// This submodule contains middlewares and other tools needed only for the Cyrkensia server. -/// Note that the routes that Cyrkensia uses are directly in the `cyrkensia` binary due to technical obstacles. pub mod server; /// Remove from [Vec] diff --git a/src/server/mod.rs b/src/server/mod.rs index a773f24..e09ce53 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -43,7 +43,7 @@ pub struct CyrkensiaState { /// Last Hostinfo Update /// - /// The [timestamp](Instant) when the [hostinfo] was last updated. + /// The [timestamp](Instant) when the [Hostinfo] was last updated. /// `.elapsed().as_secs()` will be used to compare it with the `max_age` in the [Config]. /// Only used if caching is activated. pub last_updated: Mutex From 7ec7065a300d8658f3fb7b65f34b391bf1d44a64 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Tue, 15 Nov 2022 22:56:24 +0100 Subject: [PATCH 18/36] i forgor borrow --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 5e3f264..e7d7bfe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,7 +27,7 @@ //! // Load the config file //! let config = Config::load_file("config.json").unwrap(); //! // Generate the corresponding Hostinfo -//! let mut hostinfo = Hostinfo::generate(config).unwrap(); +//! let mut hostinfo = Hostinfo::generate(&config).unwrap(); //! // Optionally set the origin //! hostinfo.set_origin("https://foo.bar/my-hostinfo.json".to_string()); //! ``` From 2615a0678c7d1ba928058d7d5bda4ecd16a9b22f Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Thu, 24 Nov 2022 22:17:01 +0100 Subject: [PATCH 19/36] Better Metadata structure --- Cargo.lock | 67 ++++++++++++++++++++--------------- Cargo.toml | 1 + src/album.rs | 55 ++++------------------------- src/artist.rs | 78 +++++++++++++++++++---------------------- src/config.rs | 3 +- src/hostinfo.rs | 68 +++++++++++++++++++++++------------ src/lib.rs | 22 +----------- src/metadata.rs | 39 +++++++++------------ src/server/mod.rs | 18 +++++++--- src/server/responses.rs | 6 ++-- src/server/routes.rs | 4 +-- 11 files changed, 168 insertions(+), 193 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0918e86..9e74775 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -235,9 +235,9 @@ dependencies = [ [[package]] name = "aho-corasick" -version = "0.7.19" +version = "0.7.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4f55bd91a0978cbfd91c457a164bab8b4001c833b7f323132c0a4e1922dd44e" +checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" dependencies = [ "memchr", ] @@ -322,9 +322,9 @@ checksum = "572f695136211188308f16ad2ca5c851a712c464060ae6974944458eb83880ba" [[package]] name = "bytes" -version = "1.2.1" +version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ec8a7b6a70fde80372154c65702f00a0f56f3e1c36abbc6c440484be248856db" +checksum = "dfb24e866b15a1af2a1b663f10c6b6b8f397a84aadb828f12e5b289ec23a3a3c" [[package]] name = "bytestring" @@ -337,9 +337,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.76" +version = "1.0.77" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76a284da2e6fe2092f2353e51713435363112dfd60030e22add80be333fb928f" +checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4" dependencies = [ "jobserver", ] @@ -428,9 +428,9 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.81" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97abf9f0eca9e52b7f81b945524e76710e6cb2366aead23b7d4fbf72e281f888" +checksum = "d4a41a86530d0fe7f5d9ea779916b7cadd2d4f9add748b99c2c029cbbdfaf453" dependencies = [ "cc", "cxxbridge-flags", @@ -440,9 +440,9 @@ dependencies = [ [[package]] name = "cxx-build" -version = "1.0.81" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7cc32cc5fea1d894b77d269ddb9f192110069a8a9c1f1d441195fba90553dea3" +checksum = "06416d667ff3e3ad2df1cd8cd8afae5da26cf9cec4d0825040f88b5ca659a2f0" dependencies = [ "cc", "codespan-reporting", @@ -455,15 +455,15 @@ dependencies = [ [[package]] name = "cxxbridge-flags" -version = "1.0.81" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ca220e4794c934dc6b1207c3b42856ad4c302f2df1712e9f8d2eec5afaacf1f" +checksum = "820a9a2af1669deeef27cb271f476ffd196a2c4b6731336011e0ba63e2c7cf71" [[package]] name = "cxxbridge-macro" -version = "1.0.81" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b846f081361125bfc8dc9d3940c84e1fd83ba54bbca7b17cd29483c828be0704" +checksum = "a08a6e2fcc370a089ad3b4aaf54db3b1b4cee38ddabce5896b33eb693275f470" dependencies = [ "proc-macro2", "quote", @@ -479,6 +479,7 @@ dependencies = [ "chrono", "serde", "serde_json", + "uuid", ] [[package]] @@ -496,9 +497,9 @@ dependencies = [ [[package]] name = "digest" -version = "0.10.5" +version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adfbc57365a37acbd2ebf2b64d7e69bb766e2fea813521ed536f5d0520dcf86c" +checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f" dependencies = [ "block-buffer", "crypto-common", @@ -515,9 +516,9 @@ dependencies = [ [[package]] name = "flate2" -version = "1.0.24" +version = "1.0.25" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f82b0f4c27ad9f8bfd1f3208d882da2b09c301bc1c828fd3a00d0216d2fbbff6" +checksum = "a8a2db397cb1c8772f31494cb8917e48cd1e64f0fa7efac59fbd741a0a8ce841" dependencies = [ "crc32fast", "miniz_oxide", @@ -682,9 +683,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "1.9.1" +version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10a35a97730320ffe8e2d410b5d3b69279b98d2c14bdb8b70ea89ecf7888d41e" +checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399" dependencies = [ "autocfg", "hashbrown", @@ -786,9 +787,9 @@ checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" [[package]] name = "miniz_oxide" -version = "0.5.4" +version = "0.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "96590ba8f175222643a85693f33d26e9c8a015f599c216509b1a6894af675d34" +checksum = "b275950c28b37e794e8c55d88aeb5e139d0ce23fdbbeda68f8d7174abdf9e8fa" dependencies = [ "adler", ] @@ -1059,9 +1060,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.87" +version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ce777b7b150d76b9cf60d28b55f5847135a003f7d7350c6be7a773508ce7d45" +checksum = "020ff22c755c2ed3f8cf162dbb41a7268d934702f3ed3631656ea597e08fc3db" dependencies = [ "itoa", "ryu", @@ -1206,9 +1207,9 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" [[package]] name = "tokio" -version = "1.21.2" +version = "1.22.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9e03c497dc955702ba729190dc4aac6f2a0ce97f913e5b1b5912fc5039d9099" +checksum = "d76ce4a75fb488c605c54bf610f221cea8b0dafb53333c1a67e8ee199dcd2ae3" dependencies = [ "autocfg", "bytes", @@ -1318,6 +1319,16 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "uuid" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "422ee0de9031b5b948b97a8fc04e3aa35230001a722ddd27943e0be31564ce4c" +dependencies = [ + "getrandom", + "serde", +] + [[package]] name = "version_check" version = "0.9.4" @@ -1528,9 +1539,9 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.0.1+zstd.1.5.2" +version = "2.0.3+zstd.1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fd07cbbc53846d9145dbffdf6dd09a7a0aa52be46741825f5c97bdd4f73f12b" +checksum = "44ccf97612ac95f3ccb89b2d7346b345e52f1c3019be4984f0455fb4ba991f8a" dependencies = [ "cc", "libc", diff --git a/Cargo.toml b/Cargo.toml index 6727c0f..7a9447e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -18,6 +18,7 @@ keywords = [] # Main crate serde = { version = "1", features = ["derive"] } serde_json = "1" +uuid = { version = "1.2", features = ["v4", "serde"] } # Server only actix-web = { version = "4", optional = true, features = ["rustls"] } actix-cors = { version = "0.6", optional = true} diff --git a/src/album.rs b/src/album.rs index dce30b8..47670ff 100644 --- a/src/album.rs +++ b/src/album.rs @@ -1,7 +1,9 @@ use serde::{Serialize, Deserialize}; +use uuid::Uuid; use std::cmp::PartialEq; +use std::collections::HashMap; use std::convert::From; -use super::{Artist, Metadata, add_vec, remove_vec}; +use super::Metadata; /// Album /// @@ -23,15 +25,10 @@ pub struct Album { /// The relative path of the album. pub path: String, - /// Artists - /// - /// The Artists of the album. - pub artists: Vec, - /// Files /// /// All files present in the album as a relative path. - pub files: Vec, + pub files: HashMap>, /// Size /// @@ -43,54 +40,18 @@ impl Album { /// New Album /// /// Creates a new album. If `artists` or `files` is [None], an empty array will be created for them. - pub fn new(name: String, cover: String, path: String, artists: Option>, files: Option>, size: u128) -> Album { + pub fn new(name: String, cover: String, path: String, files: Option>>, size: u128) -> Album { Album { name, cover, path, - artists: match artists { - Some(x) => x, - None => Vec::new() - }, files: match files { Some(x) => x, - None => Vec::new() + None => HashMap::new() }, size } } - - /// Add [Artist] - /// - /// Adds an [Artist] to the album if they don't exist already. - pub fn add_artist(&mut self, art: Artist) -> &mut Album { - add_vec(&mut self.artists, art); - self - } - - /// Add file - /// - /// Adds a file to the album if it doesn't exist already. - pub fn add_file(&mut self, file: String) -> &mut Album { - add_vec(&mut self.files, file); - self - } - - /// Remove [Artist] - /// - /// Removes an [Artist] from the album if they already exist. - pub fn remove_artist(&mut self, art: Artist) -> &mut Album { - remove_vec(&mut self.artists, art); - self - } - - /// Remove file - /// - /// Removes a file from the album if it already exists. - pub fn remove_file(&mut self, file: String) -> &mut Album { - remove_vec(&mut self.files, file); - self - } } impl From for Album { @@ -99,8 +60,7 @@ impl From for Album { name: x.name, cover: x.cover, path: "".to_string(), - artists: x.artists, - files: Vec::new(), + files: x.artists, size: 0 } } @@ -111,7 +71,6 @@ impl PartialEq for Album { self.name == other.name && self.cover == other.cover && self.path == other.path && - self.artists == other.artists && self.files == other.files && self.size == other.size } diff --git a/src/artist.rs b/src/artist.rs index fffef9e..76bb2b6 100644 --- a/src/artist.rs +++ b/src/artist.rs @@ -1,12 +1,17 @@ use serde::{Serialize, Deserialize}; +use uuid::Uuid; use std::fmt::{Display, Result}; use std::cmp::PartialEq; use std::convert::From; -use super::{Owner, add_vec, remove_vec}; +use std::path::{Path, PathBuf}; +use std::fs; +use std::io; +use super::Owner; /// Artist /// /// A struct representing an author or artist of a song. +/// An array of this is stored in a root of a Cyrkensia repository as a `.artists.json` file. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Artist { pub name: String, @@ -16,60 +21,53 @@ pub struct Artist { /// The website of the artist. pub website: Option, - /// Own music + /// Uuid /// - /// List of files (music) that the artist made. - pub music: Vec, - - /// Features - /// - /// List of files (music) that the artist was featured in. - pub features: Vec + /// The artist's UUID + pub uuid: Uuid } impl Artist { /// New Artist /// /// Creates a new Artist - pub fn new(name: String, website: Option, music: Vec, features: Vec) -> Artist { + pub fn new(name: String, website: Option, uuid: Uuid) -> Artist { Artist { name, website, - music, - features + uuid } } - /// Add music - /// - /// Adds a new music entry if it doesn't exist already - pub fn add_music(&mut self, music: String) -> &mut Artist { - add_vec(&mut self.music, music); - self - } - - /// Add feature + /// Load single .artists.json /// - /// Adds a new featured entry if it doesn't exist already - pub fn add_feature(&mut self, featured: String) -> &mut Artist { - add_vec(&mut self.features, featured); - self + /// Loads a single `.artists.json` as a [Vec] of [Artist]s + pub fn load_artists(path: impl AsRef) -> io::Result> { + let rawdata = fs::read_to_string(path)?; + Ok(serde_json::from_str(rawdata.as_str())?) } - /// Remove music + /// Load multiple .artists.json /// - /// Removes a music entry if it exists - pub fn remove_music(&mut self, music: String) -> &mut Artist { - remove_vec(&mut self.music, music); - self + /// Loads multiple `.artists.json` as a combined [Vec] of [Artist]s + pub fn load_multiple_artists(paths: Vec>) -> io::Result> { + let mut res: Vec = Vec::new(); + for pth in paths { + let artst = Artist::load_artists(pth)?; + res.extend(artst); + } + Ok(res) } - /// Remove feature + /// Read multiple folders' .artists.json /// - /// Removes a featured entry if it exists - pub fn remove_feature(&mut self, featured: String) -> &mut Artist { - remove_vec(&mut self.features, featured); - self + /// Reads the .artists.json of multiple folders. Essentially like [load_multiple_artists], but with `.artists.json` appended. + pub fn read_multiple(paths: &[String]) -> io::Result> { + let conv_paths: Vec = paths.iter() + .map(|x| Path::new(x).join(".artists.json")).collect(); + + // Read all artists + Artist::load_multiple_artists(conv_paths) } } @@ -78,8 +76,7 @@ impl From for Artist { Artist { name: x.name, website: x.website, - music: Vec::new(), - features: Vec::new() + uuid: Uuid::new_v4() } } } @@ -87,9 +84,9 @@ impl From for Artist { impl Display for Artist { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result { if let Some(web) = self.website.clone() { - write!(f, "{} ({})", self.name, web) + write!(f, "{} ({}) {}", self.name, web, self.uuid) } else { - write!(f, "{}", self.name) + write!(f, "{} {}", self.name, self.uuid) } } } @@ -98,7 +95,6 @@ impl PartialEq for Artist { fn eq(&self, other: &Self) -> bool { self.name == other.name && self.website == other.website && - self.music == other.music && - self.features == other.features + self.uuid == other.uuid } } \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index 0903cba..f76a7d4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -5,6 +5,7 @@ use std::convert::From; use std::io; use std::fs; use std::path::Path; +use uuid::Uuid; use super::{Owner, Hostinfo}; /// Configuration @@ -25,7 +26,7 @@ pub struct Config { /// UUIDv4 /// /// The UUID of the repository. - pub uuid: String, + pub uuid: Uuid, /// Icon /// diff --git a/src/hostinfo.rs b/src/hostinfo.rs index 1ea45e6..40c3bdd 100644 --- a/src/hostinfo.rs +++ b/src/hostinfo.rs @@ -5,7 +5,8 @@ use std::ffi::OsString; use std::io; use std::fs; use std::path::{Path, PathBuf}; -use super::{Owner, Album, Config, Metadata}; +use uuid::Uuid; +use super::{Owner, Album, Config, Metadata, Artist}; /// Hostinfo /// @@ -25,7 +26,7 @@ pub struct Hostinfo { /// UUID /// /// The UUIDv4 of the repository. - pub uuid: String, + pub uuid: Uuid, /// Secured /// @@ -50,7 +51,12 @@ pub struct Hostinfo { /// Maintainers and Owners /// /// List of all repository maintainers/owners. - pub owners: Vec + pub owners: Vec, + + /// Featured Artists + /// + /// List of all [Artist]s in this repository. + pub artists: Vec } impl Hostinfo { @@ -68,19 +74,20 @@ impl Hostinfo { Hostinfo { name: "".to_string(), icon: "".to_string(), - uuid: "".to_string(), + uuid: Uuid::new_v4(), secured: false, size: 0, origin: "".to_string(), albums: Vec::new(), - owners: Vec::new() + owners: Vec::new(), + artists: Vec::new() } } /// Generate Hostinfo /// /// Generates a Hostinfo based on a [Config]. - pub fn generate(cfg: &Config) -> io::Result { + pub fn generate(cfg: &Config, arts: &Vec) -> io::Result { let mut albums: Vec = Vec::new(); for rootpath in &cfg.root { let album_slice = Hostinfo::read_albums(rootpath)?; @@ -89,6 +96,7 @@ impl Hostinfo { let mut hostinfo = Hostinfo::from(cfg.clone()); hostinfo.size = albums.iter().map(|x| x.size).sum(); hostinfo.albums = albums; + hostinfo.artists = arts.to_owned(); Ok(hostinfo) } @@ -128,23 +136,38 @@ impl Hostinfo { /// This is a wrapper for the second `.filter_map()` in [read_albums](Hostinfo::read_albums) since clojures don't allow the `?`. /// You can of course also use it if you desire. pub fn parse_album(path: &PathBuf, name: &OsString) -> io::Result { - if let Some(fname) = name.to_str() { - // Read data - let m = Metadata::load(path.join(".metadata.json"))?; - let c = Hostinfo::list_files(path)?; - - // Create Album - return Ok(Album { - name: m.name, - cover: m.cover, - artists: m.artists, - path: fname.to_string(), - files: c.0, - size: c.1, - }); + let Some(fname) = name.to_str() else { + // Return NotFound error + return Err(io::Error::new(io::ErrorKind::NotFound, "The OsString could not be parsed to a String")); + }; + + // Read data + let mut m = Metadata::load(path.join(".metadata.json"))?; + let c = Hostinfo::list_files(path)?; + + // List files with default Artist + if let Some(defart) = m.default { + for file in c.0 { + if let Some(other_arts) = m.artists.get_mut(&file) { + // Add default Artist to listed file if it's not included yet + if other_arts.contains(&defart) { + other_arts.push(defart); + } + } else { + // Append all yet unlisted files + m.artists.insert(file, vec![defart]); + } + } } - // Return NotFound error by default - Err(io::Error::new(io::ErrorKind::NotFound, "The OsString could not be parsed to a String")) + + // Create Album + Ok(Album { + name: m.name, + cover: m.cover, + path: fname.to_string(), + files: m.artists, + size: c.1, + }) } /// List files @@ -210,6 +233,7 @@ impl From for Hostinfo { origin: "".to_string(), albums: Vec::new(), owners: x.owners, + artists: Vec::new() } } } diff --git a/src/lib.rs b/src/lib.rs index e7d7bfe..5bc1e71 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -32,8 +32,6 @@ //! hostinfo.set_origin("https://foo.bar/my-hostinfo.json".to_string()); //! ``` -use std::cmp::PartialEq; - /// Owner struct mod owner; pub use self::owner::Owner; @@ -86,22 +84,4 @@ pub mod meta { /// Server Routes /// /// This submodule contains middlewares and other tools needed only for the Cyrkensia server. -pub mod server; - -/// Remove from [Vec] -/// -/// Removes an element from a [Vec], if it exists already, without returning a new [Vec]. -pub(crate) fn remove_vec(arr: &mut Vec, elm: T) { - if let Some(i) = arr.iter().position(|x| *x == elm) { - arr.remove(i); - } -} - -/// Add to [Vec] -/// -/// Adds an element to a [Vec], if the element doesn't exist yet, without returning a new [Vec]. -pub(crate) fn add_vec(arr: &mut Vec, elm: T) { - if !arr.contains(&elm) { - arr.push(elm); - } -} \ No newline at end of file +pub mod server; \ No newline at end of file diff --git a/src/metadata.rs b/src/metadata.rs index 66cc31d..ff790bc 100644 --- a/src/metadata.rs +++ b/src/metadata.rs @@ -1,12 +1,14 @@ use serde::{Serialize, Deserialize}; use serde_json::from_str; +use uuid::Uuid; +use std::collections::HashMap; use std::fmt::{Display, Result}; use std::cmp::PartialEq; use std::convert::From; use std::path::Path; use std::fs; use std::io; -use super::{Artist, Album, add_vec, remove_vec}; +use super::Album; /// .metdata.json /// @@ -23,23 +25,29 @@ pub struct Metadata { /// The asset key representing the album cover art. pub cover: String, - /// Artists + /// Default Artist /// - /// List of [Artist]s in this album. - pub artists: Vec + /// Represents the UUIDv4 of the main [Artist] of this album + pub default: Option, + + /// Additional Artists + /// + /// Map of which additional artists are associated with what music track + pub artists: HashMap> } impl Metadata { /// New Metadata /// /// Creates new [Metadata]. Authors can be appended later on. - pub fn new(name: String, cover: String, artists: Option>) -> Metadata { + pub fn new(name: String, cover: String, default_artist: Option, artists: Option>>) -> Metadata { Metadata { name, cover, + default: default_artist, artists: match artists { Some(x) => x, - None => Vec::new() + None => HashMap::new() } } } @@ -51,22 +59,6 @@ impl Metadata { let data = fs::read_to_string(path)?; Ok(from_str(data.as_str())?) } - - /// Add Artist - /// - /// Adds an [Artist], if they don't exist yet. - pub fn add_artist(&mut self, art: Artist) -> &mut Metadata { - add_vec(&mut self.artists, art); - self - } - - /// Remove Artist - /// - /// Removes an [Artist], if they already exist. - pub fn remove_artist(&mut self, art: Artist) -> &mut Metadata { - remove_vec(&mut self.artists, art); - self - } } impl From for Metadata { @@ -74,7 +66,8 @@ impl From for Metadata { Metadata { name: x.name, cover: x.cover, - artists: x.artists + artists: x.files, + default: None } } } diff --git a/src/server/mod.rs b/src/server/mod.rs index e09ce53..884a09a 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,5 +1,5 @@ use actix_web::http::Uri; -use crate::{Hostinfo, Config}; +use crate::{Hostinfo, Config, Artist}; use std::fmt::Write; use std::sync::Mutex; use std::time::Instant; @@ -35,6 +35,11 @@ pub struct CyrkensiaState { /// The loaded Config (read-only) pub config: Config, + /// Artists + /// + /// The loaded Artists (read-only) + pub artists: Vec, + /// Hostinfo /// /// The latest generated [Hostinfo]. @@ -53,14 +58,18 @@ impl CyrkensiaState { /// Constructur /// /// Creates a new [CyrkensiaState] with given [Config]. - pub fn new(cfg: Config) -> io::Result { + pub fn new(cfg: Config) -> io::Result { + // Read all artists + let arts = Artist::read_multiple(&cfg.root)?; + // State with caching if cfg.max_age.is_some() { - let hostinfo = Hostinfo::generate(&cfg)?; + let hostinfo = Hostinfo::generate(&cfg, &arts)?; return Ok(CyrkensiaState { last_updated: Mutex::new(Instant::now()), hostinfo: Mutex::new(hostinfo), - config: cfg + config: cfg, + artists: arts }); } @@ -69,6 +78,7 @@ impl CyrkensiaState { hostinfo: Mutex::new(Hostinfo::empty()), last_updated: Mutex::new(Instant::now()), config: cfg, + artists: arts }) } } diff --git a/src/server/responses.rs b/src/server/responses.rs index cd628ab..56a0127 100644 --- a/src/server/responses.rs +++ b/src/server/responses.rs @@ -1,14 +1,14 @@ use std::io; use actix_web::{HttpResponse, body::MessageBody}; use actix_web::http::header::{ContentType, CONTENT_LENGTH}; -use crate::{Config, Hostinfo}; +use crate::{Config, Hostinfo, Artist}; /// Hostinfo from Config /// /// Attempts to create a [HttpResponse] from a generated [Hostinfo] by a [Config]. -pub fn hostinfo_json(cfg: &Config) -> io::Result { +pub fn hostinfo_json(cfg: &Config, arts: &Vec) -> io::Result { // Generate Hostinfo - let hostinfo = Hostinfo::generate(cfg)?; + let hostinfo = Hostinfo::generate(cfg, arts)?; hostinfo_data(&hostinfo) } diff --git a/src/server/routes.rs b/src/server/routes.rs index ab5d842..5720e86 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -10,7 +10,7 @@ pub async fn hostinfo(req: HttpRequest, data: web::Data) -> impl // Get config let Some(delay) = data.config.max_age else { // Ad hoch Hostinfo - let Ok(resp) = responses::hostinfo_json(&data.config) else { + let Ok(resp) = responses::hostinfo_json(&data.config, &data.artists) else { return responses::server_500(Some("Failed to generate hostinfo")); }; return resp; @@ -26,7 +26,7 @@ pub async fn hostinfo(req: HttpRequest, data: web::Data) -> impl if last_updated.elapsed().as_secs() >= delay { // Generate new Hostinfo if expired - let Ok(new_hostinfo) = Hostinfo::generate(&data.config) else { + let Ok(new_hostinfo) = Hostinfo::generate(&data.config, &data.artists) else { return responses::server_500(Some("Failed to update hostinfo")); }; From 137b920ca4081d57ad7ad29fe845ba11ce9c39fe Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Fri, 25 Nov 2022 02:21:53 +0100 Subject: [PATCH 20/36] Fix doctest --- src/lib.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 5bc1e71..50e91cb 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -22,12 +22,14 @@ //! //! Reading a Config and generating its Hostinfo //! ```no_run -//! use cyrkensia::{Hostinfo, Config}; +//! use cyrkensia::{Hostinfo, Config, Artist}; //! //! // Load the config file //! let config = Config::load_file("config.json").unwrap(); +//! // Load the artists +//! let artists = Artist::read_multiple(&config.root).unwrap(); //! // Generate the corresponding Hostinfo -//! let mut hostinfo = Hostinfo::generate(&config).unwrap(); +//! let mut hostinfo = Hostinfo::generate(&config, &artists).unwrap(); //! // Optionally set the origin //! hostinfo.set_origin("https://foo.bar/my-hostinfo.json".to_string()); //! ``` From fb89f4008ae7851b1206d77ff5b3d391e93034c4 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Fri, 25 Nov 2022 02:35:43 +0100 Subject: [PATCH 21/36] Add Artists to State Cache as well --- src/server/mod.rs | 6 +++--- src/server/routes.rs | 23 ++++++++++++++++++----- 2 files changed, 21 insertions(+), 8 deletions(-) diff --git a/src/server/mod.rs b/src/server/mod.rs index 884a09a..eae65be 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -38,7 +38,7 @@ pub struct CyrkensiaState { /// Artists /// /// The loaded Artists (read-only) - pub artists: Vec, + pub artists: Mutex>, /// Hostinfo /// @@ -69,7 +69,7 @@ impl CyrkensiaState { last_updated: Mutex::new(Instant::now()), hostinfo: Mutex::new(hostinfo), config: cfg, - artists: arts + artists: Mutex::new(arts) }); } @@ -78,7 +78,7 @@ impl CyrkensiaState { hostinfo: Mutex::new(Hostinfo::empty()), last_updated: Mutex::new(Instant::now()), config: cfg, - artists: arts + artists: Mutex::new(arts) }) } } diff --git a/src/server/routes.rs b/src/server/routes.rs index 5720e86..5476805 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -1,7 +1,7 @@ use std::time::Instant; use actix_web::{web, Responder, HttpRequest}; use super::{CyrkensiaState, responses, uri_noquery}; -use crate::Hostinfo; +use crate::{Hostinfo, Artist}; /// Hostinfo Route /// @@ -10,27 +10,40 @@ pub async fn hostinfo(req: HttpRequest, data: web::Data) -> impl // Get config let Some(delay) = data.config.max_age else { // Ad hoch Hostinfo - let Ok(resp) = responses::hostinfo_json(&data.config, &data.artists) else { + let Ok(artists) = Artist::read_multiple(&data.config.root) else { + return responses::server_500(Some("Failed to generate hostinfo")); + }; + let Ok(resp) = responses::hostinfo_json(&data.config, &artists) else { return responses::server_500(Some("Failed to generate hostinfo")); }; return resp; }; - // Get last update timestamp and cached hostinfo + // Get last update timestamp and cached hostinfo and artists let Ok(mut last_updated) = data.last_updated.lock() else { return responses::server_500(None::); }; let Ok(mut hostinfo) = data.hostinfo.lock() else { return responses::server_500(None::); }; + let Ok(mut artists) = data.artists.lock() else { + return responses::server_500(None::); + }; + // Update Cache if expired if last_updated.elapsed().as_secs() >= delay { - // Generate new Hostinfo if expired - let Ok(new_hostinfo) = Hostinfo::generate(&data.config, &data.artists) else { + // Read updated artists + let Ok(new_artists) = Artist::read_multiple(&data.config.root) else { + return responses::server_500(Some("Failed to update hostinfo")); + }; + + // Generate new Hostinfo + let Ok(new_hostinfo) = Hostinfo::generate(&data.config, &artists) else { return responses::server_500(Some("Failed to update hostinfo")); }; // Update Hostinfo and Timestamp + *artists = new_artists; *hostinfo = new_hostinfo; *last_updated = Instant::now(); } From bf2062c3f54dbc0167a6ffaeebfade0163b66912 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Fri, 25 Nov 2022 17:53:37 +0100 Subject: [PATCH 22/36] Account struct finished along with wrapper functions --- Cargo.lock | 41 ++++ Cargo.toml | 10 +- build.rs | 20 +- src/accounts.rs | 84 ++++++++ src/album.rs | 102 ++++----- src/artist.rs | 132 ++++++------ src/bin/cyrkensia-cfg.rs | 2 +- src/bin/cyrkensia.rs | 14 +- src/config.rs | 158 +++++++------- src/hostinfo.rs | 454 +++++++++++++++++++-------------------- src/lib.rs | 44 ++-- src/metadata.rs | 106 ++++----- src/owner.rs | 108 +++++----- src/server/middleware.rs | 16 +- src/server/mod.rs | 120 +++++------ src/server/redirect.rs | 10 +- src/server/responses.rs | 38 ++-- src/server/routes.rs | 88 ++++---- 18 files changed, 842 insertions(+), 705 deletions(-) create mode 100644 src/accounts.rs diff --git a/Cargo.lock b/Cargo.lock index 9e74775..84c880b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -266,6 +266,18 @@ dependencies = [ "libc", ] +[[package]] +name = "arrayref" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544" + +[[package]] +name = "arrayvec" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6" + [[package]] name = "autocfg" version = "1.1.0" @@ -284,6 +296,20 @@ version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" +[[package]] +name = "blake3" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "895adc16c8b3273fbbc32685a7d55227705eda08c01e77704020f3491924b44b" +dependencies = [ + "arrayref", + "arrayvec", + "cc", + "cfg-if", + "constant_time_eq", + "digest", +] + [[package]] name = "block-buffer" version = "0.10.3" @@ -375,6 +401,12 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "constant_time_eq" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3ad85c1f65dc7b37604eb0e89748faf0b9653065f2a8ef69f96a687ec1e9279" + [[package]] name = "convert_case" version = "0.4.0" @@ -476,7 +508,9 @@ version = "1.2.0" dependencies = [ "actix-cors", "actix-web", + "blake3", "chrono", + "rand", "serde", "serde_json", "uuid", @@ -503,6 +537,7 @@ checksum = "8168378f4e5023e7218c89c891c0fd8ecdb5e5e4f18cb78f38cf245dd021e76f" dependencies = [ "block-buffer", "crypto-common", + "subtle", ] [[package]] @@ -1132,6 +1167,12 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" +[[package]] +name = "subtle" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" + [[package]] name = "syn" version = "1.0.103" diff --git a/Cargo.toml b/Cargo.toml index 7a9447e..4a41d2d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -19,13 +19,19 @@ keywords = [] serde = { version = "1", features = ["derive"] } serde_json = "1" uuid = { version = "1.2", features = ["v4", "serde"] } + # Server only actix-web = { version = "4", optional = true, features = ["rustls"] } -actix-cors = { version = "0.6", optional = true} +actix-cors = { version = "0.6", optional = true } + +# Accounts only +blake3 = { version = "1.3", optional = true } +rand = { version = "0.8", optional = true, features = ["std"] } [features] default = ["server"] -server = ["actix-web", "actix-cors"] +accounts = ["blake3", "rand"] +server = ["actix-web", "actix-cors", "accounts"] [build-dependencies] chrono = "0.4" diff --git a/build.rs b/build.rs index 2cd08d5..7aea4cf 100644 --- a/build.rs +++ b/build.rs @@ -3,19 +3,19 @@ use std::env; use chrono::Utc; fn version(name: &str) -> String { - let output = Command::new(name).arg("--version").output().unwrap(); - let raw = String::from_utf8(output.stdout).unwrap(); - raw.replace(&format!("{} ", name), "") + let output = Command::new(name).arg("--version").output().unwrap(); + let raw = String::from_utf8(output.stdout).unwrap(); + raw.replace(&format!("{} ", name), "") } fn main() { - // ----- Target Triple ----- - println!("cargo:rustc-env=TARGET={}", env::var("TARGET").unwrap()); + // ----- Target Triple ----- + println!("cargo:rustc-env=TARGET={}", env::var("TARGET").unwrap()); - // ----- Rust Version ----- - println!("cargo:rustc-env=CARGO_VERSION={}", version("cargo")); - println!("cargo:rustc-env=RUSTC_VERSION={}", version("rustc")); + // ----- Rust Version ----- + println!("cargo:rustc-env=CARGO_VERSION={}", version("cargo")); + println!("cargo:rustc-env=RUSTC_VERSION={}", version("rustc")); - // ----- Compile Date ----- - println!("cargo:rustc-env=COMPILE_DATE={}", Utc::now().format("%Y-%m-%d")); + // ----- Compile Date ----- + println!("cargo:rustc-env=COMPILE_DATE={}", Utc::now().format("%Y-%m-%d")); } \ No newline at end of file diff --git a/src/accounts.rs b/src/accounts.rs new file mode 100644 index 0000000..6058f39 --- /dev/null +++ b/src/accounts.rs @@ -0,0 +1,84 @@ +use serde::{Deserialize, Serialize}; +use rand::distributions::Alphanumeric; +use rand::{Rng, thread_rng}; +use blake3::{Hasher, OUT_LEN}; +use std::fmt::Display; + +#[derive(Debug, Deserialize, Serialize, Clone)] +pub struct Account { + /// Username + /// + /// The account username. + pub username: String, + + /// Password + /// + /// The BLAKE3-hashed password and salt. + pub password: String, + + /// Hash Salt + /// + /// The salt used for hashing. + pub salt: String +} + +impl Account { + /// New Account + /// + /// Creates a new account with a random salt and given password. + pub fn new(name: String, passwd: String) -> Account { + let salt = random_salt(); + Account { + username: name, + password: hash_passwd_salt(passwd, &salt), + salt + } + } + + /// Verify Password + /// + /// Verifies the Account against a given plaintext password. + pub fn verify(&self, passwd: String) -> bool { + let passhash = hash_passwd_salt(passwd, &self.salt); + passhash == self.password + } +} + +impl Display for Account { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}:{}", self.username, self.password) + } +} + +/// Hash input +/// +/// Hashes an input. The input has to append the salt itself. +/// Returns a formatted String representing the hash value. +pub fn hash(input: &[u8]) -> String { + let mut hasher = Hasher::new(); + hasher.update(input); + hasher.finalize().to_string() +} + +/// Hash Password with Salt +/// +/// Hashes the given password with given salt. +/// Wrapper for [hash]. +pub fn hash_passwd_salt(passwd: String, salt: &String) -> String { + // Get input and salt as bytes + let mut userpass: Vec = passwd.into(); + userpass.extend(salt.as_bytes()); + hash(&userpass) +} + +/// Random Salt +/// +/// Generates a random salt for the given bit length. +/// Note that `bits` should be a multiple of 8. +pub fn random_salt() -> String { + thread_rng() + .sample_iter(&Alphanumeric) + .take(OUT_LEN) + .map(char::from) + .collect() +} \ No newline at end of file diff --git a/src/album.rs b/src/album.rs index 47670ff..92ffbe8 100644 --- a/src/album.rs +++ b/src/album.rs @@ -10,68 +10,68 @@ use super::Metadata; /// A struct representing an album of the Cyrkensia repository. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Album { - /// Name - /// - /// The name of the album. - pub name: String, + /// Name + /// + /// The name of the album. + pub name: String, - /// Cover - /// - /// The album cover asset key. - pub cover: String, + /// Cover + /// + /// The album cover asset key. + pub cover: String, - /// Path - /// - /// The relative path of the album. - pub path: String, + /// Path + /// + /// The relative path of the album. + pub path: String, - /// Files - /// - /// All files present in the album as a relative path. - pub files: HashMap>, + /// Files + /// + /// All files present in the album as a relative path. + pub files: HashMap>, - /// Size - /// - /// The size of the Album. - pub size: u128 + /// Size + /// + /// The size of the Album. + pub size: u128 } impl Album { - /// New Album - /// - /// Creates a new album. If `artists` or `files` is [None], an empty array will be created for them. - pub fn new(name: String, cover: String, path: String, files: Option>>, size: u128) -> Album { - Album { - name, - cover, - path, - files: match files { - Some(x) => x, - None => HashMap::new() - }, - size - } - } + /// New Album + /// + /// Creates a new album. If `artists` or `files` is [None], an empty array will be created for them. + pub fn new(name: String, cover: String, path: String, files: Option>>, size: u128) -> Album { + Album { + name, + cover, + path, + files: match files { + Some(x) => x, + None => HashMap::new() + }, + size + } + } } impl From for Album { - fn from(x: Metadata) -> Album { - Album { - name: x.name, - cover: x.cover, - path: "".to_string(), - files: x.artists, - size: 0 - } - } + fn from(x: Metadata) -> Album { + Album { + name: x.name, + cover: x.cover, + path: "".to_string(), + files: x.artists, + size: 0 + } + } } impl PartialEq for Album { - fn eq(&self, other: &Self) -> bool { - self.name == other.name && - self.cover == other.cover && - self.path == other.path && - self.files == other.files && - self.size == other.size - } + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.cover == other.cover && + self.path == other.path && + self.files == other.files && + self.size == other.size + } } \ No newline at end of file diff --git a/src/artist.rs b/src/artist.rs index 76bb2b6..ddf10d9 100644 --- a/src/artist.rs +++ b/src/artist.rs @@ -14,87 +14,87 @@ use super::Owner; /// An array of this is stored in a root of a Cyrkensia repository as a `.artists.json` file. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Artist { - pub name: String, + pub name: String, - /// Website - /// - /// The website of the artist. - pub website: Option, + /// Website + /// + /// The website of the artist. + pub website: Option, - /// Uuid - /// - /// The artist's UUID - pub uuid: Uuid + /// Uuid + /// + /// The artist's UUID + pub uuid: Uuid } impl Artist { - /// New Artist - /// - /// Creates a new Artist - pub fn new(name: String, website: Option, uuid: Uuid) -> Artist { - Artist { - name, - website, - uuid - } - } + /// New Artist + /// + /// Creates a new Artist + pub fn new(name: String, website: Option, uuid: Uuid) -> Artist { + Artist { + name, + website, + uuid + } + } - /// Load single .artists.json - /// - /// Loads a single `.artists.json` as a [Vec] of [Artist]s - pub fn load_artists(path: impl AsRef) -> io::Result> { - let rawdata = fs::read_to_string(path)?; - Ok(serde_json::from_str(rawdata.as_str())?) - } + /// Load single .artists.json + /// + /// Loads a single `.artists.json` as a [Vec] of [Artist]s + pub fn load_artists(path: impl AsRef) -> io::Result> { + let rawdata = fs::read_to_string(path)?; + Ok(serde_json::from_str(rawdata.as_str())?) + } - /// Load multiple .artists.json - /// - /// Loads multiple `.artists.json` as a combined [Vec] of [Artist]s - pub fn load_multiple_artists(paths: Vec>) -> io::Result> { - let mut res: Vec = Vec::new(); - for pth in paths { - let artst = Artist::load_artists(pth)?; - res.extend(artst); - } - Ok(res) - } + /// Load multiple .artists.json + /// + /// Loads multiple `.artists.json` as a combined [Vec] of [Artist]s + pub fn load_multiple_artists(paths: Vec>) -> io::Result> { + let mut res: Vec = Vec::new(); + for pth in paths { + let artst = Artist::load_artists(pth)?; + res.extend(artst); + } + Ok(res) + } - /// Read multiple folders' .artists.json - /// - /// Reads the .artists.json of multiple folders. Essentially like [load_multiple_artists], but with `.artists.json` appended. - pub fn read_multiple(paths: &[String]) -> io::Result> { - let conv_paths: Vec = paths.iter() - .map(|x| Path::new(x).join(".artists.json")).collect(); - - // Read all artists - Artist::load_multiple_artists(conv_paths) - } + /// Read multiple folders' .artists.json + /// + /// Reads the .artists.json of multiple folders. Essentially like [load_multiple_artists], but with `.artists.json` appended. + pub fn read_multiple(paths: &[String]) -> io::Result> { + let conv_paths: Vec = paths.iter() + .map(|x| Path::new(x).join(".artists.json")).collect(); + + // Read all artists + Artist::load_multiple_artists(conv_paths) + } } impl From for Artist { - fn from(x: Owner) -> Artist { - Artist { - name: x.name, - website: x.website, - uuid: Uuid::new_v4() - } - } + fn from(x: Owner) -> Artist { + Artist { + name: x.name, + website: x.website, + uuid: Uuid::new_v4() + } + } } impl Display for Artist { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result { - if let Some(web) = self.website.clone() { - write!(f, "{} ({}) {}", self.name, web, self.uuid) - } else { - write!(f, "{} {}", self.name, self.uuid) - } - } + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result { + if let Some(web) = self.website.clone() { + write!(f, "{} ({}) {}", self.name, web, self.uuid) + } else { + write!(f, "{} {}", self.name, self.uuid) + } + } } impl PartialEq for Artist { - fn eq(&self, other: &Self) -> bool { - self.name == other.name && - self.website == other.website && - self.uuid == other.uuid - } + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.website == other.website && + self.uuid == other.uuid + } } \ No newline at end of file diff --git a/src/bin/cyrkensia-cfg.rs b/src/bin/cyrkensia-cfg.rs index 6d4d05e..db37e0d 100644 --- a/src/bin/cyrkensia-cfg.rs +++ b/src/bin/cyrkensia-cfg.rs @@ -1,3 +1,3 @@ fn main() { - println!("This is still WIP!!!"); + println!("This is still WIP!!!"); } \ No newline at end of file diff --git a/src/bin/cyrkensia.rs b/src/bin/cyrkensia.rs index d4c072d..29058aa 100644 --- a/src/bin/cyrkensia.rs +++ b/src/bin/cyrkensia.rs @@ -2,14 +2,14 @@ /*#[actix_web::main] async fn main() -> std::io::Result<()> { - HttpServer::new(|| { - App::new() - }) - .bind(("127.0.0.1", 8080))? - .run() - .await + HttpServer::new(|| { + App::new() + }) + .bind(("127.0.0.1", 8080))? + .run() + .await }*/ fn main() { - println!("This is still WIP!!!"); + println!("This is still WIP!!!"); } \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index f76a7d4..3a47074 100644 --- a/src/config.rs +++ b/src/config.rs @@ -13,102 +13,102 @@ use super::{Owner, Hostinfo}; /// The server configuration used for Cyrkensia. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Config { - /// Name - /// - /// The display name of the repository. - pub name: String, + /// Name + /// + /// The display name of the repository. + pub name: String, - /// File roots - /// - /// The file roots where all albums are stored. - pub root: Vec, + /// File roots + /// + /// The file roots where all albums are stored. + pub root: Vec, - /// UUIDv4 - /// - /// The UUID of the repository. - pub uuid: Uuid, + /// UUIDv4 + /// + /// The UUID of the repository. + pub uuid: Uuid, - /// Icon - /// - /// The Rich Presence asset key used for displaying the server. - pub icon: String, + /// Icon + /// + /// The Rich Presence asset key used for displaying the server. + pub icon: String, - /// Htpasswd file - /// - /// The path to the .htpasswd file for HTTP-Basic Authentication. If none is present, HTTP Basic Auth will be disabled. - pub htpasswd: Option, + /// Htpasswd file + /// + /// The path to the .htpasswd file for HTTP-Basic Authentication. If none is present, HTTP Basic Auth will be disabled. + pub htpasswd: Option, - /// Bind address - /// - /// The IP address to bind to, e.g. `127.0.0.1`, `0.0.0.0:80` or a Unix socket (Unix only). - pub bindaddr: String, + /// Bind address + /// + /// The IP address to bind to, e.g. `127.0.0.1`, `0.0.0.0:80` or a Unix socket (Unix only). + pub bindaddr: String, - /// TLS Certificate (Optional) - /// - /// The Path to the TLS certificate. TLS will only be activated if both certificate and key are provided. - pub tlscert: Option, + /// TLS Certificate (Optional) + /// + /// The Path to the TLS certificate. TLS will only be activated if both certificate and key are provided. + pub tlscert: Option, - /// TLS Key (Optional) - /// - /// The path to the TLS key. TLS will only be activated if both certificate and key are provided. - pub tlskey: Option, + /// TLS Key (Optional) + /// + /// The path to the TLS key. TLS will only be activated if both certificate and key are provided. + pub tlskey: Option, - /// Owners - /// - /// List of repository [maintainers](Owner) - pub owners: Vec, + /// Owners + /// + /// List of repository [maintainers](Owner) + pub owners: Vec, - /// Maximum Age - /// - /// The maximum age of the [Hostinfo] in milliseconds as a [u64]. If [None], the Hostinfo will always be regenerated when its route is accessed. - /// This basically activates caching. - pub max_age: Option + /// Maximum Age + /// + /// The maximum age of the [Hostinfo] in milliseconds as a [u64]. If [None], the Hostinfo will always be regenerated when its route is accessed. + /// This basically activates caching. + pub max_age: Option } impl Config { - /// Load Config File - /// - /// Loads a config from a file in the filesystem. - pub fn load_file(path: impl AsRef) -> io::Result { - let rawfile = fs::read_to_string(path)?; - Ok(from_str(rawfile.as_str())?) - } + /// Load Config File + /// + /// Loads a config from a file in the filesystem. + pub fn load_file(path: impl AsRef) -> io::Result { + let rawfile = fs::read_to_string(path)?; + Ok(from_str(rawfile.as_str())?) + } - /// Load Config JSON - /// - /// Loads a config from an already existing &[str]. - pub fn load_json(data: &str) -> io::Result { - Ok(from_str(data)?) - } + /// Load Config JSON + /// + /// Loads a config from an already existing &[str]. + pub fn load_json(data: &str) -> io::Result { + Ok(from_str(data)?) + } } impl From for Config { - fn from(x: Hostinfo) -> Config { - Config { - name: x.name, - root: Vec::new(), - uuid: x.uuid, - icon: x.icon, - htpasswd: None, - bindaddr: "".to_string(), - tlscert: None, - tlskey: None, - owners: x.owners, - max_age: None - } - } + fn from(x: Hostinfo) -> Config { + Config { + name: x.name, + root: Vec::new(), + uuid: x.uuid, + icon: x.icon, + htpasswd: None, + bindaddr: "".to_string(), + tlscert: None, + tlskey: None, + owners: x.owners, + max_age: None + } + } } impl PartialEq for Config { - fn eq(&self, other: &Self) -> bool { - self.name == other.name && - self.root == other.root && - self.uuid == other.uuid && - self.icon == other.icon && - self.htpasswd == other.htpasswd && - self.bindaddr == other.bindaddr && - self.tlscert == other.tlscert && - self.tlskey == other.tlskey && - self.owners == other.owners - } + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.root == other.root && + self.uuid == other.uuid && + self.icon == other.icon && + self.htpasswd == other.htpasswd && + self.bindaddr == other.bindaddr && + self.tlscert == other.tlscert && + self.tlskey == other.tlskey && + self.owners == other.owners + } } \ No newline at end of file diff --git a/src/hostinfo.rs b/src/hostinfo.rs index 40c3bdd..d8ede21 100644 --- a/src/hostinfo.rs +++ b/src/hostinfo.rs @@ -13,240 +13,240 @@ use super::{Owner, Album, Config, Metadata, Artist}; /// A struct representing the metadata or hostinfo and index of a Cyrkensia repository. #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Hostinfo { - /// Name - /// - /// The name of the Cyrkensia repository. - pub name: String, - - /// Icon - /// - /// The icon representing the Cyrkensia repo. - pub icon: String, - - /// UUID - /// - /// The UUIDv4 of the repository. - pub uuid: Uuid, - - /// Secured - /// - /// Determines whether a repository requires HTTP Basic Auth or not. - pub secured: bool, - - /// Size in bytes - /// - /// The total size of the repository and its music files in bytes. - pub size: u128, - - /// Origin URL - /// - /// The URL to get an updated version of this Hostinfo - pub origin: String, - - /// Albums - /// - /// List of all albums that this Cyrkensia repository provides. - pub albums: Vec, - - /// Maintainers and Owners - /// - /// List of all repository maintainers/owners. - pub owners: Vec, - - /// Featured Artists - /// - /// List of all [Artist]s in this repository. - pub artists: Vec + /// Name + /// + /// The name of the Cyrkensia repository. + pub name: String, + + /// Icon + /// + /// The icon representing the Cyrkensia repo. + pub icon: String, + + /// UUID + /// + /// The UUIDv4 of the repository. + pub uuid: Uuid, + + /// Secured + /// + /// Determines whether a repository requires HTTP Basic Auth or not. + pub secured: bool, + + /// Size in bytes + /// + /// The total size of the repository and its music files in bytes. + pub size: u128, + + /// Origin URL + /// + /// The URL to get an updated version of this Hostinfo + pub origin: String, + + /// Albums + /// + /// List of all albums that this Cyrkensia repository provides. + pub albums: Vec, + + /// Maintainers and Owners + /// + /// List of all repository maintainers/owners. + pub owners: Vec, + + /// Featured Artists + /// + /// List of all [Artist]s in this repository. + pub artists: Vec } impl Hostinfo { - /// Set Origin - /// - /// Sets the origin of the Hostinfo. This function solely exists to remind library users to swap out the empty default origin. - pub fn set_origin(&mut self, org: String) { - self.origin = org - } - - /// Generate empty Hostinfo - /// - /// Generates an empty Hostinfo. - pub fn empty() -> Hostinfo { - Hostinfo { - name: "".to_string(), - icon: "".to_string(), - uuid: Uuid::new_v4(), - secured: false, - size: 0, - origin: "".to_string(), - albums: Vec::new(), - owners: Vec::new(), - artists: Vec::new() - } - } - - /// Generate Hostinfo - /// - /// Generates a Hostinfo based on a [Config]. - pub fn generate(cfg: &Config, arts: &Vec) -> io::Result { - let mut albums: Vec = Vec::new(); - for rootpath in &cfg.root { - let album_slice = Hostinfo::read_albums(rootpath)?; - albums.extend(album_slice); - } - let mut hostinfo = Hostinfo::from(cfg.clone()); - hostinfo.size = albums.iter().map(|x| x.size).sum(); - hostinfo.albums = albums; - hostinfo.artists = arts.to_owned(); - Ok(hostinfo) - } - - /// Read Albums - /// - /// Reads a given directory and returns it as a [Vec] of [Album]s. - pub fn read_albums(path: impl AsRef) -> io::Result> { - // Read given Cyrkensia root - let albums: Vec = fs::read_dir(path.as_ref())? - - // Only use working entries and get directory path and name - .filter_map(|x| { - // Try getting the DirEntry - let Ok(dir) = x else { - return None; - }; - // Filter out non-dirs - if !dir.path().is_dir() { - return None; - } - // Return path and filename - Some((dir.path(), dir.file_name())) - }) - - // Create Album instances - .filter_map(|y| { - Hostinfo::parse_album(&y.0, &y.1).ok() - }) - - // Collect and Return - .collect(); - Ok(albums) - } - - /// Parse album - /// - /// This is a wrapper for the second `.filter_map()` in [read_albums](Hostinfo::read_albums) since clojures don't allow the `?`. - /// You can of course also use it if you desire. - pub fn parse_album(path: &PathBuf, name: &OsString) -> io::Result { - let Some(fname) = name.to_str() else { - // Return NotFound error - return Err(io::Error::new(io::ErrorKind::NotFound, "The OsString could not be parsed to a String")); - }; - - // Read data - let mut m = Metadata::load(path.join(".metadata.json"))?; - let c = Hostinfo::list_files(path)?; - - // List files with default Artist - if let Some(defart) = m.default { - for file in c.0 { - if let Some(other_arts) = m.artists.get_mut(&file) { - // Add default Artist to listed file if it's not included yet - if other_arts.contains(&defart) { - other_arts.push(defart); - } - } else { - // Append all yet unlisted files - m.artists.insert(file, vec![defart]); - } - } - } - - // Create Album - Ok(Album { - name: m.name, - cover: m.cover, - path: fname.to_string(), - files: m.artists, - size: c.1, - }) - } - - /// List files - /// - /// Lists all files in a given directory and their total size - pub fn list_files(path: impl AsRef) -> io::Result<(Vec, u128)> { - let mut allsize: u128 = 0; - - // Read Dir - let file_entries = fs::read_dir(path)? - - // Only files and with successful metadata - .filter_map(|x| { - // Get successful DirEntries - let Ok(entry) = x else { - return None; - }; - // Filter out non-files - if !entry.path().is_file() { - return None; - } - // Get successful Metadata - let Ok(fmeta) = entry.metadata() else { - return None; - }; - // Return Path and Length - Some((entry.path(), fmeta.len())) - }) - - // Return only the filename and not the entire path - .filter_map(|y| { - // Get OS filename - let Some(filename) = y.0.file_name() else { - return None; - }; - // Get filename as &str - let Some(fname) = filename.to_str() else { - return None; - }; - // Filter out dotfiles - if fname.starts_with('.') { - return None; - } - // Append to size and return filename - allsize += y.1 as u128; - Some(fname.to_string()) - }) - - // Collect to Vec and return result - .collect(); - Ok((file_entries, allsize)) - } + /// Set Origin + /// + /// Sets the origin of the Hostinfo. This function solely exists to remind library users to swap out the empty default origin. + pub fn set_origin(&mut self, org: String) { + self.origin = org + } + + /// Generate empty Hostinfo + /// + /// Generates an empty Hostinfo. + pub fn empty() -> Hostinfo { + Hostinfo { + name: "".to_string(), + icon: "".to_string(), + uuid: Uuid::new_v4(), + secured: false, + size: 0, + origin: "".to_string(), + albums: Vec::new(), + owners: Vec::new(), + artists: Vec::new() + } + } + + /// Generate Hostinfo + /// + /// Generates a Hostinfo based on a [Config]. + pub fn generate(cfg: &Config, arts: &Vec) -> io::Result { + let mut albums: Vec = Vec::new(); + for rootpath in &cfg.root { + let album_slice = Hostinfo::read_albums(rootpath)?; + albums.extend(album_slice); + } + let mut hostinfo = Hostinfo::from(cfg.clone()); + hostinfo.size = albums.iter().map(|x| x.size).sum(); + hostinfo.albums = albums; + hostinfo.artists = arts.to_owned(); + Ok(hostinfo) + } + + /// Read Albums + /// + /// Reads a given directory and returns it as a [Vec] of [Album]s. + pub fn read_albums(path: impl AsRef) -> io::Result> { + // Read given Cyrkensia root + let albums: Vec = fs::read_dir(path.as_ref())? + + // Only use working entries and get directory path and name + .filter_map(|x| { + // Try getting the DirEntry + let Ok(dir) = x else { + return None; + }; + // Filter out non-dirs + if !dir.path().is_dir() { + return None; + } + // Return path and filename + Some((dir.path(), dir.file_name())) + }) + + // Create Album instances + .filter_map(|y| { + Hostinfo::parse_album(&y.0, &y.1).ok() + }) + + // Collect and Return + .collect(); + Ok(albums) + } + + /// Parse album + /// + /// This is a wrapper for the second `.filter_map()` in [read_albums](Hostinfo::read_albums) since clojures don't allow the `?`. + /// You can of course also use it if you desire. + pub fn parse_album(path: &PathBuf, name: &OsString) -> io::Result { + let Some(fname) = name.to_str() else { + // Return NotFound error + return Err(io::Error::new(io::ErrorKind::NotFound, "The OsString could not be parsed to a String")); + }; + + // Read data + let mut m = Metadata::load(path.join(".metadata.json"))?; + let c = Hostinfo::list_files(path)?; + + // List files with default Artist + if let Some(defart) = m.default { + for file in c.0 { + if let Some(other_arts) = m.artists.get_mut(&file) { + // Add default Artist to listed file if it's not included yet + if other_arts.contains(&defart) { + other_arts.push(defart); + } + } else { + // Append all yet unlisted files + m.artists.insert(file, vec![defart]); + } + } + } + + // Create Album + Ok(Album { + name: m.name, + cover: m.cover, + path: fname.to_string(), + files: m.artists, + size: c.1, + }) + } + + /// List files + /// + /// Lists all files in a given directory and their total size + pub fn list_files(path: impl AsRef) -> io::Result<(Vec, u128)> { + let mut allsize: u128 = 0; + + // Read Dir + let file_entries = fs::read_dir(path)? + + // Only files and with successful metadata + .filter_map(|x| { + // Get successful DirEntries + let Ok(entry) = x else { + return None; + }; + // Filter out non-files + if !entry.path().is_file() { + return None; + } + // Get successful Metadata + let Ok(fmeta) = entry.metadata() else { + return None; + }; + // Return Path and Length + Some((entry.path(), fmeta.len())) + }) + + // Return only the filename and not the entire path + .filter_map(|y| { + // Get OS filename + let Some(filename) = y.0.file_name() else { + return None; + }; + // Get filename as &str + let Some(fname) = filename.to_str() else { + return None; + }; + // Filter out dotfiles + if fname.starts_with('.') { + return None; + } + // Append to size and return filename + allsize += y.1 as u128; + Some(fname.to_string()) + }) + + // Collect to Vec and return result + .collect(); + Ok((file_entries, allsize)) + } } impl From for Hostinfo { - fn from(x: Config) -> Hostinfo { - Hostinfo { - name: x.name, - icon: x.icon, - uuid: x.uuid, - secured: x.htpasswd.is_some(), - size: 0, - origin: "".to_string(), - albums: Vec::new(), - owners: x.owners, - artists: Vec::new() - } - } + fn from(x: Config) -> Hostinfo { + Hostinfo { + name: x.name, + icon: x.icon, + uuid: x.uuid, + secured: x.htpasswd.is_some(), + size: 0, + origin: "".to_string(), + albums: Vec::new(), + owners: x.owners, + artists: Vec::new() + } + } } impl PartialEq for Hostinfo { - fn eq(&self, other: &Self) -> bool { - self.name == other.name && - self.icon == other.icon && - self.uuid == other.uuid && - self.secured == other.secured && - self.size == other.size && - self.origin == other.origin && - self.albums == other.albums && - self.owners == other.owners - } + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.icon == other.icon && + self.uuid == other.uuid && + self.secured == other.secured && + self.size == other.size && + self.origin == other.origin && + self.albums == other.albums && + self.owners == other.owners + } } \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 50e91cb..7cdea4e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -62,28 +62,34 @@ pub use self::hostinfo::Hostinfo; /// /// This little module just contains information about this crate. pub mod meta { - pub const VERSION: &str = env!("CARGO_PKG_VERSION"); - pub const NAME: &str = env!("CARGO_PKG_NAME"); - pub const NAME_RICH: &str = "Cyrkensia"; - pub const AUTHORS: &str = env!("CARGO_PKG_AUTHORS"); - pub const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY"); - pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION"); - pub const LICENSE: &str = "EUPL-1.2"; - pub const LICENSE_RICH: &str = "European Union Public License v1.2"; - pub const LICENSE_URL: &str = "https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12"; - pub const CARGO_VERSION: &str = env!("CARGO_VERSION"); - pub const RUSTC_VERSION: &str = env!("RUSTC_VERSION"); - pub const COMPILE_DATE: &str = env!("COMPILE_DATE"); - pub const TARGET: &str = env!("TARGET"); - pub const USERAGENT: &str = concat!( - env!("CARGO_PKG_NAME"), - "/", - env!("CARGO_PKG_VERSION") - ); + pub const VERSION: &str = env!("CARGO_PKG_VERSION"); + pub const NAME: &str = env!("CARGO_PKG_NAME"); + pub const NAME_RICH: &str = "Cyrkensia"; + pub const AUTHORS: &str = env!("CARGO_PKG_AUTHORS"); + pub const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY"); + pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION"); + pub const LICENSE: &str = "EUPL-1.2"; + pub const LICENSE_RICH: &str = "European Union Public License v1.2"; + pub const LICENSE_URL: &str = "https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12"; + pub const CARGO_VERSION: &str = env!("CARGO_VERSION"); + pub const RUSTC_VERSION: &str = env!("RUSTC_VERSION"); + pub const COMPILE_DATE: &str = env!("COMPILE_DATE"); + pub const TARGET: &str = env!("TARGET"); + pub const USERAGENT: &str = concat!( + env!("CARGO_PKG_NAME"), + "/", + env!("CARGO_PKG_VERSION") + ); } #[cfg(feature = "server")] /// Server Routes /// /// This submodule contains middlewares and other tools needed only for the Cyrkensia server. -pub mod server; \ No newline at end of file +pub mod server; + +#[cfg(feature = "accounts")] +/// Account database +/// +/// Submodule containing the [Account](accounts::Account) struct and related cryptographic and wrapper functions. +pub mod accounts; \ No newline at end of file diff --git a/src/metadata.rs b/src/metadata.rs index ff790bc..f18a92d 100644 --- a/src/metadata.rs +++ b/src/metadata.rs @@ -15,73 +15,73 @@ use super::Album; /// A struct representing an album's `.metadata.json` file. #[derive(Debug, Serialize, Deserialize)] pub struct Metadata { - /// Name - /// - /// The name of the album. - pub name: String, + /// Name + /// + /// The name of the album. + pub name: String, - /// Cover - /// - /// The asset key representing the album cover art. - pub cover: String, + /// Cover + /// + /// The asset key representing the album cover art. + pub cover: String, - /// Default Artist - /// - /// Represents the UUIDv4 of the main [Artist] of this album - pub default: Option, + /// Default Artist + /// + /// Represents the UUIDv4 of the main [Artist] of this album + pub default: Option, - /// Additional Artists - /// - /// Map of which additional artists are associated with what music track - pub artists: HashMap> + /// Additional Artists + /// + /// Map of which additional artists are associated with what music track + pub artists: HashMap> } impl Metadata { - /// New Metadata - /// - /// Creates new [Metadata]. Authors can be appended later on. - pub fn new(name: String, cover: String, default_artist: Option, artists: Option>>) -> Metadata { - Metadata { - name, - cover, - default: default_artist, - artists: match artists { - Some(x) => x, - None => HashMap::new() - } - } - } + /// New Metadata + /// + /// Creates new [Metadata]. Authors can be appended later on. + pub fn new(name: String, cover: String, default_artist: Option, artists: Option>>) -> Metadata { + Metadata { + name, + cover, + default: default_artist, + artists: match artists { + Some(x) => x, + None => HashMap::new() + } + } + } - /// Load .metadata.json - /// - /// Loads a `.metadata.json` file into a [Metadata] instance. - pub fn load(path: impl AsRef) -> io::Result { - let data = fs::read_to_string(path)?; - Ok(from_str(data.as_str())?) - } + /// Load .metadata.json + /// + /// Loads a `.metadata.json` file into a [Metadata] instance. + pub fn load(path: impl AsRef) -> io::Result { + let data = fs::read_to_string(path)?; + Ok(from_str(data.as_str())?) + } } impl From for Metadata { - fn from(x: Album) -> Metadata { - Metadata { - name: x.name, - cover: x.cover, - artists: x.files, - default: None - } - } + fn from(x: Album) -> Metadata { + Metadata { + name: x.name, + cover: x.cover, + artists: x.files, + default: None + } + } } impl PartialEq for Metadata { - fn eq(&self, other: &Self) -> bool { - self.name == other.name && - self.cover == other.cover && - self.artists == other.artists - } + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.cover == other.cover && + self.artists == other.artists + } } impl Display for Metadata { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result { - write!(f, "{}", self.name) - } + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result { + write!(f, "{}", self.name) + } } \ No newline at end of file diff --git a/src/owner.rs b/src/owner.rs index b6d7346..0a888ad 100644 --- a/src/owner.rs +++ b/src/owner.rs @@ -9,72 +9,72 @@ use super::Artist; /// The datatype for Cyrkensia owners. #[derive(Serialize, Deserialize, Debug, Clone)] pub struct Owner { - /// Name - /// - /// The username of the owner. This is optional. - pub name: String, + /// Name + /// + /// The username of the owner. This is optional. + pub name: String, - /// E-Mail - /// - /// The email address of the owner. This is optional. - pub email: Option, + /// E-Mail + /// + /// The email address of the owner. This is optional. + pub email: Option, - /// Website - /// - /// The website or profile of an owner. This is optional. - pub website: Option + /// Website + /// + /// The website or profile of an owner. This is optional. + pub website: Option } impl Owner { - /// New Owner - /// - /// Creates a new owner. E-Mail and Website are optional, though if `email` isn't used, `website` should be, and vice versa. - pub fn new(name: String, email: Option, website: Option) -> Owner { - Owner { - name, - email, - website - } - } + /// New Owner + /// + /// Creates a new owner. E-Mail and Website are optional, though if `email` isn't used, `website` should be, and vice versa. + pub fn new(name: String, email: Option, website: Option) -> Owner { + Owner { + name, + email, + website + } + } } impl From for Owner { - fn from(x: Artist) -> Self { - Owner { - name: x.name, - email: None, - website: x.website - } - } + fn from(x: Artist) -> Self { + Owner { + name: x.name, + email: None, + website: x.website + } + } } impl PartialEq for Owner { - fn eq(&self, other: &Self) -> bool { - self.name == other.name && - self.email == other.email && - self.website == other.website - } + fn eq(&self, other: &Self) -> bool { + self.name == other.name && + self.email == other.email && + self.website == other.website + } } impl Display for Owner { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result { - match (self.email.clone(), self.website.clone()) { - (None, None) => { - // Name only - write!(f, "{}", self.name) - }, - (None, Some(y)) => { - // Name and Website - write!(f, "{} ({})", self.name, y) - }, - (Some(x), None) => { - // Name and E-Mail - write!(f, "{} <{}>", self.name, x) - }, - (Some(x), Some(y)) => { - // Name, E-Mail and Website - write!(f, "{} <{}> ({})", self.name, x, y) - } - } - } + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result { + match (self.email.clone(), self.website.clone()) { + (None, None) => { + // Name only + write!(f, "{}", self.name) + }, + (None, Some(y)) => { + // Name and Website + write!(f, "{} ({})", self.name, y) + }, + (Some(x), None) => { + // Name and E-Mail + write!(f, "{} <{}>", self.name, x) + }, + (Some(x), Some(y)) => { + // Name, E-Mail and Website + write!(f, "{} <{}> ({})", self.name, x, y) + } + } + } } \ No newline at end of file diff --git a/src/server/middleware.rs b/src/server/middleware.rs index adadf21..3f28758 100644 --- a/src/server/middleware.rs +++ b/src/server/middleware.rs @@ -5,18 +5,18 @@ use crate::meta; /// /// Appends the license headers (`X-License`, `X-License-SPDX` and `X-License-URL`) to every HTTP Response. pub fn license_headers() -> DefaultHeaders { - DefaultHeaders::new() - .add(("X-License", meta::LICENSE_RICH)) - .add(("X-License-SPDX", meta::LICENSE)) - .add(("X-License-URL", meta::LICENSE_URL)) + DefaultHeaders::new() + .add(("X-License", meta::LICENSE_RICH)) + .add(("X-License-SPDX", meta::LICENSE)) + .add(("X-License-URL", meta::LICENSE_URL)) } /// Owner and Source Code Headers /// /// Appends the `X-Authors` and `X-Repository` headers to every HTTP Response. pub fn source_headers() -> DefaultHeaders { - DefaultHeaders::new() - .add(("Server", meta::USERAGENT)) - .add(("X-Authors", meta::AUTHORS.replace(':', ", "))) - .add(("X-Repository", meta::REPOSITORY)) + DefaultHeaders::new() + .add(("Server", meta::USERAGENT)) + .add(("X-Authors", meta::AUTHORS.replace(':', ", "))) + .add(("X-Repository", meta::REPOSITORY)) } \ No newline at end of file diff --git a/src/server/mod.rs b/src/server/mod.rs index eae65be..4d2c294 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -30,75 +30,75 @@ pub mod responses; /// /// State for the Actix-Web server. Used in [routes]. pub struct CyrkensiaState { - /// Config - /// - /// The loaded Config (read-only) - pub config: Config, + /// Config + /// + /// The loaded Config (read-only) + pub config: Config, - /// Artists - /// - /// The loaded Artists (read-only) - pub artists: Mutex>, + /// Artists + /// + /// The loaded Artists (read-only) + pub artists: Mutex>, - /// Hostinfo - /// - /// The latest generated [Hostinfo]. - /// Only used if caching is activated. - pub hostinfo: Mutex, + /// Hostinfo + /// + /// The latest generated [Hostinfo]. + /// Only used if caching is activated. + pub hostinfo: Mutex, - /// Last Hostinfo Update - /// - /// The [timestamp](Instant) when the [Hostinfo] was last updated. - /// `.elapsed().as_secs()` will be used to compare it with the `max_age` in the [Config]. - /// Only used if caching is activated. - pub last_updated: Mutex -} - -impl CyrkensiaState { - /// Constructur - /// - /// Creates a new [CyrkensiaState] with given [Config]. - pub fn new(cfg: Config) -> io::Result { - // Read all artists - let arts = Artist::read_multiple(&cfg.root)?; - - // State with caching - if cfg.max_age.is_some() { - let hostinfo = Hostinfo::generate(&cfg, &arts)?; - return Ok(CyrkensiaState { - last_updated: Mutex::new(Instant::now()), - hostinfo: Mutex::new(hostinfo), - config: cfg, - artists: Mutex::new(arts) - }); - } - - // State without caching - Ok(CyrkensiaState { - hostinfo: Mutex::new(Hostinfo::empty()), - last_updated: Mutex::new(Instant::now()), - config: cfg, - artists: Mutex::new(arts) - }) - } + /// Last Hostinfo Update + /// + /// The [timestamp](Instant) when the [Hostinfo] was last updated. + /// `.elapsed().as_secs()` will be used to compare it with the `max_age` in the [Config]. + /// Only used if caching is activated. + pub last_updated: Mutex } /// Uri Display without Query /// /// Displays a Uri without the query parameters pub fn uri_noquery(uri: &Uri) -> String { - let mut f = String::new(); + let mut f = String::new(); + + // Protocol + if let Some(scheme) = uri.scheme() { + let _ = write!(&mut f, "{}://", scheme); + } + // Server + if let Some(authority) = uri.authority() { + let _ = write!(&mut f, "{}", authority); + } + // Path + let _ = write!(&mut f, "{}", uri.path()); + + f +} + +impl CyrkensiaState { + /// Constructur + /// + /// Creates a new [CyrkensiaState] with given [Config]. + pub fn new(cfg: Config) -> io::Result { + // Read all artists + let arts = Artist::read_multiple(&cfg.root)?; - // Protocol - if let Some(scheme) = uri.scheme() { - let _ = write!(&mut f, "{}://", scheme); - } - // Server - if let Some(authority) = uri.authority() { - let _ = write!(&mut f, "{}", authority); - } - // Path - let _ = write!(&mut f, "{}", uri.path()); + // State with caching + if cfg.max_age.is_some() { + let hostinfo = Hostinfo::generate(&cfg, &arts)?; + return Ok(CyrkensiaState { + last_updated: Mutex::new(Instant::now()), + hostinfo: Mutex::new(hostinfo), + config: cfg, + artists: Mutex::new(arts) + }); + } - f + // State without caching + Ok(CyrkensiaState { + hostinfo: Mutex::new(Hostinfo::empty()), + last_updated: Mutex::new(Instant::now()), + config: cfg, + artists: Mutex::new(arts) + }) + } } \ No newline at end of file diff --git a/src/server/redirect.rs b/src/server/redirect.rs index 76e009a..a42438f 100644 --- a/src/server/redirect.rs +++ b/src/server/redirect.rs @@ -5,21 +5,21 @@ use crate::meta; /// /// Creates a new 301 Moved Permanently redirect with the given Url. pub fn redirect(url: &str) -> impl Responder { - HttpResponse::MovedPermanently() - .append_header((LOCATION, url)) - .finish() + HttpResponse::MovedPermanently() + .append_header((LOCATION, url)) + .finish() } /// Repository redirect /// /// Redirects to the source code repository. pub async fn repository() -> impl Responder { - redirect(meta::REPOSITORY) + redirect(meta::REPOSITORY) } /// License redirect /// /// Redirects to the license text. pub async fn license() -> impl Responder { - redirect(meta::LICENSE_URL) + redirect(meta::LICENSE_URL) } \ No newline at end of file diff --git a/src/server/responses.rs b/src/server/responses.rs index 56a0127..6d988a9 100644 --- a/src/server/responses.rs +++ b/src/server/responses.rs @@ -7,35 +7,35 @@ use crate::{Config, Hostinfo, Artist}; /// /// Attempts to create a [HttpResponse] from a generated [Hostinfo] by a [Config]. pub fn hostinfo_json(cfg: &Config, arts: &Vec) -> io::Result { - // Generate Hostinfo - let hostinfo = Hostinfo::generate(cfg, arts)?; - hostinfo_data(&hostinfo) + // Generate Hostinfo + let hostinfo = Hostinfo::generate(cfg, arts)?; + hostinfo_data(&hostinfo) } /// Hostinfo from Data /// /// Attempts to create a [HttpResponse] from a [Hostinfo] struct. pub fn hostinfo_data(hstinfo: &Hostinfo) -> io::Result { - // Convert to String - let raw_json = serde_json::to_string(hstinfo)?; - - // Return HttpReponse - Ok(HttpResponse::Ok() - .content_type(ContentType::json()) - .append_header( - (CONTENT_LENGTH, raw_json.len()) - ) - .body(raw_json)) + // Convert to String + let raw_json = serde_json::to_string(hstinfo)?; + + // Return HttpReponse + Ok(HttpResponse::Ok() + .content_type(ContentType::json()) + .append_header( + (CONTENT_LENGTH, raw_json.len()) + ) + .body(raw_json)) } /// HTTP Status 500 /// /// Returns a 500 Error with an optional body message pub fn server_500(msg: Option) -> HttpResponse { - if let Some(message) = msg { - return HttpResponse::InternalServerError() - .body(message) - } - HttpResponse::InternalServerError() - .finish() + if let Some(message) = msg { + return HttpResponse::InternalServerError() + .body(message) + } + HttpResponse::InternalServerError() + .finish() } \ No newline at end of file diff --git a/src/server/routes.rs b/src/server/routes.rs index 5476805..642f8c0 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -7,54 +7,54 @@ use crate::{Hostinfo, Artist}; /// /// Route for serving a [Hostinfo]. Server needs [CyrkensiaState] in `.app_data()` for this. pub async fn hostinfo(req: HttpRequest, data: web::Data) -> impl Responder { - // Get config - let Some(delay) = data.config.max_age else { - // Ad hoch Hostinfo - let Ok(artists) = Artist::read_multiple(&data.config.root) else { - return responses::server_500(Some("Failed to generate hostinfo")); - }; - let Ok(resp) = responses::hostinfo_json(&data.config, &artists) else { - return responses::server_500(Some("Failed to generate hostinfo")); - }; - return resp; - }; + // Get config + let Some(delay) = data.config.max_age else { + // Ad hoch Hostinfo + let Ok(artists) = Artist::read_multiple(&data.config.root) else { + return responses::server_500(Some("Failed to generate hostinfo")); + }; + let Ok(resp) = responses::hostinfo_json(&data.config, &artists) else { + return responses::server_500(Some("Failed to generate hostinfo")); + }; + return resp; + }; - // Get last update timestamp and cached hostinfo and artists - let Ok(mut last_updated) = data.last_updated.lock() else { - return responses::server_500(None::); - }; - let Ok(mut hostinfo) = data.hostinfo.lock() else { - return responses::server_500(None::); - }; - let Ok(mut artists) = data.artists.lock() else { - return responses::server_500(None::); - }; + // Get last update timestamp and cached hostinfo and artists + let Ok(mut last_updated) = data.last_updated.lock() else { + return responses::server_500(None::); + }; + let Ok(mut hostinfo) = data.hostinfo.lock() else { + return responses::server_500(None::); + }; + let Ok(mut artists) = data.artists.lock() else { + return responses::server_500(None::); + }; - // Update Cache if expired - if last_updated.elapsed().as_secs() >= delay { - // Read updated artists - let Ok(new_artists) = Artist::read_multiple(&data.config.root) else { - return responses::server_500(Some("Failed to update hostinfo")); - }; + // Update Cache if expired + if last_updated.elapsed().as_secs() >= delay { + // Read updated artists + let Ok(new_artists) = Artist::read_multiple(&data.config.root) else { + return responses::server_500(Some("Failed to update hostinfo")); + }; - // Generate new Hostinfo - let Ok(new_hostinfo) = Hostinfo::generate(&data.config, &artists) else { - return responses::server_500(Some("Failed to update hostinfo")); - }; + // Generate new Hostinfo + let Ok(new_hostinfo) = Hostinfo::generate(&data.config, &artists) else { + return responses::server_500(Some("Failed to update hostinfo")); + }; - // Update Hostinfo and Timestamp - *artists = new_artists; - *hostinfo = new_hostinfo; - *last_updated = Instant::now(); - } + // Update Hostinfo and Timestamp + *artists = new_artists; + *hostinfo = new_hostinfo; + *last_updated = Instant::now(); + } - // Set Origin URL - let mut final_hostinfo = hostinfo.clone(); - final_hostinfo.set_origin(uri_noquery(req.uri())); + // Set Origin URL + let mut final_hostinfo = hostinfo.clone(); + final_hostinfo.set_origin(uri_noquery(req.uri())); - // Return final result - let Ok(finalres) = responses::hostinfo_data(&final_hostinfo) else { - return responses::server_500(Some("Failed to generate hostinfo")); - }; - finalres + // Return final result + let Ok(finalres) = responses::hostinfo_data(&final_hostinfo) else { + return responses::server_500(Some("Failed to generate hostinfo")); + }; + finalres } \ No newline at end of file From 862811f4ad85b16377978b78e3ccd2a58cc056e3 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Fri, 25 Nov 2022 18:01:47 +0100 Subject: [PATCH 23/36] More Account stuff --- src/{accounts.rs => account.rs} | 11 +++++++++++ src/config.rs | 5 +++-- src/lib.rs | 2 +- src/server/mod.rs | 23 +++++++++++++++++------ 4 files changed, 32 insertions(+), 9 deletions(-) rename src/{accounts.rs => account.rs} (88%) diff --git a/src/accounts.rs b/src/account.rs similarity index 88% rename from src/accounts.rs rename to src/account.rs index 6058f39..54a46f9 100644 --- a/src/accounts.rs +++ b/src/account.rs @@ -1,8 +1,11 @@ use serde::{Deserialize, Serialize}; +use serde_json::from_str; use rand::distributions::Alphanumeric; use rand::{Rng, thread_rng}; use blake3::{Hasher, OUT_LEN}; use std::fmt::Display; +use std::path::Path; +use std::{io, fs}; #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Account { @@ -42,6 +45,14 @@ impl Account { let passhash = hash_passwd_salt(passwd, &self.salt); passhash == self.password } + + /// Load Account file + /// + /// Loads an Account file + pub fn load(file: impl AsRef) -> io::Result> { + let data = fs::read_to_string(file)?; + Ok(from_str(data.as_str())?) + } } impl Display for Account { diff --git a/src/config.rs b/src/config.rs index 3a47074..843dd57 100644 --- a/src/config.rs +++ b/src/config.rs @@ -33,9 +33,10 @@ pub struct Config { /// The Rich Presence asset key used for displaying the server. pub icon: String, - /// Htpasswd file + /// Account file /// - /// The path to the .htpasswd file for HTTP-Basic Authentication. If none is present, HTTP Basic Auth will be disabled. + /// The path to the Account file for HTTP-Basic Authentication. If none is present, HTTP Basic Auth will be disabled. + /// Note that the file must be a JSON of [Vec]<[Account](super::account::Account)>. pub htpasswd: Option, /// Bind address diff --git a/src/lib.rs b/src/lib.rs index 7cdea4e..92392b4 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -92,4 +92,4 @@ pub mod server; /// Account database /// /// Submodule containing the [Account](accounts::Account) struct and related cryptographic and wrapper functions. -pub mod accounts; \ No newline at end of file +pub mod account; \ No newline at end of file diff --git a/src/server/mod.rs b/src/server/mod.rs index 4d2c294..44d478f 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,4 +1,5 @@ use actix_web::http::Uri; +use crate::account::Account; use crate::{Hostinfo, Config, Artist}; use std::fmt::Write; use std::sync::Mutex; @@ -35,9 +36,14 @@ pub struct CyrkensiaState { /// The loaded Config (read-only) pub config: Config, + /// Accounts + /// + /// The optionally loaded Account database (read-only) + pub accounts: Option>, + /// Artists /// - /// The loaded Artists (read-only) + /// The lateast loaded Artists pub artists: Mutex>, /// Hostinfo @@ -78,18 +84,22 @@ impl CyrkensiaState { /// Constructur /// /// Creates a new [CyrkensiaState] with given [Config]. - pub fn new(cfg: Config) -> io::Result { - // Read all artists - let arts = Artist::read_multiple(&cfg.root)?; + pub fn new(cfg: Config) -> io::Result { + let accounts = match &cfg.htpasswd { + Some(path) => Some(Account::load(path)?), + None => None + }; // State with caching if cfg.max_age.is_some() { + let arts = Artist::read_multiple(&cfg.root)?; let hostinfo = Hostinfo::generate(&cfg, &arts)?; return Ok(CyrkensiaState { last_updated: Mutex::new(Instant::now()), hostinfo: Mutex::new(hostinfo), + artists: Mutex::new(arts), config: cfg, - artists: Mutex::new(arts) + accounts }); } @@ -97,8 +107,9 @@ impl CyrkensiaState { Ok(CyrkensiaState { hostinfo: Mutex::new(Hostinfo::empty()), last_updated: Mutex::new(Instant::now()), + artists: Mutex::new(Vec::new()), config: cfg, - artists: Mutex::new(arts) + accounts }) } } \ No newline at end of file From 307473af9292f082fdf2e9562e1bc2b747b362a8 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Fri, 25 Nov 2022 18:59:20 +0100 Subject: [PATCH 24/36] Add CORS everywhere middleware --- src/server/middleware.rs | 44 ++++++++++++++++++++++++++++++++++++++++ src/server/mod.rs | 1 - 2 files changed, 44 insertions(+), 1 deletion(-) diff --git a/src/server/middleware.rs b/src/server/middleware.rs index 3f28758..aa79cf7 100644 --- a/src/server/middleware.rs +++ b/src/server/middleware.rs @@ -1,4 +1,6 @@ use actix_web::middleware::DefaultHeaders; +use actix_web::http::header; +use actix_cors::Cors; use crate::meta; /// License Headers @@ -19,4 +21,46 @@ pub fn source_headers() -> DefaultHeaders { .add(("Server", meta::USERAGENT)) .add(("X-Authors", meta::AUTHORS.replace(':', ", "))) .add(("X-Repository", meta::REPOSITORY)) +} + +/// CORS everywhere middleware +/// +/// Create a CORS Middleware that allows any origin. +pub fn cors_everywhere() -> Cors { + // Cors Middleware + Cors::default() + .supports_credentials() + .allow_any_origin() + .max_age(86400) + + // --- Methods --- + .allowed_methods(vec![ + "GET", "HEAD", "OPTIONS" + ]) + + // --- Headers --- + .allowed_headers(vec![ + header::ETAG, + header::CACHE_CONTROL, + header::IF_MODIFIED_SINCE, + header::AUTHORIZATION, + header::ACCEPT, + header::ACCEPT_LANGUAGE, + header::ACCEPT_ENCODING, + header::CONTENT_TYPE, + header::CONTENT_LENGTH, + header::ORIGIN, + header::DNT, + header::USER_AGENT + ]) + .allowed_header("X-Requested-With") + + // --- Exposed --- + .expose_headers(vec![ + header::WWW_AUTHENTICATE, + header::CONTENT_LENGTH, + header::CONTENT_ENCODING, + header::CONTENT_RANGE, + header::CONTENT_TYPE + ]) } \ No newline at end of file diff --git a/src/server/mod.rs b/src/server/mod.rs index 44d478f..8c62010 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -16,7 +16,6 @@ pub mod middleware; /// Submodule containing Cyrkensia redirects. pub mod redirect; - /// Routes /// /// Submodule containing Cyrkensia routes. From 5cb32cd39b10f712813a1f6894da42a7830f0c06 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Fri, 25 Nov 2022 20:10:21 +0100 Subject: [PATCH 25/36] Switch password hashing to Argon2 --- Cargo.lock | 38 +++++++++++++++++++++++++++++ Cargo.toml | 7 +++--- src/account.rs | 65 ++++++++++++++++++++++---------------------------- 3 files changed, 71 insertions(+), 39 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 84c880b..5bd5b32 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -266,6 +266,17 @@ dependencies = [ "libc", ] +[[package]] +name = "argon2" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db4ce4441f99dbd377ca8a8f57b698c44d0d6e712d8329b5040da5a64aa1ce73" +dependencies = [ + "base64ct", + "blake2", + "password-hash", +] + [[package]] name = "arrayref" version = "0.3.6" @@ -290,12 +301,27 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" +[[package]] +name = "base64ct" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b645a089122eccb6111b4f81cbc1a49f5900ac4666bb93ac027feaecf15607bf" + [[package]] name = "bitflags" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" +[[package]] +name = "blake2" +version = "0.10.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b12e5fd123190ce1c2e559308a94c9bacad77907d4c6005d9e58fe1a0689e55e" +dependencies = [ + "digest", +] + [[package]] name = "blake3" version = "1.3.2" @@ -508,6 +534,7 @@ version = "1.2.0" dependencies = [ "actix-cors", "actix-web", + "argon2", "blake3", "chrono", "rand", @@ -899,6 +926,17 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "password-hash" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7676374caaee8a325c9e7a2ae557f216c5563a171d6997b0ef8a65af35147700" +dependencies = [ + "base64ct", + "rand_core", + "subtle", +] + [[package]] name = "paste" version = "1.0.9" diff --git a/Cargo.toml b/Cargo.toml index 4a41d2d..4882d11 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,15 +23,16 @@ uuid = { version = "1.2", features = ["v4", "serde"] } # Server only actix-web = { version = "4", optional = true, features = ["rustls"] } actix-cors = { version = "0.6", optional = true } +blake3 = { version = "1.3", optional = true } # Accounts only -blake3 = { version = "1.3", optional = true } +argon2 = { version = "0.4", optional = true, features = ["std", "password-hash"] } rand = { version = "0.8", optional = true, features = ["std"] } [features] default = ["server"] -accounts = ["blake3", "rand"] -server = ["actix-web", "actix-cors", "accounts"] +accounts = ["argon2", "rand"] +server = ["actix-web", "actix-cors", "blake3", "accounts"] [build-dependencies] chrono = "0.4" diff --git a/src/account.rs b/src/account.rs index 54a46f9..1c06ced 100644 --- a/src/account.rs +++ b/src/account.rs @@ -1,11 +1,11 @@ -use serde::{Deserialize, Serialize}; -use serde_json::from_str; -use rand::distributions::Alphanumeric; -use rand::{Rng, thread_rng}; -use blake3::{Hasher, OUT_LEN}; use std::fmt::Display; use std::path::Path; use std::{io, fs}; +use serde::{Deserialize, Serialize}; +use serde_json::from_str; +use argon2::password_hash::rand_core::OsRng; +use argon2::password_hash::{SaltString, Result}; +use argon2::{Argon2, PasswordHasher, PasswordVerifier, PasswordHash}; #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Account { @@ -29,21 +29,23 @@ impl Account { /// New Account /// /// Creates a new account with a random salt and given password. - pub fn new(name: String, passwd: String) -> Account { + pub fn new(name: String, passwd: String) -> Result { let salt = random_salt(); - Account { + let hash = hash_passwd_salt(passwd, &salt)?.to_string(); + Ok(Account { username: name, - password: hash_passwd_salt(passwd, &salt), + password: hash, salt - } + }) } /// Verify Password /// /// Verifies the Account against a given plaintext password. - pub fn verify(&self, passwd: String) -> bool { - let passhash = hash_passwd_salt(passwd, &self.salt); - passhash == self.password + pub fn verify(&self, passwd: String) -> Result<()> { + let passhash = hash_passwd_salt(passwd, &self.salt)?; + get_argon2() + .verify_password(self.password.as_bytes(), &passhash) } /// Load Account file @@ -61,35 +63,26 @@ impl Display for Account { } } -/// Hash input -/// -/// Hashes an input. The input has to append the salt itself. -/// Returns a formatted String representing the hash value. -pub fn hash(input: &[u8]) -> String { - let mut hasher = Hasher::new(); - hasher.update(input); - hasher.finalize().to_string() -} - /// Hash Password with Salt /// -/// Hashes the given password with given salt. -/// Wrapper for [hash]. -pub fn hash_passwd_salt(passwd: String, salt: &String) -> String { - // Get input and salt as bytes - let mut userpass: Vec = passwd.into(); - userpass.extend(salt.as_bytes()); - hash(&userpass) +/// Hashes the password with given salt to a [String]. +/// Wrapper for [Argon2]'s `hash_password()`. +pub fn hash_passwd_salt(passwd: String, salt: &String) -> Result { + get_argon2() + .hash_password(passwd.as_bytes(), salt) } /// Random Salt /// -/// Generates a random salt for the given bit length. -/// Note that `bits` should be a multiple of 8. +/// Generates a random salt for Argon2 with the [OsRng]. pub fn random_salt() -> String { - thread_rng() - .sample_iter(&Alphanumeric) - .take(OUT_LEN) - .map(char::from) - .collect() + SaltString::generate(&mut OsRng) + .to_string() +} + +/// Get Argon2 context +/// +/// Creates an Argon2 context that is used for every function here. +pub fn get_argon2() -> Argon2<'static> { + Argon2::default() } \ No newline at end of file From c16c6c252e44eb28308900280294e21b51c4c04c Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Mon, 28 Nov 2022 21:48:55 +0100 Subject: [PATCH 26/36] Small improvements to keep this alive --- src/account.rs | 14 +++++++++----- src/server/redirect.rs | 4 ++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/src/account.rs b/src/account.rs index 1c06ced..c8fc45e 100644 --- a/src/account.rs +++ b/src/account.rs @@ -44,7 +44,7 @@ impl Account { /// Verifies the Account against a given plaintext password. pub fn verify(&self, passwd: String) -> Result<()> { let passhash = hash_passwd_salt(passwd, &self.salt)?; - get_argon2() + get_argon2!() .verify_password(self.password.as_bytes(), &passhash) } @@ -68,7 +68,7 @@ impl Display for Account { /// Hashes the password with given salt to a [String]. /// Wrapper for [Argon2]'s `hash_password()`. pub fn hash_passwd_salt(passwd: String, salt: &String) -> Result { - get_argon2() + get_argon2!() .hash_password(passwd.as_bytes(), salt) } @@ -83,6 +83,10 @@ pub fn random_salt() -> String { /// Get Argon2 context /// /// Creates an Argon2 context that is used for every function here. -pub fn get_argon2() -> Argon2<'static> { - Argon2::default() -} \ No newline at end of file +#[macro_export] +macro_rules! get_argon2 { + () => { + Argon2::default() + }; +} +pub use get_argon2; diff --git a/src/server/redirect.rs b/src/server/redirect.rs index a42438f..de0fca7 100644 --- a/src/server/redirect.rs +++ b/src/server/redirect.rs @@ -13,13 +13,13 @@ pub fn redirect(url: &str) -> impl Responder { /// Repository redirect /// /// Redirects to the source code repository. -pub async fn repository() -> impl Responder { +pub fn repository() -> impl Responder { redirect(meta::REPOSITORY) } /// License redirect /// /// Redirects to the license text. -pub async fn license() -> impl Responder { +pub fn license() -> impl Responder { redirect(meta::LICENSE_URL) } \ No newline at end of file From ec29995d4121a1cd50dbc581c7a9ef0b6137f389 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Sat, 3 Dec 2022 02:10:17 +0100 Subject: [PATCH 27/36] Album indexing route done --- src/server/mod.rs | 6 ++--- src/server/responses.rs | 34 +++++++++++++++++++----- src/server/routes.rs | 57 +++++++++++++++++++++++++++++++++++++++-- 3 files changed, 86 insertions(+), 11 deletions(-) diff --git a/src/server/mod.rs b/src/server/mod.rs index 8c62010..5510c4f 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -38,7 +38,7 @@ pub struct CyrkensiaState { /// Accounts /// /// The optionally loaded Account database (read-only) - pub accounts: Option>, + pub accounts: Vec, /// Artists /// @@ -85,8 +85,8 @@ impl CyrkensiaState { /// Creates a new [CyrkensiaState] with given [Config]. pub fn new(cfg: Config) -> io::Result { let accounts = match &cfg.htpasswd { - Some(path) => Some(Account::load(path)?), - None => None + Some(path) => Account::load(path)?, + None => Vec::new() }; // State with caching diff --git a/src/server/responses.rs b/src/server/responses.rs index 6d988a9..b0477eb 100644 --- a/src/server/responses.rs +++ b/src/server/responses.rs @@ -1,6 +1,7 @@ use std::io; -use actix_web::{HttpResponse, body::MessageBody}; -use actix_web::http::header::{ContentType, CONTENT_LENGTH}; +use actix_web::body::MessageBody; +use actix_web::{HttpResponse, HttpResponseBuilder}; +use actix_web::http::header::{ContentType, CONTENT_LENGTH, WWW_AUTHENTICATE}; use crate::{Config, Hostinfo, Artist}; /// Hostinfo from Config @@ -32,10 +33,31 @@ pub fn hostinfo_data(hstinfo: &Hostinfo) -> io::Result { /// /// Returns a 500 Error with an optional body message pub fn server_500(msg: Option) -> HttpResponse { + error(HttpResponse::InternalServerError(), msg) +} + +/// HTTP Status 404 +/// +/// Returns a 404 Error with an optional body message +pub fn client_404(msg: Option) -> HttpResponse { + error(HttpResponse::NotFound(), msg) +} + +/// HTTP Status 401 +/// +/// Returns a 401 Error with an optional body message +pub fn client_401(msg: Option) -> HttpResponse { + let mut resp = HttpResponse::Unauthorized(); + resp.insert_header((WWW_AUTHENTICATE, "Basic realm=\"Cyrkensia\"")); + error(resp, msg) +} + +/// General Purpose Status Reponse Builder +/// +/// Just makes the [HttpResponseBuilder] as a finished [HttpResponse], optionally being able to pass a body. +pub fn error(mut resp: HttpResponseBuilder, msg: Option) -> HttpResponse { if let Some(message) = msg { - return HttpResponse::InternalServerError() - .body(message) + return resp.body(message) } - HttpResponse::InternalServerError() - .finish() + resp.finish() } \ No newline at end of file diff --git a/src/server/routes.rs b/src/server/routes.rs index 642f8c0..8bf4f2e 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -1,7 +1,9 @@ use std::time::Instant; -use actix_web::{web, Responder, HttpRequest}; +use std::path::Path; +use actix_web::{web, Responder, HttpRequest, HttpResponse}; +use actix_web::http::header::ContentType; use super::{CyrkensiaState, responses, uri_noquery}; -use crate::{Hostinfo, Artist}; +use crate::{Hostinfo, Artist, Metadata}; /// Hostinfo Route /// @@ -57,4 +59,55 @@ pub async fn hostinfo(req: HttpRequest, data: web::Data) -> impl return responses::server_500(Some("Failed to generate hostinfo")); }; finalres +} + +/// Index Route Params +/// +/// Simple struct containing the param-name and param-type needed for the [index] route. +pub struct IndexParams { + album: String +} + +/// Album Index Route +/// +/// Route for listing all files of a specific. Redundant, can be ignored. +pub async fn index(p: web::Path, data: web::Data) -> impl Responder { + // Read files and album name depending on if cache is enabled or not + let meta: (String, usize, Vec) = match data.config.max_age { + Some(_) => { + // Cached files and metadata + let Ok(hostinfo) = data.hostinfo.lock() else { + return responses::server_500(None::); + }; + let Some(album) = hostinfo.albums.clone().into_iter().find(|x| x.path == p.album) else { + return responses::client_404(Some("Album not found")); + }; + + // Return tri-tuple + let files: Vec = album.files.keys().cloned().collect(); + (album.name, files.len(), files) + + }, + None => { + // Ad-hoc files and metadata + let Ok(files) = Hostinfo::list_files(&p.album) else { + return responses::client_404(Some("Album not found or accessable")); + }; + let Ok(album) = Metadata::load(Path::new(p.album.as_str()).join(".metadata.json")) else { + return responses::client_404(Some("Album not found")); + }; + + // Return tri-tuple + (album.name, files.0.len(), files.0) + } + }; + + // Codegen + let headstr = format!("

{} ({})

", meta.0, meta.1); + let bodystr: String = meta.2.into_iter().fold(String::new(), |total, item| total + &format!("{}
\n", item, item)); + + // Send response + HttpResponse::Ok() + .content_type(ContentType::html()) + .body(headstr + &bodystr) } \ No newline at end of file From e89b77f9267dd987d6ce409b0519725d8388dea5 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Sat, 3 Dec 2022 14:32:39 +0100 Subject: [PATCH 28/36] Album finder done and route updated --- src/album.rs | 31 +++++++++++++++++++++++++++++++ src/server/routes.rs | 24 +++++++++++++++--------- 2 files changed, 46 insertions(+), 9 deletions(-) diff --git a/src/album.rs b/src/album.rs index 92ffbe8..1883393 100644 --- a/src/album.rs +++ b/src/album.rs @@ -1,8 +1,11 @@ use serde::{Serialize, Deserialize}; use uuid::Uuid; +use std::fs; +use std::io; use std::cmp::PartialEq; use std::collections::HashMap; use std::convert::From; +use std::path::PathBuf; use super::Metadata; /// Album @@ -52,6 +55,34 @@ impl Album { size } } + + /// Find Album in filesystem + /// + /// Attempts to find an album in given roots by set folder name + pub fn find(roots: &[String], name: &String) -> io::Result { + for root in roots { + let item = fs::read_dir(root)?.into_iter() + // Filter out invalid entries + .filter_map(|x| x.ok()) + // Get dirname as String + .filter_map(|x| { + let path = x.path(); + if let Some(filename) = path.file_name() + .and_then(|y| y.to_str()).map(|z| z.to_string()) { + return Some((filename, path)); + } + None + }) + // Find album + .find(|item| &item.0 == name); + + // Return first match + if let Some(path) = item { + return Ok(path.1); + } + } + Err(io::Error::new(io::ErrorKind::NotFound, "Could not find album")) + } } impl From for Album { diff --git a/src/server/routes.rs b/src/server/routes.rs index 8bf4f2e..0f01e16 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -1,9 +1,8 @@ use std::time::Instant; -use std::path::Path; use actix_web::{web, Responder, HttpRequest, HttpResponse}; use actix_web::http::header::ContentType; use super::{CyrkensiaState, responses, uri_noquery}; -use crate::{Hostinfo, Artist, Metadata}; +use crate::{Hostinfo, Artist, Metadata, Album}; /// Hostinfo Route /// @@ -72,6 +71,8 @@ pub struct IndexParams { /// /// Route for listing all files of a specific. Redundant, can be ignored. pub async fn index(p: web::Path, data: web::Data) -> impl Responder { + // Extract album name + let path = p.into_inner(); // Read files and album name depending on if cache is enabled or not let meta: (String, usize, Vec) = match data.config.max_age { Some(_) => { @@ -79,7 +80,7 @@ pub async fn index(p: web::Path, data: web::Data) - let Ok(hostinfo) = data.hostinfo.lock() else { return responses::server_500(None::); }; - let Some(album) = hostinfo.albums.clone().into_iter().find(|x| x.path == p.album) else { + let Some(album) = hostinfo.albums.clone().into_iter().find(|x| x.path == path.album) else { return responses::client_404(Some("Album not found")); }; @@ -89,13 +90,18 @@ pub async fn index(p: web::Path, data: web::Data) - }, None => { - // Ad-hoc files and metadata - let Ok(files) = Hostinfo::list_files(&p.album) else { - return responses::client_404(Some("Album not found or accessable")); + // Attempt to find album in filesystem + let Ok(path) = Album::find(&data.config.root, &path.album) else { + return responses::client_404(Some("Album not found")); }; - let Ok(album) = Metadata::load(Path::new(p.album.as_str()).join(".metadata.json")) else { + + // Ad-hoc metadata and files + let Ok(album) = Metadata::load(path.join(".metadata.json")) else { return responses::client_404(Some("Album not found")); }; + let Ok(files) = Hostinfo::list_files(path) else { + return responses::client_404(Some("Album not accessable")); + }; // Return tri-tuple (album.name, files.0.len(), files.0) @@ -103,8 +109,8 @@ pub async fn index(p: web::Path, data: web::Data) - }; // Codegen - let headstr = format!("

{} ({})

", meta.0, meta.1); - let bodystr: String = meta.2.into_iter().fold(String::new(), |total, item| total + &format!("{}
\n", item, item)); + let headstr = format!("

{} ({})

\n", meta.0, meta.1); + let bodystr = meta.2.into_iter().fold(String::new(), |total, item| total + &format!("{}
\n", item, item)); // Send response HttpResponse::Ok() From b49ab1044fa804ed5be942b252ac66c8a053d496 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Sun, 4 Dec 2022 03:57:00 +0100 Subject: [PATCH 29/36] Structural tuning and server binary --- Cargo.lock | 191 +++++++++++++++++++------------------------ Cargo.toml | 9 +- src/account.rs | 26 +++++- src/album.rs | 23 +++--- src/bin/cyrkensia.rs | 96 +++++++++++++++++++--- src/config.rs | 42 ++++++---- src/hostinfo.rs | 20 +---- src/lib.rs | 13 +-- src/metadata.rs | 26 ++---- src/server/routes.rs | 55 ++++++------- 10 files changed, 278 insertions(+), 223 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 5bd5b32..47187f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -43,7 +43,6 @@ dependencies = [ "actix-codec", "actix-rt", "actix-service", - "actix-tls", "actix-utils", "ahash", "base64", @@ -134,24 +133,6 @@ dependencies = [ "pin-project-lite", ] -[[package]] -name = "actix-tls" -version = "3.0.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9fde0cf292f7cdc7f070803cb9a0d45c018441321a78b1042ffbbb81ec333297" -dependencies = [ - "actix-codec", - "actix-rt", - "actix-service", - "actix-utils", - "futures-core", - "log", - "pin-project-lite", - "tokio-rustls", - "tokio-util", - "webpki-roots", -] - [[package]] name = "actix-utils" version = "3.0.1" @@ -175,7 +156,6 @@ dependencies = [ "actix-rt", "actix-server", "actix-service", - "actix-tls", "actix-utils", "actix-web-codegen", "ahash", @@ -537,6 +517,8 @@ dependencies = [ "argon2", "blake3", "chrono", + "dirs", + "kagero", "rand", "serde", "serde_json", @@ -567,6 +549,26 @@ dependencies = [ "subtle", ] +[[package]] +name = "dirs" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" +dependencies = [ + "libc", + "redox_users", + "winapi", +] + [[package]] name = "encoding_rs" version = "0.8.31" @@ -777,6 +779,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "kagero" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dff686c11ce916d3ffd62f7ed470638d3d0021bb503a2d818a220f3e795687e" +dependencies = [ + "url", + "winres", +] + [[package]] name = "language-tags" version = "0.3.2" @@ -1024,6 +1036,17 @@ dependencies = [ "bitflags", ] +[[package]] +name = "redox_users" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" +dependencies = [ + "getrandom", + "redox_syscall", + "thiserror", +] + [[package]] name = "regex" version = "1.7.0" @@ -1041,21 +1064,6 @@ version = "0.6.28" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" -[[package]] -name = "ring" -version = "0.16.20" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc" -dependencies = [ - "cc", - "libc", - "once_cell", - "spin", - "untrusted", - "web-sys", - "winapi", -] - [[package]] name = "rustc_version" version = "0.4.0" @@ -1065,18 +1073,6 @@ dependencies = [ "semver", ] -[[package]] -name = "rustls" -version = "0.20.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "539a2bfe908f471bfa933876bd1eb6a19cf2176d375f82ef7f99530a40e48c2c" -dependencies = [ - "log", - "ring", - "sct", - "webpki", -] - [[package]] name = "ryu" version = "1.0.11" @@ -1095,16 +1091,6 @@ version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8132065adcfd6e02db789d9285a0deb2f3fcb04002865ab67d5fb103533898" -[[package]] -name = "sct" -version = "0.7.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4" -dependencies = [ - "ring", - "untrusted", -] - [[package]] name = "semver" version = "1.0.14" @@ -1199,12 +1185,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "spin" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" - [[package]] name = "subtle" version = "2.4.1" @@ -1231,6 +1211,26 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "thiserror" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "time" version = "0.1.44" @@ -1302,17 +1302,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "tokio-rustls" -version = "0.23.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59" -dependencies = [ - "rustls", - "tokio", - "webpki", -] - [[package]] name = "tokio-util" version = "0.7.4" @@ -1327,6 +1316,15 @@ dependencies = [ "tracing", ] +[[package]] +name = "toml" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" +dependencies = [ + "serde", +] + [[package]] name = "tracing" version = "0.1.37" @@ -1381,12 +1379,6 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0edd1e5b14653f783770bce4a4dabb4a5108a5370a5f5d8cfe8710c361f6c8b" -[[package]] -name = "untrusted" -version = "0.7.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" - [[package]] name = "url" version = "2.3.1" @@ -1396,6 +1388,7 @@ dependencies = [ "form_urlencoded", "idna", "percent-encoding", + "serde", ] [[package]] @@ -1480,35 +1473,6 @@ version = "0.2.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f" -[[package]] -name = "web-sys" -version = "0.3.60" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcda906d8be16e728fd5adc5b729afad4e444e106ab28cd1c7256e54fa61510f" -dependencies = [ - "js-sys", - "wasm-bindgen", -] - -[[package]] -name = "webpki" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd" -dependencies = [ - "ring", - "untrusted", -] - -[[package]] -name = "webpki-roots" -version = "0.22.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "368bfe657969fb01238bb756d351dcade285e0f6fcbd36dcb23359a5169975be" -dependencies = [ - "webpki", -] - [[package]] name = "winapi" version = "0.3.9" @@ -1597,6 +1561,15 @@ version = "0.42.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5" +[[package]] +name = "winres" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b68db261ef59e9e52806f688020631e987592bd83619edccda9c47d42cde4f6c" +dependencies = [ + "toml", +] + [[package]] name = "zstd" version = "0.11.2+zstd.1.5.2" diff --git a/Cargo.toml b/Cargo.toml index 4882d11..2008932 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,15 +13,18 @@ documentation = "https://docs.rs/cyrkensia" authors = ["Stridsvagn69420"] categories = [] keywords = [] +default-run = "cyrkensia" [dependencies] # Main crate serde = { version = "1", features = ["derive"] } serde_json = "1" uuid = { version = "1.2", features = ["v4", "serde"] } +dirs = "4" +kagero = { version = "0.4", default-features = false, features = ["printer"] } # Server only -actix-web = { version = "4", optional = true, features = ["rustls"] } +actix-web = { version = "4", optional = true } actix-cors = { version = "0.6", optional = true } blake3 = { version = "1.3", optional = true } @@ -30,9 +33,9 @@ argon2 = { version = "0.4", optional = true, features = ["std", "password-hash"] rand = { version = "0.8", optional = true, features = ["std"] } [features] -default = ["server"] +default = ["server", "accounts"] accounts = ["argon2", "rand"] -server = ["actix-web", "actix-cors", "blake3", "accounts"] +server = ["actix-web", "actix-cors", "blake3"] [build-dependencies] chrono = "0.4" diff --git a/src/account.rs b/src/account.rs index c8fc45e..76f6c23 100644 --- a/src/account.rs +++ b/src/account.rs @@ -1,11 +1,13 @@ use std::fmt::Display; use std::path::Path; -use std::{io, fs}; +use std::{io, fs, env}; +use dirs::home_dir; use serde::{Deserialize, Serialize}; use serde_json::from_str; use argon2::password_hash::rand_core::OsRng; use argon2::password_hash::{SaltString, Result}; use argon2::{Argon2, PasswordHasher, PasswordVerifier, PasswordHash}; +use super::meta; #[derive(Debug, Deserialize, Serialize, Clone)] pub struct Account { @@ -55,6 +57,26 @@ impl Account { let data = fs::read_to_string(file)?; Ok(from_str(data.as_str())?) } + + /// Cascade Loading + /// + /// Attempts to load a user file by: + /// 1. First command-line argument + /// 2. `CYRKENSIA_USERS` environment variable + /// 3. `~/.config/cyrkensia/users.json` file + pub fn load_cascade(cmdarg: Option<&String>, pathcfg: Option<&String>) -> io::Result> { + // Select extra path + let envvar = env::var(meta::USERS_ENVVAR); + + // Read users from extra location + if let Some(path) = cmdarg.or_else(|| envvar.as_ref().ok()).or(pathcfg) { + return Account::load(path); + } + + // Read with default path + let localpath = home_dir().unwrap_or_default().join(meta::USERS_PATH); + Account::load(localpath) + } } impl Display for Account { @@ -89,4 +111,4 @@ macro_rules! get_argon2 { Argon2::default() }; } -pub use get_argon2; +pub use get_argon2; \ No newline at end of file diff --git a/src/album.rs b/src/album.rs index 1883393..79bba8e 100644 --- a/src/album.rs +++ b/src/album.rs @@ -3,7 +3,6 @@ use uuid::Uuid; use std::fs; use std::io; use std::cmp::PartialEq; -use std::collections::HashMap; use std::convert::From; use std::path::PathBuf; use super::Metadata; @@ -28,10 +27,15 @@ pub struct Album { /// The relative path of the album. pub path: String, + /// Artists + /// + /// The UUID of the artists responsible for this album. + pub artists: Vec, + /// Files /// /// All files present in the album as a relative path. - pub files: HashMap>, + pub files: Vec, /// Size /// @@ -43,16 +47,14 @@ impl Album { /// New Album /// /// Creates a new album. If `artists` or `files` is [None], an empty array will be created for them. - pub fn new(name: String, cover: String, path: String, files: Option>>, size: u128) -> Album { + pub fn new(name: String, cover: String, path: String, artists: Vec, files: Vec, size: u128) -> Album { Album { name, cover, path, - files: match files { - Some(x) => x, - None => HashMap::new() - }, - size + files, + size, + artists } } @@ -91,8 +93,9 @@ impl From for Album { name: x.name, cover: x.cover, path: "".to_string(), - files: x.artists, - size: 0 + files: Vec::new(), + size: 0, + artists: x.artists } } } diff --git a/src/bin/cyrkensia.rs b/src/bin/cyrkensia.rs index 29058aa..e5d2b7c 100644 --- a/src/bin/cyrkensia.rs +++ b/src/bin/cyrkensia.rs @@ -1,15 +1,89 @@ -//use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder}; +use std::{env, io}; +use std::process::exit; +use cyrkensia::Config; +use cyrkensia::meta::WIKI_HELP_URL; +use cyrkensia::server::CyrkensiaState; +use cyrkensia::server::routes::{index, hostinfo}; +use cyrkensia::server::middleware::{cors_everywhere, source_headers, license_headers}; +use actix_web::{web, App, HttpServer}; +use kagero::printer::{Printer, Colors}; -/*#[actix_web::main] -async fn main() -> std::io::Result<()> { - HttpServer::new(|| { - App::new() +/// Init +/// +/// Server preparations. +fn init() -> io::Result { + // Safe Args Collect to String + let args: Vec = env::args_os() + .filter_map(|x| { + let Some(arg) = x.to_str() else { + return None; + }; + Some(arg.to_string()) }) - .bind(("127.0.0.1", 8080))? - .run() - .await -}*/ + .collect(); + + // Config + Config::load_cascade(args.get(1)) +} + +/// Server +/// +/// Server startup. +async fn server(cfg: Config) -> io::Result<()> { + // ---- Server Init ---- + let bindaddr = cfg.bindaddr.clone(); + let unbound_server = HttpServer::new(move || { + // Initialize state + let Ok(state) = CyrkensiaState::new(cfg.clone()) else { + Printer::default().errorln("Cyrkensia failed trying to initialize!", Colors::YellowBright); + exit(1); + }; + + // ---- App ---- + App::new() + // State + .app_data(web::Data::new(state)) + // Middleware + .wrap(cors_everywhere()) + .wrap(source_headers()) + .wrap(license_headers()) + //Routes + .route("/", web::get().to(hostinfo)) + .route("/{album}", web::get().to(index)) + }); + + // ---- Server Bind ---- + #[cfg(target_family = "unix")] + let server = if bindaddr.starts_with('/') { + unbound_server.bind_uds(bindaddr)? + } else { + unbound_server.bind(bindaddr)? + }; + + #[cfg(not(target_family = "unix"))] + let server = unbound_server.bind(bindaddr)?; + + // ---- Ignite ---- + server.run().await +} + +#[actix_web::main] +async fn main() { + // Init + let mut console = Printer::default(); + let Ok(config) = init() else { + console.errorln("Failed to read the config file for Cyrkensia!", Colors::RedBright); + console.errorln(&("See ".to_owned() + WIKI_HELP_URL + " for more."), Colors::Yellow); + exit(1); + }; + + // Start + if let Err(serv) = server(config).await { + console.errorln("An error occured while running the server:", Colors::Red); + eprintln!("{serv}"); + } -fn main() { - println!("This is still WIP!!!"); + // Exit + console.println("Successfully stopped the Cyrkensia server!", Colors::Cyan); + exit(0) } \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index 843dd57..62474dc 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,12 +1,14 @@ use serde::{Serialize, Deserialize}; use serde_json::from_str; +use dirs::home_dir; +use uuid::Uuid; use std::cmp::PartialEq; use std::convert::From; +use std::path::Path; use std::io; use std::fs; -use std::path::Path; -use uuid::Uuid; -use super::{Owner, Hostinfo}; +use std::env; +use super::{Owner, Hostinfo, meta}; /// Configuration /// @@ -44,16 +46,6 @@ pub struct Config { /// The IP address to bind to, e.g. `127.0.0.1`, `0.0.0.0:80` or a Unix socket (Unix only). pub bindaddr: String, - /// TLS Certificate (Optional) - /// - /// The Path to the TLS certificate. TLS will only be activated if both certificate and key are provided. - pub tlscert: Option, - - /// TLS Key (Optional) - /// - /// The path to the TLS key. TLS will only be activated if both certificate and key are provided. - pub tlskey: Option, - /// Owners /// /// List of repository [maintainers](Owner) @@ -81,6 +73,26 @@ impl Config { pub fn load_json(data: &str) -> io::Result { Ok(from_str(data)?) } + + /// Cascade Loading + /// + /// Attempts to load a config file by: + /// 1. First command-line argument + /// 2. `CYRKENSIA_CONFIG` environment variable + /// 3. `~/.config/cyrkensia/config.json` file + pub fn load_cascade(cmdarg: Option<&String>) -> io::Result { + // Select extra path + let envvar = env::var(meta::CONFIG_ENVVAR); + + // Read config from extra location + if let Some(path) = cmdarg.or_else(|| envvar.as_ref().ok()) { + return Config::load_file(path); + } + + // Read with default path + let localpath = home_dir().unwrap_or_default().join(meta::CONFIG_PATH); + Config::load_file(localpath) + } } impl From for Config { @@ -92,8 +104,6 @@ impl From for Config { icon: x.icon, htpasswd: None, bindaddr: "".to_string(), - tlscert: None, - tlskey: None, owners: x.owners, max_age: None } @@ -108,8 +118,6 @@ impl PartialEq for Config { self.icon == other.icon && self.htpasswd == other.htpasswd && self.bindaddr == other.bindaddr && - self.tlscert == other.tlscert && - self.tlskey == other.tlskey && self.owners == other.owners } } \ No newline at end of file diff --git a/src/hostinfo.rs b/src/hostinfo.rs index d8ede21..10a0888 100644 --- a/src/hostinfo.rs +++ b/src/hostinfo.rs @@ -142,31 +142,17 @@ impl Hostinfo { }; // Read data - let mut m = Metadata::load(path.join(".metadata.json"))?; + let m = Metadata::load(path.join(".metadata.json"))?; let c = Hostinfo::list_files(path)?; - // List files with default Artist - if let Some(defart) = m.default { - for file in c.0 { - if let Some(other_arts) = m.artists.get_mut(&file) { - // Add default Artist to listed file if it's not included yet - if other_arts.contains(&defart) { - other_arts.push(defart); - } - } else { - // Append all yet unlisted files - m.artists.insert(file, vec![defart]); - } - } - } - // Create Album Ok(Album { name: m.name, cover: m.cover, path: fname.to_string(), - files: m.artists, + files: c.0, size: c.1, + artists: m.artists, }) } diff --git a/src/lib.rs b/src/lib.rs index 92392b4..2accb82 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -67,6 +67,7 @@ pub mod meta { pub const NAME_RICH: &str = "Cyrkensia"; pub const AUTHORS: &str = env!("CARGO_PKG_AUTHORS"); pub const REPOSITORY: &str = env!("CARGO_PKG_REPOSITORY"); + pub const WIKI_HELP_URL: &str = concat!(env!("CARGO_PKG_REPOSITORY"), "/wiki/Troubleshooting"); pub const DESCRIPTION: &str = env!("CARGO_PKG_DESCRIPTION"); pub const LICENSE: &str = "EUPL-1.2"; pub const LICENSE_RICH: &str = "European Union Public License v1.2"; @@ -75,11 +76,11 @@ pub mod meta { pub const RUSTC_VERSION: &str = env!("RUSTC_VERSION"); pub const COMPILE_DATE: &str = env!("COMPILE_DATE"); pub const TARGET: &str = env!("TARGET"); - pub const USERAGENT: &str = concat!( - env!("CARGO_PKG_NAME"), - "/", - env!("CARGO_PKG_VERSION") - ); + pub const USERAGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION")); + pub const CONFIG_ENVVAR: &str = "CYRKENSIA_CONFIG"; + pub const CONFIG_PATH: &str = concat!(".config/", env!("CARGO_PKG_NAME"), "/config.json"); + pub const USERS_ENVVAR: &str = "CYRKENSIA_USERS"; + pub const USERS_PATH: &str = concat!(".config/", env!("CARGO_PKG_NAME"), "/users.json"); } #[cfg(feature = "server")] @@ -92,4 +93,4 @@ pub mod server; /// Account database /// /// Submodule containing the [Account](accounts::Account) struct and related cryptographic and wrapper functions. -pub mod account; \ No newline at end of file +pub mod account; diff --git a/src/metadata.rs b/src/metadata.rs index f18a92d..c57429c 100644 --- a/src/metadata.rs +++ b/src/metadata.rs @@ -1,7 +1,6 @@ use serde::{Serialize, Deserialize}; use serde_json::from_str; use uuid::Uuid; -use std::collections::HashMap; use std::fmt::{Display, Result}; use std::cmp::PartialEq; use std::convert::From; @@ -25,30 +24,21 @@ pub struct Metadata { /// The asset key representing the album cover art. pub cover: String, - /// Default Artist + /// Artists /// - /// Represents the UUIDv4 of the main [Artist] of this album - pub default: Option, - - /// Additional Artists - /// - /// Map of which additional artists are associated with what music track - pub artists: HashMap> + /// Represents the UUIDv4 of the [Artist] of this album + pub artists: Vec } impl Metadata { /// New Metadata /// /// Creates new [Metadata]. Authors can be appended later on. - pub fn new(name: String, cover: String, default_artist: Option, artists: Option>>) -> Metadata { + pub fn new(name: String, cover: String, artists: Vec) -> Metadata { Metadata { name, cover, - default: default_artist, - artists: match artists { - Some(x) => x, - None => HashMap::new() - } + artists } } @@ -66,8 +56,7 @@ impl From for Metadata { Metadata { name: x.name, cover: x.cover, - artists: x.files, - default: None + artists: x.artists } } } @@ -75,8 +64,7 @@ impl From for Metadata { impl PartialEq for Metadata { fn eq(&self, other: &Self) -> bool { self.name == other.name && - self.cover == other.cover && - self.artists == other.artists + self.cover == other.cover } } diff --git a/src/server/routes.rs b/src/server/routes.rs index 0f01e16..e9d3918 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -1,6 +1,7 @@ use std::time::Instant; use actix_web::{web, Responder, HttpRequest, HttpResponse}; use actix_web::http::header::ContentType; +use serde::Deserialize; use super::{CyrkensiaState, responses, uri_noquery}; use crate::{Hostinfo, Artist, Metadata, Album}; @@ -60,6 +61,7 @@ pub async fn hostinfo(req: HttpRequest, data: web::Data) -> impl finalres } +#[derive(Deserialize)] /// Index Route Params /// /// Simple struct containing the param-name and param-type needed for the [index] route. @@ -74,38 +76,33 @@ pub async fn index(p: web::Path, data: web::Data) - // Extract album name let path = p.into_inner(); // Read files and album name depending on if cache is enabled or not - let meta: (String, usize, Vec) = match data.config.max_age { - Some(_) => { - // Cached files and metadata - let Ok(hostinfo) = data.hostinfo.lock() else { - return responses::server_500(None::); - }; - let Some(album) = hostinfo.albums.clone().into_iter().find(|x| x.path == path.album) else { - return responses::client_404(Some("Album not found")); - }; - - // Return tri-tuple - let files: Vec = album.files.keys().cloned().collect(); - (album.name, files.len(), files) + let meta: (String, usize, Vec) = if data.config.max_age.is_some() { + // Cached files and metadata + let Ok(hostinfo) = data.hostinfo.lock() else { + return responses::server_500(None::); + }; + let Some(album) = hostinfo.albums.clone().into_iter().find(|x| x.path == path.album) else { + return responses::client_404(Some("Album not found")); + }; - }, - None => { - // Attempt to find album in filesystem - let Ok(path) = Album::find(&data.config.root, &path.album) else { - return responses::client_404(Some("Album not found")); - }; + // Return tri-tuple + (album.name, album.files.len(), album.files) + } else { + // Attempt to find album in filesystem + let Ok(path) = Album::find(&data.config.root, &path.album) else { + return responses::client_404(Some("Album not found")); + }; - // Ad-hoc metadata and files - let Ok(album) = Metadata::load(path.join(".metadata.json")) else { - return responses::client_404(Some("Album not found")); - }; - let Ok(files) = Hostinfo::list_files(path) else { - return responses::client_404(Some("Album not accessable")); - }; + // Ad-hoc metadata and files + let Ok(album) = Metadata::load(path.join(".metadata.json")) else { + return responses::client_404(Some("Album not found")); + }; + let Ok(files) = Hostinfo::list_files(path) else { + return responses::client_404(Some("Album not accessable")); + }; - // Return tri-tuple - (album.name, files.0.len(), files.0) - } + // Return tri-tuple + (album.name, files.0.len(), files.0) }; // Codegen From 90b5a12991674bbb1f95f62930e54a6562b51c68 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Sun, 4 Dec 2022 05:14:14 +0100 Subject: [PATCH 30/36] Small fixes and better code --- src/bin/cyrkensia.rs | 14 +++++++++----- src/config.rs | 2 +- src/hostinfo.rs | 15 --------------- src/server/redirect.rs | 13 ++++++++++++- src/server/routes.rs | 20 ++++++++++++-------- 5 files changed, 34 insertions(+), 30 deletions(-) diff --git a/src/bin/cyrkensia.rs b/src/bin/cyrkensia.rs index e5d2b7c..5e07ec5 100644 --- a/src/bin/cyrkensia.rs +++ b/src/bin/cyrkensia.rs @@ -3,6 +3,7 @@ use std::process::exit; use cyrkensia::Config; use cyrkensia::meta::WIKI_HELP_URL; use cyrkensia::server::CyrkensiaState; +use cyrkensia::server::redirect::trail_slash; use cyrkensia::server::routes::{index, hostinfo}; use cyrkensia::server::middleware::{cors_everywhere, source_headers, license_headers}; use actix_web::{web, App, HttpServer}; @@ -31,11 +32,12 @@ fn init() -> io::Result { /// Server startup. async fn server(cfg: Config) -> io::Result<()> { // ---- Server Init ---- + let mut printer = Printer::default(); let bindaddr = cfg.bindaddr.clone(); let unbound_server = HttpServer::new(move || { // Initialize state let Ok(state) = CyrkensiaState::new(cfg.clone()) else { - Printer::default().errorln("Cyrkensia failed trying to initialize!", Colors::YellowBright); + eprintln!("Cyrkensia failed trying to initialize!"); exit(1); }; @@ -49,7 +51,8 @@ async fn server(cfg: Config) -> io::Result<()> { .wrap(license_headers()) //Routes .route("/", web::get().to(hostinfo)) - .route("/{album}", web::get().to(index)) + .route("/{album}/", web::get().to(index)) + .route("/{album}", web::get().to(trail_slash)) }); // ---- Server Bind ---- @@ -64,6 +67,7 @@ async fn server(cfg: Config) -> io::Result<()> { let server = unbound_server.bind(bindaddr)?; // ---- Ignite ---- + printer.println("Cyrkensia server successfully started!", Colors::CyanBright); server.run().await } @@ -73,17 +77,17 @@ async fn main() { let mut console = Printer::default(); let Ok(config) = init() else { console.errorln("Failed to read the config file for Cyrkensia!", Colors::RedBright); - console.errorln(&("See ".to_owned() + WIKI_HELP_URL + " for more."), Colors::Yellow); + console.errorln(&("See ".to_owned() + WIKI_HELP_URL + " for more."), Colors::YellowBright); exit(1); }; // Start if let Err(serv) = server(config).await { - console.errorln("An error occured while running the server:", Colors::Red); + console.errorln("An error occured while running the server:", Colors::RedBright); eprintln!("{serv}"); } // Exit - console.println("Successfully stopped the Cyrkensia server!", Colors::Cyan); + console.println("Cyrkensia server successfully stopped!", Colors::CyanBright); exit(0) } \ No newline at end of file diff --git a/src/config.rs b/src/config.rs index 62474dc..cb2ec10 100644 --- a/src/config.rs +++ b/src/config.rs @@ -53,7 +53,7 @@ pub struct Config { /// Maximum Age /// - /// The maximum age of the [Hostinfo] in milliseconds as a [u64]. If [None], the Hostinfo will always be regenerated when its route is accessed. + /// The maximum age of the [Hostinfo] in *seconds* as a [u64]. If [None], the Hostinfo will always be regenerated when its route is accessed. /// This basically activates caching. pub max_age: Option } diff --git a/src/hostinfo.rs b/src/hostinfo.rs index 10a0888..3af1560 100644 --- a/src/hostinfo.rs +++ b/src/hostinfo.rs @@ -38,11 +38,6 @@ pub struct Hostinfo { /// The total size of the repository and its music files in bytes. pub size: u128, - /// Origin URL - /// - /// The URL to get an updated version of this Hostinfo - pub origin: String, - /// Albums /// /// List of all albums that this Cyrkensia repository provides. @@ -60,13 +55,6 @@ pub struct Hostinfo { } impl Hostinfo { - /// Set Origin - /// - /// Sets the origin of the Hostinfo. This function solely exists to remind library users to swap out the empty default origin. - pub fn set_origin(&mut self, org: String) { - self.origin = org - } - /// Generate empty Hostinfo /// /// Generates an empty Hostinfo. @@ -77,7 +65,6 @@ impl Hostinfo { uuid: Uuid::new_v4(), secured: false, size: 0, - origin: "".to_string(), albums: Vec::new(), owners: Vec::new(), artists: Vec::new() @@ -216,7 +203,6 @@ impl From for Hostinfo { uuid: x.uuid, secured: x.htpasswd.is_some(), size: 0, - origin: "".to_string(), albums: Vec::new(), owners: x.owners, artists: Vec::new() @@ -231,7 +217,6 @@ impl PartialEq for Hostinfo { self.uuid == other.uuid && self.secured == other.secured && self.size == other.size && - self.origin == other.origin && self.albums == other.albums && self.owners == other.owners } diff --git a/src/server/redirect.rs b/src/server/redirect.rs index de0fca7..91e5b3b 100644 --- a/src/server/redirect.rs +++ b/src/server/redirect.rs @@ -1,5 +1,6 @@ -use actix_web::{HttpResponse, Responder, http::header::LOCATION}; +use actix_web::{HttpResponse, Responder, http::header::LOCATION, HttpRequest}; use crate::meta; +use super::uri_noquery; /// Redirect /// @@ -22,4 +23,14 @@ pub fn repository() -> impl Responder { /// Redirects to the license text. pub fn license() -> impl Responder { redirect(meta::LICENSE_URL) +} + +/// Trailing slash redirect +/// +/// Redirects the user to a URL with a trailing slash. +pub async fn trail_slash(req: HttpRequest) -> impl Responder { + let uri = uri_noquery(req.uri()); + HttpResponse::Found() + .insert_header(("Location", uri + "/")) + .finish() } \ No newline at end of file diff --git a/src/server/routes.rs b/src/server/routes.rs index e9d3918..1776091 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -1,14 +1,14 @@ use std::time::Instant; -use actix_web::{web, Responder, HttpRequest, HttpResponse}; +use actix_web::{web, Responder, HttpResponse}; use actix_web::http::header::ContentType; use serde::Deserialize; -use super::{CyrkensiaState, responses, uri_noquery}; +use super::{CyrkensiaState, responses}; use crate::{Hostinfo, Artist, Metadata, Album}; /// Hostinfo Route /// /// Route for serving a [Hostinfo]. Server needs [CyrkensiaState] in `.app_data()` for this. -pub async fn hostinfo(req: HttpRequest, data: web::Data) -> impl Responder { +pub async fn hostinfo(data: web::Data) -> impl Responder { // Get config let Some(delay) = data.config.max_age else { // Ad hoch Hostinfo @@ -51,8 +51,7 @@ pub async fn hostinfo(req: HttpRequest, data: web::Data) -> impl } // Set Origin URL - let mut final_hostinfo = hostinfo.clone(); - final_hostinfo.set_origin(uri_noquery(req.uri())); + let final_hostinfo = hostinfo.clone(); // Return final result let Ok(finalres) = responses::hostinfo_data(&final_hostinfo) else { @@ -66,7 +65,7 @@ pub async fn hostinfo(req: HttpRequest, data: web::Data) -> impl /// /// Simple struct containing the param-name and param-type needed for the [index] route. pub struct IndexParams { - album: String + pub album: String } /// Album Index Route @@ -106,11 +105,16 @@ pub async fn index(p: web::Path, data: web::Data) - }; // Codegen - let headstr = format!("

{} ({})

\n", meta.0, meta.1); + let headmeta = r""; + let headstr = format!("

{} ({})

", meta.0, meta.1); let bodystr = meta.2.into_iter().fold(String::new(), |total, item| total + &format!("{}
\n", item, item)); // Send response HttpResponse::Ok() .content_type(ContentType::html()) - .body(headstr + &bodystr) + .body(format!("{}{}{}", headmeta, headstr, bodystr)) } \ No newline at end of file From 1ceca0a3fba034c532ad877ee9ff8e70e9c0ab85 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Sun, 4 Dec 2022 14:34:01 +0100 Subject: [PATCH 31/36] Timestamp logging and more macros --- Cargo.toml | 5 +++-- src/artist.rs | 2 +- src/bin/cyrkensia.rs | 27 ++++++++++++++++++++------- src/lib.rs | 10 ++++------ src/metadata.rs | 2 +- src/server/mod.rs | 30 +++++++++++++++++++++++++++++- 6 files changed, 58 insertions(+), 18 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 2008932..f0cd0eb 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -27,6 +27,7 @@ kagero = { version = "0.4", default-features = false, features = ["printer"] } actix-web = { version = "4", optional = true } actix-cors = { version = "0.6", optional = true } blake3 = { version = "1.3", optional = true } +chrono = { version = "*", optional = true, features = ["std", "clock"] } # Accounts only argon2 = { version = "0.4", optional = true, features = ["std", "password-hash"] } @@ -35,7 +36,7 @@ rand = { version = "0.8", optional = true, features = ["std"] } [features] default = ["server", "accounts"] accounts = ["argon2", "rand"] -server = ["actix-web", "actix-cors", "blake3"] +server = ["actix-web", "actix-cors", "blake3", "chrono"] [build-dependencies] chrono = "0.4" @@ -53,7 +54,7 @@ required-features = [] [profile.release] lto = true strip = true -debug = true +debug = false [package.metadata.docs.rs] targets = [ diff --git a/src/artist.rs b/src/artist.rs index ddf10d9..6856dc9 100644 --- a/src/artist.rs +++ b/src/artist.rs @@ -61,7 +61,7 @@ impl Artist { /// Read multiple folders' .artists.json /// - /// Reads the .artists.json of multiple folders. Essentially like [load_multiple_artists], but with `.artists.json` appended. + /// Reads the .artists.json of multiple folders. Essentially like `load_multiple_artists`, but with `.artists.json` appended. pub fn read_multiple(paths: &[String]) -> io::Result> { let conv_paths: Vec = paths.iter() .map(|x| Path::new(x).join(".artists.json")).collect(); diff --git a/src/bin/cyrkensia.rs b/src/bin/cyrkensia.rs index 5e07ec5..d6e7c13 100644 --- a/src/bin/cyrkensia.rs +++ b/src/bin/cyrkensia.rs @@ -1,6 +1,6 @@ use std::{env, io}; use std::process::exit; -use cyrkensia::Config; +use cyrkensia::{Config, timelog, timestamp}; use cyrkensia::meta::WIKI_HELP_URL; use cyrkensia::server::CyrkensiaState; use cyrkensia::server::redirect::trail_slash; @@ -8,6 +8,7 @@ use cyrkensia::server::routes::{index, hostinfo}; use cyrkensia::server::middleware::{cors_everywhere, source_headers, license_headers}; use actix_web::{web, App, HttpServer}; use kagero::printer::{Printer, Colors}; +use chrono::Local; /// Init /// @@ -67,7 +68,8 @@ async fn server(cfg: Config) -> io::Result<()> { let server = unbound_server.bind(bindaddr)?; // ---- Ignite ---- - printer.println("Cyrkensia server successfully started!", Colors::CyanBright); + printer.print(timelog!(), Colors::Cyan) + .println("Cyrkensia server successfully started!", Colors::CyanBright); server.run().await } @@ -77,17 +79,28 @@ async fn main() { let mut console = Printer::default(); let Ok(config) = init() else { console.errorln("Failed to read the config file for Cyrkensia!", Colors::RedBright); - console.errorln(&("See ".to_owned() + WIKI_HELP_URL + " for more."), Colors::YellowBright); + morehelp(&mut console); exit(1); }; // Start - if let Err(serv) = server(config).await { - console.errorln("An error occured while running the server:", Colors::RedBright); - eprintln!("{serv}"); + if let Err(segv) = server(config).await { + console.error(timelog!(), Colors::Red) + .errorln("An error occured while running the server:", Colors::RedBright); + eprintln!("{segv}"); + morehelp(&mut console); + exit(1); } // Exit - console.println("Cyrkensia server successfully stopped!", Colors::CyanBright); + console.print(timelog!(), Colors::Cyan) + .println("Cyrkensia server successfully stopped!", Colors::CyanBright); exit(0) +} + +/// More help +/// +/// Tells you to google the error. +fn morehelp(cmd: &mut Printer) { + cmd.errorln(&("See ".to_owned() + WIKI_HELP_URL + " for more."), Colors::YellowBright); } \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index 2accb82..aced3a6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -12,10 +12,10 @@ //! If you're searching for Cyrkensia as a binary, see the [crates.io](https://crates.io/crates/cyrkensia) or [GitHub](https://github.com/Stridsvagn69420/Cyrkensia) page for more. //! //! ## Features -//! By default, the `server` feature is enabled. The latter is only relevant for people who write a custom Cyrkensia server. +//! By default, the `accounts` and `server` features are enabled. The latter is only relevant for people who write a custom Cyrkensia server. //! You can disable `server` with this: //! ```toml -//! cyrkensia = { version = "1", default-features = false } +//! cyrkensia = { version = "1", default-features = false, features = ["accounts"] } //! ``` //! //! ## Examples @@ -30,8 +30,6 @@ //! let artists = Artist::read_multiple(&config.root).unwrap(); //! // Generate the corresponding Hostinfo //! let mut hostinfo = Hostinfo::generate(&config, &artists).unwrap(); -//! // Optionally set the origin -//! hostinfo.set_origin("https://foo.bar/my-hostinfo.json".to_string()); //! ``` /// Owner struct @@ -92,5 +90,5 @@ pub mod server; #[cfg(feature = "accounts")] /// Account database /// -/// Submodule containing the [Account](accounts::Account) struct and related cryptographic and wrapper functions. -pub mod account; +/// Submodule containing the [Account](account::Account) struct and related cryptographic and wrapper functions. +pub mod account; \ No newline at end of file diff --git a/src/metadata.rs b/src/metadata.rs index c57429c..d0223f1 100644 --- a/src/metadata.rs +++ b/src/metadata.rs @@ -26,7 +26,7 @@ pub struct Metadata { /// Artists /// - /// Represents the UUIDv4 of the [Artist] of this album + /// Represents the UUIDv4 of the [Artist](super::Artist) of this album pub artists: Vec } diff --git a/src/server/mod.rs b/src/server/mod.rs index 5510c4f..e176360 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -111,4 +111,32 @@ impl CyrkensiaState { accounts }) } -} \ No newline at end of file +} + +/// Timestamp +/// +/// Creates the current timestamp formatted as `[%Y-%m-%d %H:%M:%S]`. +/// Requires [chrono::Local]. +/// Evaluates to `Local::now().format("[%Y-%m-%d %H:%M:%S]").to_string()`. +#[macro_export] +macro_rules! timestamp { + () => { + Local::now().format("[%Y-%m-%d %H:%M:%S]").to_string() + }; +} +pub use timestamp; + +/// Timelog +/// +/// Formats a given message with a timestamp. +/// If no message is provided, it just return [timestamp!], but with a whitespace added. +#[macro_export] +macro_rules! timelog { + () => { + (timestamp!() + " ").as_str() + }; + ($msg:expr) => { + (timestamp!() + " " + $msg).as_str() + }; +} +pub use timelog; \ No newline at end of file From b79cfa3b3c15a5fefff4ebe2dad8ea68716295e7 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Sun, 4 Dec 2022 17:37:54 +0100 Subject: [PATCH 32/36] Artists live in central artists.json file now --- src/artist.rs | 47 +++++++++++++++++++++----------------------- src/config.rs | 9 ++++++++- src/lib.rs | 4 +++- src/server/mod.rs | 2 +- src/server/routes.rs | 10 ++++++---- 5 files changed, 40 insertions(+), 32 deletions(-) diff --git a/src/artist.rs b/src/artist.rs index 6856dc9..2cce581 100644 --- a/src/artist.rs +++ b/src/artist.rs @@ -1,12 +1,12 @@ use serde::{Serialize, Deserialize}; use uuid::Uuid; +use dirs::home_dir; use std::fmt::{Display, Result}; use std::cmp::PartialEq; use std::convert::From; -use std::path::{Path, PathBuf}; -use std::fs; -use std::io; -use super::Owner; +use std::path::Path; +use std::{fs, io, env}; +use super::{Owner, meta}; /// Artist /// @@ -39,35 +39,32 @@ impl Artist { } } - /// Load single .artists.json + /// Load artists.json /// - /// Loads a single `.artists.json` as a [Vec] of [Artist]s - pub fn load_artists(path: impl AsRef) -> io::Result> { + /// Loads a `artists.json` as a [Vec] of [Artist]s + pub fn load(path: impl AsRef) -> io::Result> { let rawdata = fs::read_to_string(path)?; Ok(serde_json::from_str(rawdata.as_str())?) } - /// Load multiple .artists.json + /// Cascade Loading /// - /// Loads multiple `.artists.json` as a combined [Vec] of [Artist]s - pub fn load_multiple_artists(paths: Vec>) -> io::Result> { - let mut res: Vec = Vec::new(); - for pth in paths { - let artst = Artist::load_artists(pth)?; - res.extend(artst); + /// Attempts to load a config file by: + /// 1. Provided [String] + /// 2. `CYRKENSIA_ARTISTS` environment variable + /// 3. `~/.config/cyrkensia/artists.json` file + pub fn load_cascade(cmdarg: &Option) -> io::Result> { + // Select extra path + let envvar = env::var(meta::ARTISTS_ENVVAR); + + // Read config from extra location + if let Some(path) = cmdarg.as_ref().or_else(|| envvar.as_ref().ok()) { + return Artist::load(path); } - Ok(res) - } - /// Read multiple folders' .artists.json - /// - /// Reads the .artists.json of multiple folders. Essentially like `load_multiple_artists`, but with `.artists.json` appended. - pub fn read_multiple(paths: &[String]) -> io::Result> { - let conv_paths: Vec = paths.iter() - .map(|x| Path::new(x).join(".artists.json")).collect(); - - // Read all artists - Artist::load_multiple_artists(conv_paths) + // Read with default path + let localpath = home_dir().unwrap_or_default().join(meta::ARTISTS_PATH); + Artist::load(localpath) } } diff --git a/src/config.rs b/src/config.rs index cb2ec10..30c7a67 100644 --- a/src/config.rs +++ b/src/config.rs @@ -41,9 +41,15 @@ pub struct Config { /// Note that the file must be a JSON of [Vec]<[Account](super::account::Account)>. pub htpasswd: Option, + /// Artists file + /// + /// The path to the central artists file, used for displaying an album's artists. + /// It will cascade load the file as described in [Artist](crate::Artist)'s `load_cascade()` function. + pub artists: Option, + /// Bind address /// - /// The IP address to bind to, e.g. `127.0.0.1`, `0.0.0.0:80` or a Unix socket (Unix only). + /// The IP address to bind to, e.g. `127.0.0.1`, `0.0.0.0:80` or a Unix Domain Socket (Unix only). pub bindaddr: String, /// Owners @@ -104,6 +110,7 @@ impl From for Config { icon: x.icon, htpasswd: None, bindaddr: "".to_string(), + artists: None, owners: x.owners, max_age: None } diff --git a/src/lib.rs b/src/lib.rs index aced3a6..06b9fdf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -27,7 +27,7 @@ //! // Load the config file //! let config = Config::load_file("config.json").unwrap(); //! // Load the artists -//! let artists = Artist::read_multiple(&config.root).unwrap(); +//! let artists = Artist::load_cascade(&None).unwrap(); //! // Generate the corresponding Hostinfo //! let mut hostinfo = Hostinfo::generate(&config, &artists).unwrap(); //! ``` @@ -79,6 +79,8 @@ pub mod meta { pub const CONFIG_PATH: &str = concat!(".config/", env!("CARGO_PKG_NAME"), "/config.json"); pub const USERS_ENVVAR: &str = "CYRKENSIA_USERS"; pub const USERS_PATH: &str = concat!(".config/", env!("CARGO_PKG_NAME"), "/users.json"); + pub const ARTISTS_ENVVAR: &str = "CYRKENSIA_ARTISTS"; + pub const ARTISTS_PATH: &str = concat!(".config/", env!("CARGO_PKG_NAME"), "/artists.json"); } #[cfg(feature = "server")] diff --git a/src/server/mod.rs b/src/server/mod.rs index e176360..7c6b029 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -91,7 +91,7 @@ impl CyrkensiaState { // State with caching if cfg.max_age.is_some() { - let arts = Artist::read_multiple(&cfg.root)?; + let arts = Artist::load_cascade(&cfg.artists)?; let hostinfo = Hostinfo::generate(&cfg, &arts)?; return Ok(CyrkensiaState { last_updated: Mutex::new(Instant::now()), diff --git a/src/server/routes.rs b/src/server/routes.rs index 1776091..0e08e85 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -12,7 +12,7 @@ pub async fn hostinfo(data: web::Data) -> impl Responder { // Get config let Some(delay) = data.config.max_age else { // Ad hoch Hostinfo - let Ok(artists) = Artist::read_multiple(&data.config.root) else { + let Ok(artists) = Artist::load_cascade(&data.config.artists) else { return responses::server_500(Some("Failed to generate hostinfo")); }; let Ok(resp) = responses::hostinfo_json(&data.config, &artists) else { @@ -35,7 +35,7 @@ pub async fn hostinfo(data: web::Data) -> impl Responder { // Update Cache if expired if last_updated.elapsed().as_secs() >= delay { // Read updated artists - let Ok(new_artists) = Artist::read_multiple(&data.config.root) else { + let Ok(new_artists) = Artist::load_cascade(&data.config.artists) else { return responses::server_500(Some("Failed to update hostinfo")); }; @@ -105,11 +105,13 @@ pub async fn index(p: web::Path, data: web::Data) - }; // Codegen - let headmeta = r""; + + "###; let headstr = format!("

{} ({})

", meta.0, meta.1); let bodystr = meta.2.into_iter().fold(String::new(), |total, item| total + &format!("{}
\n", item, item)); From 036e32363b7756bef877e723ac7975abcdfa13a1 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Sun, 4 Dec 2022 19:44:19 +0100 Subject: [PATCH 33/36] "Verbose error output" --- src/bin/cyrkensia.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/bin/cyrkensia.rs b/src/bin/cyrkensia.rs index d6e7c13..6c03448 100644 --- a/src/bin/cyrkensia.rs +++ b/src/bin/cyrkensia.rs @@ -38,7 +38,9 @@ async fn server(cfg: Config) -> io::Result<()> { let unbound_server = HttpServer::new(move || { // Initialize state let Ok(state) = CyrkensiaState::new(cfg.clone()) else { - eprintln!("Cyrkensia failed trying to initialize!"); + let red: &str = Colors::RedBright.as_ref(); + eprintln!("{red}{}\x1b[0m", timelog!("Cyrkensia failed trying to initialize!")); + eprintln!("See {WIKI_HELP_URL} for more."); exit(1); }; From e1da6b570f55e0b75fdb837ced3d9a42464c5144 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Wed, 28 Dec 2022 21:54:06 +0100 Subject: [PATCH 34/36] CLI tool wip, server message wip, logger wip, file routes wip --- Cargo.lock | 145 +++++++++++++++++++++++-------------------- Cargo.toml | 12 ++-- src/bin/cyrkensia.rs | 16 ++--- src/server/routes.rs | 90 ++++++++++++++++++++++++++- 4 files changed, 180 insertions(+), 83 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 47187f7..4949822 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -295,18 +295,18 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "blake2" -version = "0.10.5" +version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b12e5fd123190ce1c2e559308a94c9bacad77907d4c6005d9e58fe1a0689e55e" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" dependencies = [ "digest", ] [[package]] name = "blake3" -version = "1.3.2" +version = "1.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "895adc16c8b3273fbbc32685a7d55227705eda08c01e77704020f3491924b44b" +checksum = "42ae2468a89544a466886840aa467a25b766499f4f04bf7d9fcd10ecee9fccef" dependencies = [ "arrayref", "arrayvec", @@ -369,9 +369,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.77" +version = "1.0.78" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4" +checksum = "a20104e2335ce8a659d6dd92a51a767a0c062599c73b343fd152cb401e828c3d" dependencies = [ "jobserver", ] @@ -392,7 +392,7 @@ dependencies = [ "js-sys", "num-integer", "num-traits", - "time 0.1.44", + "time 0.1.45", "wasm-bindgen", "winapi", ] @@ -421,9 +421,9 @@ checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" [[package]] name = "cookie" -version = "0.16.1" +version = "0.16.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "344adc371239ef32293cb1c4fe519592fcf21206c79c02854320afcdf3ab4917" +checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb" dependencies = [ "percent-encoding", "time 0.3.17", @@ -466,9 +466,9 @@ dependencies = [ [[package]] name = "cxx" -version = "1.0.82" +version = "1.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4a41a86530d0fe7f5d9ea779916b7cadd2d4f9add748b99c2c029cbbdfaf453" +checksum = "5add3fc1717409d029b20c5b6903fc0c0b02fa6741d820054f4a2efa5e5816fd" dependencies = [ "cc", "cxxbridge-flags", @@ -478,9 +478,9 @@ dependencies = [ [[package]] name = "cxx-build" -version = "1.0.82" +version = "1.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "06416d667ff3e3ad2df1cd8cd8afae5da26cf9cec4d0825040f88b5ca659a2f0" +checksum = "b4c87959ba14bc6fbc61df77c3fcfe180fc32b93538c4f1031dd802ccb5f2ff0" dependencies = [ "cc", "codespan-reporting", @@ -493,15 +493,15 @@ dependencies = [ [[package]] name = "cxxbridge-flags" -version = "1.0.82" +version = "1.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "820a9a2af1669deeef27cb271f476ffd196a2c4b6731336011e0ba63e2c7cf71" +checksum = "69a3e162fde4e594ed2b07d0f83c6c67b745e7f28ce58c6df5e6b6bef99dfb59" [[package]] name = "cxxbridge-macro" -version = "1.0.82" +version = "1.0.85" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a08a6e2fcc370a089ad3b4aaf54db3b1b4cee38ddabce5896b33eb693275f470" +checksum = "3e7e2adeb6a0d4a282e581096b06e1791532b7d576dcde5ccd9382acf55db8e6" dependencies = [ "proc-macro2", "quote", @@ -519,9 +519,9 @@ dependencies = [ "chrono", "dirs", "kagero", - "rand", "serde", "serde_json", + "sha2", "uuid", ] @@ -681,9 +681,9 @@ checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" [[package]] name = "hermit-abi" -version = "0.1.19" +version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" dependencies = [ "libc", ] @@ -757,9 +757,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4217ad341ebadf8d8e724e264f13e593e0648f5b3e94b3896a5df283be015ecc" +checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440" [[package]] name = "jobserver" @@ -797,15 +797,15 @@ checksum = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388" [[package]] name = "libc" -version = "0.2.137" +version = "0.2.139" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fc7fcc620a3bff7cdd7a365be3376c97191aeaccc2a603e600951e452615bf89" +checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79" [[package]] name = "link-cplusplus" -version = "1.0.7" +version = "1.0.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9272ab7b96c9046fbc5bc56c06c117cb639fe2d509df0c421cad82d2915cf369" +checksum = "ecd207c9c713c34f95a097a5b029ac2ce6010530c7b49d7fea24d977dede04f5" dependencies = [ "cc", ] @@ -901,9 +901,9 @@ dependencies = [ [[package]] name = "num_cpus" -version = "1.14.0" +version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6058e64324c71e02bc2b150e4f3bc8286db6c83092132ffa3f6b1eab0f9def5" +checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" dependencies = [ "hermit-abi", "libc", @@ -927,9 +927,9 @@ dependencies = [ [[package]] name = "parking_lot_core" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dc9e0dc2adc1c69d09143aff38d3d30c5c3f0df0dad82e6d25547af174ebec0" +checksum = "7ff9f3fef3968a3ec5945535ed654cb38ff72d7495a25619e2247fb15a2ed9ba" dependencies = [ "cfg-if", "libc", @@ -951,9 +951,9 @@ dependencies = [ [[package]] name = "paste" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b1de2e551fb905ac83f73f7aedf2f0cb4a0da7e35efa24a202a936269f1f18e1" +checksum = "d01a5bd0424d00070b0098dd17ebca6f961a959dead1dbcbbbc1d1cd8d3deeba" [[package]] name = "percent-encoding" @@ -981,18 +981,18 @@ checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "proc-macro2" -version = "1.0.47" +version = "1.0.49" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ea3d908b0e36316caf9e9e2c4625cdde190a7e6f440d794667ed17a1855e725" +checksum = "57a8eca9f9c4ffde41714334dee777596264c7825420f521abc92b5b5deb63a5" dependencies = [ "unicode-ident", ] [[package]] name = "quote" -version = "1.0.21" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" +checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b" dependencies = [ "proc-macro2", ] @@ -1075,9 +1075,9 @@ dependencies = [ [[package]] name = "ryu" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" +checksum = "7b4b9743ed687d4b4bcedf9ff5eaa7398495ae14e61cba0a295704edbc7decde" [[package]] name = "scopeguard" @@ -1087,30 +1087,30 @@ checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" [[package]] name = "scratch" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c8132065adcfd6e02db789d9285a0deb2f3fcb04002865ab67d5fb103533898" +checksum = "ddccb15bcce173023b3fedd9436f882a0739b8dfb45e4f6b6002bee5929f61b2" [[package]] name = "semver" -version = "1.0.14" +version = "1.0.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e25dfac463d778e353db5be2449d1cce89bd6fd23c9f1ea21310ce6e5a1b29c4" +checksum = "58bc9567378fc7690d6b2addae4e60ac2eeea07becb2c64b9f218b53865cba2a" [[package]] name = "serde" -version = "1.0.147" +version = "1.0.152" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d193d69bae983fc11a79df82342761dfbf28a99fc8d203dca4c3c1b590948965" +checksum = "bb7d1f0d3021d347a83e556fc4683dea2ea09d87bccdf88ff5c12545d89d5efb" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.147" +version = "1.0.152" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f1d362ca8fc9c3e3a7484440752472d68a6caa98f1ab81d99b5dfe517cec852" +checksum = "af487d118eecd09402d70a5d72551860e788df87b464af30e5ea6a38c75c541e" dependencies = [ "proc-macro2", "quote", @@ -1119,9 +1119,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.89" +version = "1.0.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "020ff22c755c2ed3f8cf162dbb41a7268d934702f3ed3631656ea597e08fc3db" +checksum = "877c235533714907a8c2464236f5c4b2a17262ef1bd71f38f35ea592c8da6883" dependencies = [ "itoa", "ryu", @@ -1151,6 +1151,17 @@ dependencies = [ "digest", ] +[[package]] +name = "sha2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "signal-hook-registry" version = "1.4.0" @@ -1193,9 +1204,9 @@ checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" [[package]] name = "syn" -version = "1.0.103" +version = "1.0.107" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a864042229133ada95abf3b54fdc62ef5ccabe9515b64717bcb9a1919e59445d" +checksum = "1f4064b5b16e03ae50984a5a8ed5d4f8803e6bc1fd170a3cda91a1be4b18e3f5" dependencies = [ "proc-macro2", "quote", @@ -1213,18 +1224,18 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.37" +version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10deb33631e3c9018b9baf9dcbbc4f737320d2b576bac10f6aefa048fa407e3e" +checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.37" +version = "1.0.38" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "982d17546b47146b28f7c22e3d08465f6b8903d0ea13c1660d9d84a6e7adcdbb" +checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f" dependencies = [ "proc-macro2", "quote", @@ -1233,9 +1244,9 @@ dependencies = [ [[package]] name = "time" -version = "0.1.44" +version = "0.1.45" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255" +checksum = "1b797afad3f312d1c66a56d11d0316f916356d11bd158fbc6ca6389ff6bf805a" dependencies = [ "libc", "wasi 0.10.0+wasi-snapshot-preview1", @@ -1286,9 +1297,9 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c" [[package]] name = "tokio" -version = "1.22.0" +version = "1.23.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d76ce4a75fb488c605c54bf610f221cea8b0dafb53333c1a67e8ee199dcd2ae3" +checksum = "eab6d665857cc6ca78d6e80303a02cea7a7851e85dfbd77cbdc09bd129f1ef46" dependencies = [ "autocfg", "bytes", @@ -1299,7 +1310,7 @@ dependencies = [ "pin-project-lite", "signal-hook-registry", "socket2", - "winapi", + "windows-sys", ] [[package]] @@ -1318,9 +1329,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.5.9" +version = "0.5.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" +checksum = "1333c76748e868a4d9d1017b5ab53171dfd095f70c712fdb4653a406547f598f" dependencies = [ "serde", ] @@ -1348,9 +1359,9 @@ dependencies = [ [[package]] name = "typenum" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987" +checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" [[package]] name = "unicode-bidi" @@ -1360,9 +1371,9 @@ checksum = "099b7128301d285f79ddd55b9a83d5e6b9e97c92e0ea0daebee7263e932de992" [[package]] name = "unicode-ident" -version = "1.0.5" +version = "1.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6ceab39d59e4c9499d4e5a8ee0e2735b891bb7308ac83dfb4e80cad195c9f6f3" +checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc" [[package]] name = "unicode-normalization" @@ -1591,9 +1602,9 @@ dependencies = [ [[package]] name = "zstd-sys" -version = "2.0.3+zstd.1.5.2" +version = "2.0.4+zstd.1.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44ccf97612ac95f3ccb89b2d7346b345e52f1c3019be4984f0455fb4ba991f8a" +checksum = "4fa202f2ef00074143e219d15b62ffc317d17cc33909feac471c044087cad7b0" dependencies = [ "cc", "libc", diff --git a/Cargo.toml b/Cargo.toml index f0cd0eb..101e530 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,8 +11,8 @@ repository = "https://github.com/Stridsvagn69420/Cyrkensia" homepage = "https://github.com/Stridsvagn69420/Cyrkensia" documentation = "https://docs.rs/cyrkensia" authors = ["Stridsvagn69420"] -categories = [] -keywords = [] +categories = ["web-programming::http-server", "web-programming", "multimedia", "multimedia::audio", "filesystem"] +keywords = ["music", "server", "repository"] default-run = "cyrkensia" [dependencies] @@ -27,16 +27,16 @@ kagero = { version = "0.4", default-features = false, features = ["printer"] } actix-web = { version = "4", optional = true } actix-cors = { version = "0.6", optional = true } blake3 = { version = "1.3", optional = true } -chrono = { version = "*", optional = true, features = ["std", "clock"] } +sha2 = { version = "0.10", optional = true } +chrono = { version = "0.4", optional = true, features = ["std", "clock"] } # Accounts only argon2 = { version = "0.4", optional = true, features = ["std", "password-hash"] } -rand = { version = "0.8", optional = true, features = ["std"] } [features] default = ["server", "accounts"] -accounts = ["argon2", "rand"] -server = ["actix-web", "actix-cors", "blake3", "chrono"] +accounts = ["argon2"] +server = ["actix-web", "actix-cors", "blake3", "sha2", "chrono"] [build-dependencies] chrono = "0.4" diff --git a/src/bin/cyrkensia.rs b/src/bin/cyrkensia.rs index 6c03448..311376a 100644 --- a/src/bin/cyrkensia.rs +++ b/src/bin/cyrkensia.rs @@ -75,6 +75,13 @@ async fn server(cfg: Config) -> io::Result<()> { server.run().await } +/// More help +/// +/// Tells you to google the error. +fn morehelp(cmd: &mut Printer) { + cmd.errorln(&("See ".to_owned() + WIKI_HELP_URL + " for more."), Colors::YellowBright); +} + #[actix_web::main] async fn main() { // Init @@ -85,6 +92,8 @@ async fn main() { exit(1); }; + // TODO: Add status message at start with information from the loaded config + // Start if let Err(segv) = server(config).await { console.error(timelog!(), Colors::Red) @@ -98,11 +107,4 @@ async fn main() { console.print(timelog!(), Colors::Cyan) .println("Cyrkensia server successfully stopped!", Colors::CyanBright); exit(0) -} - -/// More help -/// -/// Tells you to google the error. -fn morehelp(cmd: &mut Printer) { - cmd.errorln(&("See ".to_owned() + WIKI_HELP_URL + " for more."), Colors::YellowBright); } \ No newline at end of file diff --git a/src/server/routes.rs b/src/server/routes.rs index 0e08e85..8f4b396 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -1,4 +1,6 @@ +use std::path::PathBuf; use std::time::Instant; +use std::{io, fs}; use actix_web::{web, Responder, HttpResponse}; use actix_web::http::header::ContentType; use serde::Deserialize; @@ -60,10 +62,15 @@ pub async fn hostinfo(data: web::Data) -> impl Responder { finalres } -#[derive(Deserialize)] + + + + + /// Index Route Params /// /// Simple struct containing the param-name and param-type needed for the [index] route. +#[derive(Deserialize)] pub struct IndexParams { pub album: String } @@ -74,18 +81,19 @@ pub struct IndexParams { pub async fn index(p: web::Path, data: web::Data) -> impl Responder { // Extract album name let path = p.into_inner(); + // Read files and album name depending on if cache is enabled or not let meta: (String, usize, Vec) = if data.config.max_age.is_some() { // Cached files and metadata let Ok(hostinfo) = data.hostinfo.lock() else { return responses::server_500(None::); }; - let Some(album) = hostinfo.albums.clone().into_iter().find(|x| x.path == path.album) else { + let Some(album) = hostinfo.albums.iter().find(|x| x.path == path.album) else { return responses::client_404(Some("Album not found")); }; // Return tri-tuple - (album.name, album.files.len(), album.files) + (album.name.clone(), album.files.len(), album.files.clone()) } else { // Attempt to find album in filesystem let Ok(path) = Album::find(&data.config.root, &path.album) else { @@ -119,4 +127,80 @@ pub async fn index(p: web::Path, data: web::Data) - HttpResponse::Ok() .content_type(ContentType::html()) .body(format!("{}{}{}", headmeta, headstr, bodystr)) +} + + + + +/// File Route Params +/// +/// Simple struct for the path parameters used in [file_head] and [file_serving] +#[derive(Deserialize)] +pub struct FileParams { + pub albun: String, + pub file: String +} + +impl FileParams { + /// Find file path + /// + /// Attempts to find the file path in the filesystem. + pub fn find_file(roots: &[String], album: &String, file: String) -> io::Result { + let album_path = Album::find(roots, album)?; + // Read found directory + let filepath = fs::read_dir(album_path)?.into_iter() + .filter_map(|x| { + let Ok(dentry) = x else { + return None; + }; + Some(dentry) + }) + // Convert filename + .filter_map(|y| { + if let Some(fname) = y.file_name().to_str() { + return Some((fname.to_string(), y.path())); + } + None + + }) + // Find file + .find(|z| z.0 == file); + + // Extract path + if let Some(stuff) = filepath { + return Ok(stuff.1); + } + Err(io::Error::new(io::ErrorKind::NotFound, "Could not find file")) + } +} + +/// File Head Route +/// +/// +pub async fn file_serving(p: web::Path, data: web::Data) -> impl Responder { + let path = p.into_inner(); + + // Generate ETag with BLAKE3 hash as Hexadecimal + // Generate Digest header with BLAKE3, SHA-256, SHA-512 as Base64 + // Generate Last-Modified header from fs::metadata + // Match HTTP Status Codes + + HttpResponse::Ok() +} + +/// File Serving Route +/// +/// +pub async fn file_head(p: web::Path, data: web::Data) -> impl Responder { + let pathdata = p.into_inner(); + let Ok(path) = FileParams::find_file(&data.config.root, &pathdata.albun, pathdata.file) else { + return responses::client_404(Some("File not found")); + }; + + // Generate ETag with BLAKE3 hash as Hexadecimal + // Generate Digest header with BLAKE3, SHA-256, SHA-512 as Base64 + // Generate Last-Modified header from fs::metadata + // Include If-Modified-Since behaviour and match HTTP Status Codes + + HttpResponse::Ok().finish() } \ No newline at end of file From 0dcabf025556adc08c3cdb9e0a5ec9c3e55d52c6 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Thu, 29 Dec 2022 15:53:32 +0100 Subject: [PATCH 35/36] CLI tool wip, server message wip, logger wip. file routes DONE --- Cargo.lock | 9 +++- Cargo.toml | 3 +- src/server/mod.rs | 68 +++++++++++++++++++++++++-- src/server/routes.rs | 106 +++++++++++++++++++++++++++++++++++-------- 4 files changed, 163 insertions(+), 23 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 4949822..2e5bff2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -45,7 +45,7 @@ dependencies = [ "actix-service", "actix-utils", "ahash", - "base64", + "base64 0.13.1", "bitflags", "brotli", "bytes", @@ -281,6 +281,12 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e1b586273c5702936fe7b7d6896644d8be71e6314cfe09d3167c95f712589e8" +[[package]] +name = "base64" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ea22880d78093b0cbe17c89f64a7d457941e65759157ec6cb31a31d652b05e5" + [[package]] name = "base64ct" version = "1.5.3" @@ -515,6 +521,7 @@ dependencies = [ "actix-cors", "actix-web", "argon2", + "base64 0.20.0", "blake3", "chrono", "dirs", diff --git a/Cargo.toml b/Cargo.toml index 101e530..5a11ed8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ actix-web = { version = "4", optional = true } actix-cors = { version = "0.6", optional = true } blake3 = { version = "1.3", optional = true } sha2 = { version = "0.10", optional = true } +base64 = { version = "0.20", optional = true } chrono = { version = "0.4", optional = true, features = ["std", "clock"] } # Accounts only @@ -36,7 +37,7 @@ argon2 = { version = "0.4", optional = true, features = ["std", "password-hash"] [features] default = ["server", "accounts"] accounts = ["argon2"] -server = ["actix-web", "actix-cors", "blake3", "sha2", "chrono"] +server = ["actix-web", "actix-cors", "blake3", "sha2", "chrono", "base64"] [build-dependencies] chrono = "0.4" diff --git a/src/server/mod.rs b/src/server/mod.rs index 7c6b029..82dcbe8 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -1,10 +1,17 @@ +use actix_web::http::header::HeaderValue; +use base64::encode; +use blake3::{hash, Hash}; +use chrono::{DateTime, Utc}; +use sha2::{Sha256, Sha512, Digest}; use actix_web::http::Uri; use crate::account::Account; use crate::{Hostinfo, Config, Artist}; +use std::ffi::OsStr; use std::fmt::Write; use std::sync::Mutex; use std::time::Instant; -use std::io; +use std::{io, fs}; +use std::path::Path; /// Middlewares /// @@ -129,7 +136,7 @@ pub use timestamp; /// Timelog /// /// Formats a given message with a timestamp. -/// If no message is provided, it just return [timestamp!], but with a whitespace added. +/// If no message is provided, it just returns [timestamp!], but with a whitespace added. #[macro_export] macro_rules! timelog { () => { @@ -139,4 +146,59 @@ macro_rules! timelog { (timestamp!() + " " + $msg).as_str() }; } -pub use timelog; \ No newline at end of file +pub use timelog; + +/// Hashgen +/// +/// Generates the Blake3, SHA-512 and SHA-256 hashes in Base64. +pub fn hashgen(data: &[u8]) -> (Hash, String, String) { + // Generate hash + let sha256hash = Sha256::digest(data); + let sha512hash = Sha512::digest(data); + let b3hash = hash(data); + + // Return tuple + (b3hash, encode(sha512hash), encode(sha256hash)) +} + +/// Filetime +/// +/// Attempts to read a file's last modified date and returns it as an RFC 2822 string with the offset replaced with GMT. +/// Returns a tuple of the formatted timestamp as a [String] and the time as [DateTime] with [Utc] timezone. +pub fn filetime(p: impl AsRef) -> io::Result<(String, DateTime)> { + let systime = fs::metadata(p)?.modified()?; + let datetime: DateTime = systime.into(); + Ok((datetime.to_rfc2822().replace("+0000", "GMT"), datetime)) +} + +/// Compare time +/// +/// Attempts to parse the If-Modified-Since timestamp and compare it to the given [filetime] [result](DateTime). +/// Returns true if the If-Modified-Since condition is met, otherwise false. +pub fn compare_time(ftime: DateTime, ims_head: &HeaderValue) -> io::Result { + let Ok(x) = ims_head.to_str().map(|x| x.to_string()) else { + return Err(io::Error::new(io::ErrorKind::NotFound, "Could not extract header value")); + }; + let Ok(rtime) = DateTime::parse_from_rfc2822(x.as_str()) else { + return Err(io::Error::new(io::ErrorKind::NotFound, "Could not parse time")); + }; + Ok(ftime > rtime) +} + +/// Get MIME-Type +/// +/// Gets the MIME-Type for a given file extension. +pub fn get_mime(extop: Option<&OsStr>) -> &str { + match extop.and_then(|x| x.to_str()) { + Some("aac") => "audio/aac", + Some("mp3") => "audio/mp3", + Some("opus") => "audio/opus", + Some("wav") => "audio/wav", + Some("3gp") => "audio/3gpp", + Some("3g2") => "audio/3gpp2", + Some("mid") | Some("midi") => "audio/midi", + Some("oga") | Some("ogg") => "audio/ogg", + Some("weba") | Some("webm") => "audio/webm", + _ => "application/octet-stream" + } +} \ No newline at end of file diff --git a/src/server/routes.rs b/src/server/routes.rs index 8f4b396..a46dcc3 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -1,10 +1,13 @@ use std::path::PathBuf; use std::time::Instant; use std::{io, fs}; -use actix_web::{web, Responder, HttpResponse}; -use actix_web::http::header::ContentType; +use base64::encode; +use actix_web::{web, Responder, HttpResponse, HttpRequest}; +use actix_web::http::header::HeaderMap; +use actix_web::http::header; +use chrono::{DateTime, Utc}; use serde::Deserialize; -use super::{CyrkensiaState, responses}; +use super::{CyrkensiaState, responses, hashgen, filetime, compare_time, get_mime}; use crate::{Hostinfo, Artist, Metadata, Album}; /// Hostinfo Route @@ -125,13 +128,15 @@ pub async fn index(p: web::Path, data: web::Data) - // Send response HttpResponse::Ok() - .content_type(ContentType::html()) + .content_type(header::ContentType::html()) .body(format!("{}{}{}", headmeta, headstr, bodystr)) } + + /// File Route Params /// /// Simple struct for the path parameters used in [file_head] and [file_serving] @@ -176,31 +181,96 @@ impl FileParams { /// File Head Route /// +/// Route for serving a file's metadata only +pub async fn file_head(p: web::Path, data: web::Data) -> impl Responder { + common_file(p, data).0 +} + +/// File Serving Route /// -pub async fn file_serving(p: web::Path, data: web::Data) -> impl Responder { - let path = p.into_inner(); +/// Route for serving a file's content +pub async fn file_serving(req: HttpRequest, p: web::Path, data: web::Data) -> impl Responder { + let resp = common_file(p, data); + + let response = match (resp.1, resp.2) { + (Some(data), Some(time)) => { + // If-Modified-Since behaviour + if let Some(headval) = req.headers().get(header::IF_MODIFIED_SINCE) { + if let Ok(new) = compare_time(time, headval) { + if new { + // 200 OK + return data_resp(data, resp.0.headers()); + } else { + // 304 Not Modified + let mut newres = HttpResponse::NotModified(); + copy_headers!(newres, resp.0.headers()); + return newres.finish(); + } + } + } + // Normal file serving + data_resp(data, resp.0.headers()) + }, + // Convert Error Body + _ => resp.0 + }; - // Generate ETag with BLAKE3 hash as Hexadecimal - // Generate Digest header with BLAKE3, SHA-256, SHA-512 as Base64 - // Generate Last-Modified header from fs::metadata - // Match HTTP Status Codes + response +} - HttpResponse::Ok() +/// Copy Headers +/// +/// Copies the &[HeaderMap](HeaderMap) from a finished respose to a new reponse. +#[macro_export] +macro_rules! copy_headers { + ($resp:expr, $heads:expr) => { + for ele in $heads { + $resp.insert_header(ele); + } + }; } +pub use copy_headers; -/// File Serving Route +/// Data Reponse /// +/// Converts a normal response to a data response +fn data_resp(data: Vec, heads: &HeaderMap) -> HttpResponse { + let mut datares = HttpResponse::Ok(); + copy_headers!(datares, heads); + datares.body(data) +} + +/// INTERNAL File Route Wrapper /// -pub async fn file_head(p: web::Path, data: web::Data) -> impl Responder { +/// Internal Wrapper for [file_serving] and [file_head], so that I don't have to repeat myself. +/// If the second item is [Some], then the entire response was successful so far. The tird element is also [Some] then. +fn common_file(p: web::Path, data: web::Data) -> (HttpResponse, Option>, Option>) { + // Get filesystem path let pathdata = p.into_inner(); let Ok(path) = FileParams::find_file(&data.config.root, &pathdata.albun, pathdata.file) else { - return responses::client_404(Some("File not found")); + return (responses::client_404(Some("File not found")), None, None); }; - // Generate ETag with BLAKE3 hash as Hexadecimal - // Generate Digest header with BLAKE3, SHA-256, SHA-512 as Base64 // Generate Last-Modified header from fs::metadata - // Include If-Modified-Since behaviour and match HTTP Status Codes + let Ok(time) = filetime(&path) else { + return (responses::server_500(Some("Failed to read file")), None, None); + }; + + // Read file + let Ok(data) = fs::read(&path) else { + return (responses::server_500(Some("Failed to serve file")), None, None); + }; + + // Create response + let digest = hashgen(&data); + let response = HttpResponse::Ok() + .insert_header((header::CONTENT_LENGTH, data.len())) + .insert_header((header::CONTENT_TYPE, get_mime(path.extension()))) + .insert_header((header::LAST_MODIFIED, time.0)) + .insert_header(("Digest", format!("sha-256={},sha-512={},blake3={}", digest.2, digest.1, encode(digest.0.as_bytes())))) + .insert_header((header::ETAG, format!("\"{}\"", digest.0.to_hex()))) + .finish(); + - HttpResponse::Ok().finish() + (response, Some(data), Some(time.1)) } \ No newline at end of file From 669d0dc2b00930827b889fd300456ee0d813d185 Mon Sep 17 00:00:00 2001 From: Stridsvagn69420 Date: Thu, 29 Dec 2022 17:59:31 +0100 Subject: [PATCH 36/36] Partial content doesn't work. Time to revert. Basic Auth WIP. CLI tool wip, server message wip, logger wip. --- src/bin/cyrkensia.rs | 5 ++++- src/server/mod.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++ src/server/routes.rs | 41 ++++++++++++++++++++++++++----------- 3 files changed, 81 insertions(+), 13 deletions(-) diff --git a/src/bin/cyrkensia.rs b/src/bin/cyrkensia.rs index 311376a..b15dc48 100644 --- a/src/bin/cyrkensia.rs +++ b/src/bin/cyrkensia.rs @@ -4,7 +4,7 @@ use cyrkensia::{Config, timelog, timestamp}; use cyrkensia::meta::WIKI_HELP_URL; use cyrkensia::server::CyrkensiaState; use cyrkensia::server::redirect::trail_slash; -use cyrkensia::server::routes::{index, hostinfo}; +use cyrkensia::server::routes::{index, hostinfo, file_head, file_serving}; use cyrkensia::server::middleware::{cors_everywhere, source_headers, license_headers}; use actix_web::{web, App, HttpServer}; use kagero::printer::{Printer, Colors}; @@ -54,8 +54,11 @@ async fn server(cfg: Config) -> io::Result<()> { .wrap(license_headers()) //Routes .route("/", web::get().to(hostinfo)) + // TODO: Add favicon route .route("/{album}/", web::get().to(index)) .route("/{album}", web::get().to(trail_slash)) + .route("/{album}/{file}", web::get().to(file_serving)) + .route("/{album}/{file}", web::head().to(file_head)) }); // ---- Server Bind ---- diff --git a/src/server/mod.rs b/src/server/mod.rs index 82dcbe8..4e79f2a 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -193,6 +193,7 @@ pub fn get_mime(extop: Option<&OsStr>) -> &str { Some("aac") => "audio/aac", Some("mp3") => "audio/mp3", Some("opus") => "audio/opus", + Some("m4a") => "audio/mp4", Some("wav") => "audio/wav", Some("3gp") => "audio/3gpp", Some("3g2") => "audio/3gpp2", @@ -201,4 +202,51 @@ pub fn get_mime(extop: Option<&OsStr>) -> &str { Some("weba") | Some("webm") => "audio/webm", _ => "application/octet-stream" } +} + +/// Slice Maker +/// +/// Gets the given range of appened bytearray. The first item is the data, the second one the Content-Range header. +pub fn slice_maker(data: Vec, header: Option<&HeaderValue>) -> (Vec, Option) { + let data_len = data.len(); + + // Format range + let Some(rangehead) = header + .and_then(|x|x.to_str().ok()) else { + return (data, None); + }; + let binding = rangehead.replace("bytes=", ""); + let mut range = binding.split('-'); + + // Parse range + if let (Some(x), Some(y)) = (range.nth(0), range.nth(0)) { + return match (x.parse::(), y.parse::()) { + (Ok(a), Ok(b)) => { + // Get full-range slice + if data.get(a).is_some() && data.get(b).is_some() { + return (data[a..b].to_owned(), Some(format!("bytes {a}-{b}/{data_len}"))); + } else { + return (data, None); + } + }, + (Ok(a), Err(_)) => { + // Get start-range slice + if data.get(a).is_some() { + return (data[a..].to_owned(), Some(format!("bytes {a}-{}/{data_len}", data_len - 1))); + } else { + return (data, None); + } + }, + (Err(_), Ok(b)) => { + // Get end-range slice + if data.get(b).is_some() { + return (data[..b].to_owned(), Some(format!("bytes 0-{b}/{data_len}"))); + } else { + return (data, None); + } + }, + (Err(_), Err(_)) => (data, None), + } + } + (data, None) } \ No newline at end of file diff --git a/src/server/routes.rs b/src/server/routes.rs index a46dcc3..d86134d 100644 --- a/src/server/routes.rs +++ b/src/server/routes.rs @@ -1,13 +1,14 @@ use std::path::PathBuf; use std::time::Instant; use std::{io, fs}; +use blake3::hash; use base64::encode; use actix_web::{web, Responder, HttpResponse, HttpRequest}; use actix_web::http::header::HeaderMap; use actix_web::http::header; use chrono::{DateTime, Utc}; use serde::Deserialize; -use super::{CyrkensiaState, responses, hashgen, filetime, compare_time, get_mime}; +use super::{CyrkensiaState, responses, hashgen, filetime, compare_time, get_mime, slice_maker}; use crate::{Hostinfo, Artist, Metadata, Album}; /// Hostinfo Route @@ -142,7 +143,7 @@ pub async fn index(p: web::Path, data: web::Data) - /// Simple struct for the path parameters used in [file_head] and [file_serving] #[derive(Deserialize)] pub struct FileParams { - pub albun: String, + pub album: String, pub file: String } @@ -182,15 +183,15 @@ impl FileParams { /// File Head Route /// /// Route for serving a file's metadata only -pub async fn file_head(p: web::Path, data: web::Data) -> impl Responder { - common_file(p, data).0 +pub async fn file_head(req: HttpRequest, p: web::Path, data: web::Data) -> impl Responder { + common_file(req, p, data).0 } /// File Serving Route /// /// Route for serving a file's content pub async fn file_serving(req: HttpRequest, p: web::Path, data: web::Data) -> impl Responder { - let resp = common_file(p, data); + let resp = common_file(req.clone(), p, data); let response = match (resp.1, resp.2) { (Some(data), Some(time)) => { @@ -244,10 +245,13 @@ fn data_resp(data: Vec, heads: &HeaderMap) -> HttpResponse { /// /// Internal Wrapper for [file_serving] and [file_head], so that I don't have to repeat myself. /// If the second item is [Some], then the entire response was successful so far. The tird element is also [Some] then. -fn common_file(p: web::Path, data: web::Data) -> (HttpResponse, Option>, Option>) { +fn common_file(req: HttpRequest, p: web::Path, data: web::Data) -> (HttpResponse, Option>, Option>) { + + // TODO: CHECK BASIC AUTH + // Get filesystem path let pathdata = p.into_inner(); - let Ok(path) = FileParams::find_file(&data.config.root, &pathdata.albun, pathdata.file) else { + let Ok(path) = FileParams::find_file(&data.config.root, &pathdata.album, pathdata.file) else { return (responses::client_404(Some("File not found")), None, None); }; @@ -261,16 +265,29 @@ fn common_file(p: web::Path, data: web::Data) -> (Ht return (responses::server_500(Some("Failed to serve file")), None, None); }; + // Partial Content + let etag_header = format!("\"{}\"", hash(&data)); + let slice = slice_maker(data, req.headers().get(header::RANGE)); + let digest = hashgen(&slice.0); + // Create response - let digest = hashgen(&data); - let response = HttpResponse::Ok() - .insert_header((header::CONTENT_LENGTH, data.len())) + let mut wipresp = match slice.1 { + Some(_) => HttpResponse::PartialContent(), + None => HttpResponse::Ok(), + }; + if let Some(rangehead) = slice.1 { + wipresp.insert_header((header::CONTENT_RANGE, rangehead)); + } + let response = wipresp + .insert_header((header::ACCEPT_RANGES, "bytes")) + .insert_header((header::CONTENT_LENGTH, slice.0.len())) .insert_header((header::CONTENT_TYPE, get_mime(path.extension()))) .insert_header((header::LAST_MODIFIED, time.0)) .insert_header(("Digest", format!("sha-256={},sha-512={},blake3={}", digest.2, digest.1, encode(digest.0.as_bytes())))) - .insert_header((header::ETAG, format!("\"{}\"", digest.0.to_hex()))) + .insert_header((header::ETAG, etag_header)) .finish(); - (response, Some(data), Some(time.1)) + // TODO: Return slice used for data + (response, Some(slice.0), Some(time.1)) } \ No newline at end of file