commit 965f9d6ad494dceaa34c2fd802df94591edada7e Author: SoXX Date: Mon May 25 22:27:18 2026 +0200 inital commit diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..75e957c --- /dev/null +++ b/README.md @@ -0,0 +1,142 @@ +# go-fa-api + +Go 1.25+ SDK for [FurAffinity](https://www.furaffinity.net). FA has no JSON +API, so this library scrapes the beta theme via [Colly](https://github.com/gocolly/colly) +internally and exposes a strongly typed surface. + +## Features + +| Area | What you get | +|------|--------------| +| **Read** | `GetSubmission` · `GetUser` · `GetJournal` · `Download` | +| **Iterators** (`iter.Seq2`) | `Gallery` · `Scraps` · `Favorites` · `UserJournals` · `SubmissionComments` · `JournalComments` | +| **Discovery** | `Browse(BrowseOptions)` · `Search(query, SearchOptions)` full filter struct (rating/type/order/range/etc.) | +| **Inbox** | `SubmissionInbox` (watched-users feed) · `Notes` · `GetNote` · `Notifications` (journals/watches/comments/favs/shouts) | +| **Write** | `Fav`/`Unfav` · `Watch`/`Unwatch` · `PostSubmissionComment` · `PostJournalComment` · `SendNote` | +| **Auth** | `WithCookies(a, b)` · `WithCloudflare(cf_clearance)` · `WithUserAgent` · `WithSFW(SFWOn/Off/Auto)` | +| **Networking** | Built-in 1 req/s rate limiter · Cloudflare challenge detection · 429 `Retry-After` · 5xx exponential backoff · `context.Context` end-to-end | +| **Experimental** | `WithExperimentalJSONListings(true)` listing pages merge from FA's embedded `js-submissionData` JSON first, HTML fallback if it's absent. More resilient to markup drift; off by default. | + +Pre-1.0: expect breaking changes. Beta theme only; classic theme is not parsed. + +## Install + +```bash +go get git.anthrove.art/public/go-fa-api +``` + +## Quickstart + +```go +package main + +import ( + "context" + "fmt" + "log" + "os" + + fa "git.anthrove.art/public/go-fa-api" +) + +func main() { + client := fa.New( + fa.WithCookies(fa.Cookies{A: os.Getenv("FA_A"), B: os.Getenv("FA_B")}), + fa.WithCloudflare(fa.CFCookies{Clearance: os.Getenv("CF_CLEARANCE")}), + fa.WithUserAgent(os.Getenv("FA_UA")), + ) + + sub, err := client.GetSubmission(context.Background(), 12345678) + if err != nil { + log.Fatal(err) + } + fmt.Printf("%s by %s\n", sub.Title, sub.Author.DisplayName) + + for sub, err := range client.Gallery(context.Background(), "someuser", fa.ListOptions{MaxPages: 3}) { + if err != nil { + log.Fatal(err) + } + fmt.Println(sub.ID, sub.Title) + } +} +``` + +Runnable examples in `examples/`: `basic`, `gallery_dump`, `download`, `browse`, `search`, `inbox`, `notes`, `notifications`. + +## Auth + +FA's auth is cookie-based; Cloudflare gates submissions behind a clearance +cookie bound to your browser's User-Agent. The SDK doesn't log in for you copy the values once: + +1. Log in at https://www.furaffinity.net in your browser. +2. DevTools → **Application** → **Cookies** → copy `a`, `b`, and `cf_clearance`. +3. DevTools → **Network** → any FA request → copy the **User-Agent** header + *exactly*. CF binds `cf_clearance` to that UA; mismatch = challenge. +4. Pass them in via `fa.WithCookies` / `fa.WithCloudflare` / `fa.WithUserAgent`. + +If FA challenges you later, your `cf_clearance` expired refresh it and the +SDK will return `fa.ErrCloudflareChallenge` so you can detect it. + +> Account preference must be set to the **beta** theme (Site Preferences → Style → Beta). + +## Rate limiting + +Every request (page fetches *and* downloads) passes through one token bucket. +Default is **1 req/s**, lowest safe for FA. Lives inside the +`http.RoundTripper` so callers can't bypass it. + +```go +fa.New(fa.WithRateLimit(2*time.Second, 1)) // explicit +fa.New(fa.WithRequestsPerSecond(0.5)) // shorthand +``` + +## Iterators + +Paginated endpoints return `iter.Seq2[*T, error]`: + +```go +for sub, err := range client.Gallery(ctx, "someuser", fa.ListOptions{}) { + if err != nil { return err } + fmt.Println(sub.ID, sub.Title) +} +``` + +- **Lazy** pages fetched on demand; `break` stops further fetches. +- **Terminal errors** first error yields `(nil, err)` and stops the iterator. +- **One option-shape per iterator class**: simple paginated iterators + (Gallery / Scraps / Favorites / UserJournals / SubmissionInbox / Notes) + take `fa.ListOptions{StartPage, MaxPages}`; filtered iterators + (`Search`, `Browse`) take their own `SearchOptions` / `BrowseOptions` + struct that folds the same pagination fields in. + +## Errors + +Test with `errors.Is`: + +| Sentinel | When | What to do | +|----------|------|-----------| +| `ErrNotFound` | FA "not found" / deleted submission | surface to user | +| `ErrUnauthorized` | endpoint needs login or `Login Required` page | refresh `a`/`b` | +| `ErrCloudflareChallenge` | CF interposed a challenge | refresh `cf_clearance` | +| `ErrRateLimited` | 429 after retry budget exhausted | slow down | +| `ErrSystemMessage` | uncategorised FA system message | inspect `*SystemMessageError` | +| `ErrParse` | HTML didn't match selectors | likely FA shifted markup open an issue | + +## Test fixtures + +Parsers are selector-driven; FA's HTML drifts. `TestRefreshFixtures` (build +tag `fixtures`) hits live FA with your cookies and snapshots each curated +page into `testdata/html/`. Parser `*_RealFixture` tests `t.Skip` cleanly +when their file is absent, so the basic suite works without any cookies. + +```bash +# Configure once (or edit scripts/test.sh): +export FA_A=... FA_B=... CF_CLEARANCE=... FA_UA='Mozilla/5.0 ...' +export FA_TEST_USER=yourlogin FA_TEST_SUB_ID=... FA_TEST_JOURNAL_ID=... +# Optional refinements: FA_TEST_SUB_STORY_ID, FA_TEST_USER_WITH_SHOUTS, +# FA_TEST_GALLERY_USER, FA_TEST_GALLERY_LAST_PAGE, FA_TEST_NOTE_ID, +# FA_TEST_SEARCH_QUERY each gates a separate fixture; unset = skip. + +go test -tags=fixtures -run TestRefreshFixtures -v ./... # or ./scripts/test.sh +go test ./... # now *_RealFixture tests activate +``` \ No newline at end of file diff --git a/SDK_ISSUES.md b/SDK_ISSUES.md new file mode 100644 index 0000000..79c6bdd --- /dev/null +++ b/SDK_ISSUES.md @@ -0,0 +1,268 @@ +# SDK issues FA Droid + +Bugs whose root cause is in the **FA SDK** (`go-fa-api`, at +`/var/home/soxx/git/go-fa-api`, `replace`d in `go.mod`) not in this app. + +The SDK is a **separate module, maintained and fixed by a separate AI** +that does not see this app's code or conversation context. This file is the +handoff: every entry is a self-contained bug report meant to be copy-pasted +to that AI as-is. + +App-side bugs (frontend / go-service) live in `ISSUES.md`; fixed issues in +`SOLVED.md`. Features with UI but no backend are in `STUBS.md`; Wails/Android +stack traps in `PITFALLS.md`. + +**Status legend:** `[ ]` open · `[~]` diagnosed handoff brief drafted · +`[x]` fixed in the SDK (then moved to `SOLVED.md`) +**Numbering:** issue numbers are shared across `ISSUES.md`, `SOLVED.md` and +this file draw the next free number from the same sequence. + +--- + +## SDK handoff brief required fields + +Every entry MUST carry a handoff brief detailed enough to be copy-pasted to +the SDK AI as a standalone bug report. Do not write "sdk issue?" and stop — +that is not actionable for someone without this repo open. + +A handoff brief must answer all seven of: + +1. **SDK entry point** the exact exported function involved + (e.g. `Client.Fav(ctx, SubmissionID)` in `actions.go`). Name the file. +2. **How the app calls it** which `internal/services/*.go` wrapper + invokes it, and with what arguments. +3. **Observed behaviour** what the SDK call returns: an error (quote it + verbatim), a wrong value, or a silent no-op. +4. **Expected behaviour** what FurAffinity should do server-side and + what the SDK should return. +5. **Reproduction** concrete inputs (submission ID, username) and the + steps that trigger it. +6. **Suspected layer** HTML parsing (FA changed its markup?), request + shape (wrong form fields / missing CSRF / wrong URL), auth/cookies, or + rate-limiting. Point at the likely file: parsers are `*_parser.go`, + form posts are in `actions.go` / `*_post.go` / `*_send.go`. +7. **What is NOT the SDK** explicitly rule out the app layer so the SDK + AI does not chase a frontend bug. State what you verified. + +If you cannot yet fill all seven fields, the issue stays `[~]` and the brief +lists exactly which diagnostics are still needed never hand over a +half-brief as if it were complete. + +--- + +## Issues + +### #4 [~] Audit the FA SDK for bugs +- **Where:** `go-fa-api` (sibling module, `replace`d in `go.mod`). +- **Task:** Standing umbrella review the SDK surface used by + `internal/services/` for incorrect parsing, missing endpoints, or wrong + request shapes. +- **Cause tag:** `sdk` +- **Progress:** The first audit pass produced #1, #5, #9, #10 and #14 **all + now fixed and verified** (#1/#5/#9/#10 in app v0.0.7, #14 in v0.0.10; see + `SOLVED.md`). #15 was then fixed too (SDK gave `WithResolvedAvatars` a + count limit; app v0.0.14). #17 (priority rate limiting) was implemented too + — verified in app v0.0.16. **No open SDK issues currently.** Keep this + entry as the umbrella for future audit passes; file each concrete finding + as its own numbered issue. + +_No open SDK issues. Fixed ones are recorded in `SOLVED.md`._ + +--- + +## Add new SDK issues below + + + +### #18 [x] Rate limiter: upgrade from 2-level to N-level priority + +**Implemented in the SDK update** `options.go` now exposes `WithPriority` +and a multi-level `Priority` type; `WithPrioritizedRateLimiting` honours it. +FA Droid follow-up (assign tiers to reads/writes/preload/crawl) is tracked as +app-side work, not an SDK issue. + + +- **Component:** `go-fa-api` `ratelimit.go`, `options.go`. +- **Today:** the limiter has exactly two priorities. `WithBackgroundPriority(ctx)` + marks a request background; everything else is foreground. Background + requests wait until no foreground request is queued. Enabled via + `WithPrioritizedRateLimiting(true)`. +- **Need:** a consumer (FA Droid) wants *three+* tiers, not two: + 1. user-interactive (the page on screen, user write actions), + 2. speculative neighbor preload (likely-next submissions), + 3. bulk background crawl (inbox/watchlist warming). + With only two levels, neighbor preload must either compete with the live + page (tier 1) or interleave with the bulk crawl (tier 2) neither is right. +- **Proposed API:** keep `WithBackgroundPriority` working (maps to the lowest + level) and add `WithPriority(ctx, Priority)` where `Priority` is an ordered + enum, e.g. `PriorityInteractive`, `PriorityNormal` (default), + `PriorityLow`, `PriorityBackground`. The limiter serves waiting goroutines + highest-priority-first; the token emission rate is unchanged. +- **Compatibility:** default (no marker) must remain `PriorityNormal`; + `WithBackgroundPriority` must remain equivalent to `PriorityBackground`. +- **Why it matters to the app:** FA Droid will then assign tier 1 to + current-page reads + the write-action queue worker, tier `PriorityLow` to + neighbor preload, and `PriorityBackground` to the inbox crawler. + +### #21 [x] GetSubmission doesn't expose the viewer's favorite state + +- **Where:** `go-fa-api` `submission.go` (`Submission` struct + `parseSubmission`). +- **Symptom:** A submission the logged-in user has favorited shows the + favorite heart as *empty* on the app's submission detail page. There is no + way to know a submission's favorite state from a `GetSubmission` result. +- **Expected:** `GetSubmission` should report whether the authenticated viewer + has favorited the submission, so the UI can render the correct heart state. +- **Cause tag:** `sdk` +- **SDK handoff brief:** + 1. **Entry point:** `Client.GetSubmission(ctx, SubmissionID)` in + `submission.go`, which builds the result via `parseSubmission(id, doc)`. + The returned `Submission` struct (`submission.go:17-38`) has fields + ID, Title, Author, PostedAt, Rating, Category, Type, Species, Gender, + Description, DescriptionText, Tags, FileURL, ThumbURL, Width, Height, + Stats, Folders, Prev, Next and **nothing indicating favorite state**. + 2. **How the app calls it:** `SubmissionService.getCached` in + `internal/services/submission.go` calls `GetSubmission`, then + `dto.FromSubmission` (`internal/dto/types.go`) copies the struct to the + wire DTO. The frontend (`SubmissionView.svelte`) does + `favorited = !!sub.favorited`. + 3. **Observed behaviour:** `GetSubmission` returns a `*Submission` with no + favorite-state field. It is not a wrong value or an error the datum is + simply absent from the SDK's public type. + 4. **Expected behaviour:** When `/view/{id}/` is fetched with valid `a`/`b` + cookies, FA renders either a `+Fav` (`/fav/{id}/...`) or a `−Fav` + (`/unfav/{id}/...`) anchor exactly one, matching the viewer's current + state. The SDK should surface this on `Submission`, e.g. a new + `Favorited bool` field (final name your call), set true when the page + shows the `/unfav/` link. On an anonymous (no-cookie) fetch neither link + is present → `Favorited` false, which is correct. + 5. **Reproduction:** With cookies set, favorite submission X on FA, then + call `GetSubmission(ctx, X)` the result cannot express that X is + favorited. + 6. **Suspected layer:** HTML parsing `parseSubmission`. The SDK *already* + has the exact parser: `findFavLinks(doc, subID) (favURL, unfavURL string)` + in `actions.go` (used by `toggleFavorite` for its idempotency check). + `unfavURL != ""` means "currently favorited." `parseSubmission` just needs + to run that check and set the new field. No new scraping logic required. + 7. **What is NOT the SDK:** The app side is verified ready and correct. + `SubmissionView.svelte` already reads `sub.favorited` and types it + (`favorited?: boolean`); `getCached` correctly busts and re-fetches the + submission cache after a fav write (via `WriteService` / the action + queue). The value never reaches the app only because the SDK `Submission` + struct has no field to carry it `dto.FromSubmission` has nothing to map. +- **Related (please also check):** the same gap likely exists for *watch* + state `findWatchLinks` exists in `actions.go`, but the `User` struct may + not expose whether the viewer watches that user. Worth fixing in the same + pass. +- **When it lands (FA Droid follow-up):** add `Favorited bool` to + `dto.Submission` (`json:"favorited"`), map it in `dto.FromSubmission`, and + regenerate bindings. The frontend already consumes `sub.favorited`, so no UI + change is needed. +- **Status:** done SDK update added `Submission.Favorited`; app wired it in + v0.0.22. + +### #23 [ ] SubmissionInbox yields only the first page (~72 items) + +- **Where:** `go-fa-api` `inbox.go` (`SubmissionInbox` + `parseSubmissionInboxPage`). +- **Symptom:** The new-submission inbox shows only ~72 items even when the + account has thousands pending. A user with ~4718 inbox submissions sees one + page. +- **Expected:** `SubmissionInbox` should walk every cursor page until FA stops + rendering a "Next 72" link. +- **Cause tag:** `sdk` +- **SDK handoff brief:** + 1. **Entry point:** `Client.SubmissionInbox(ctx, ListOptions)` in `inbox.go`, + whose iterator follows `parseSubmissionInboxPage`'s returned `nextURL`. + 2. **How the app calls it:** `InboxService.StreamSubmissions` + (`internal/services/inbox.go`) runs one goroutine that does + `for sub, err := range client.SubmissionInbox(ctx, fa.ListOptions{})` + — `ListOptions{}` means `MaxPages: 0` (unbounded), so the app does not + cap the crawl. + 3. **Observed behaviour:** the `range` completes after ~72 items the + iterator yields one page then ends. Verified on-device: the app's crawl + channel (fed one item per `yield`) closes after exactly one ~72-item + chunk, so `StreamSubmissions` reports `HasMore: false` immediately after + page 1. + 4. **Expected behaviour:** FA's `/msg/submissions/` paginates via a + "Next 72" link encoding a from-id cursor; the iterator should follow it + across all ~66 pages for a 4718-item inbox. + 5. **Reproduction:** logged-in client with a large submission inbox; + `count := 0; for range client.SubmissionInbox(ctx, ListOptions{}) { count++ }` + yields ~72, not the true total. + 6. **Suspected layer:** HTML parsing `parseSubmissionInboxPage`. Its next- + cursor selector is `div.messagecenter-navigation a.button.more`; if FA + changed that markup the parser returns `nextURL == ""` and the iterator + stops after page 1. Check the selector against current `/msg/submissions/` + HTML (and the cursor-URL construction). + 7. **What is NOT the SDK:** app side verified. `StreamSubmissions` ranges the + iterator fully on a single goroutine and streams everything it yields; it + passes `ListOptions{}` (no `MaxPages` cap). On-device logging shows the + crawl ends after one chunk the iterator simply stops yielding. + +### #24 [x] Request logger drops `context.Context` (breaks trace propagation) + +**Fixed in the SDK** `transport.go`'s `logRequest` now emits its record via +`logger.InfoContext(req.Context(), "fa.request", …)` instead of `logger.Info`, +so a context-aware `slog.Handler` recovers the caller's active span and the +HTTP span nests under the RPC span. A regression test, +`TestTransport_LogRequest_PropagatesRequestContext` in `transport_test.go`, +installs a context-capturing handler and asserts a sentinel value threaded +through `req.Context()` reaches the slog record guarding against a silent +revert to `Info`. + + +- **Where:** `go-fa-api` the HTTP transport's request logging (`transport.go`, + the `logRequest` helper / wherever `slog` records an outgoing request). +- **Type:** Enhancement, not a bug the SDK works correctly; this is a + one-line change the app needs for distributed tracing. +- **Symptom:** The app (FA Droid, WI-10) added OpenTelemetry spans. An app RPC + opens an `rpc` span and threads its `context.Context` into the SDK call. The + SDK's per-request `slog` line is currently emitted with `logger.Info(...)`, + which carries **no context** so the app's `slog` handler cannot recover the + active span, and each HTTP span becomes an unparented root instead of a child + of the RPC span. +- **Expected:** the request log record should carry the request's context so a + context-aware `slog.Handler` can read the active span from it. +- **The fix (one line):** change the request-logging call from + `logger.Info("fa.request", …)` to + `logger.InfoContext(req.Context(), "fa.request", …)` (use the `*http.Request`'s + own `Context()`). `slog` already supports `InfoContext`; no API change, no new + dependency. +- **Cause tag:** `sdk` +- **SDK handoff brief:** + 1. **SDK entry point:** the HTTP transport `RoundTrip` / request path in + `transport.go` specifically the `slog` call that logs each outgoing FA + request (`logRequest`, or inline). All SDK client methods route through it. + 2. **How the app calls it:** every `internal/services/*.go` wrapper calls a + `Client.*` method with a `context.Context` that now carries an OTel span; + that ctx reaches the `*http.Request` (`req.Context()`). + 3. **Observed behaviour:** the request `slog` record is created without a + context, so `Handler.Handle` receives `context.Background()`. + 4. **Expected behaviour:** the record carries `req.Context()`, so a + context-aware handler can extract the active span. + 5. **Reproduction:** with WI-10's `diag` slog handler installed, every HTTP + span has `parentSpanId == ""` even when the call was made inside an RPC + span. After the `InfoContext` change, the HTTP span nests under the RPC + span on the same trace id. + 6. **Suspected layer:** request shape / logging purely the logging call, + no parsing or auth involved. + 7. **What is NOT the SDK behaviour-wise:** no functional SDK behaviour + changes request execution, parsing, retries, rate-limiting are all + untouched. This only changes which `slog` method is used so context flows. +- **Note:** WI-10 applied this change to the *local* `replace`d working copy of + `go-fa-api` so FA Droid v0.0.33 has working rpc→http span linkage. It is + **not committed in the SDK repo**. Until it is upstreamed, a clean SDK + checkout will degrade gracefully HTTP spans become valid but unparented + roots (no crash, no data loss, only the rpc↔http link is lost). diff --git a/actions.go b/actions.go new file mode 100644 index 0000000..7639d17 --- /dev/null +++ b/actions.go @@ -0,0 +1,216 @@ +package fa + +import ( + "context" + "fmt" + "io" + "net/http" + "net/url" + "strings" + + "github.com/PuerkitoBio/goquery" + + "git.anthrove.art/public/go-fa-api/internal/urls" +) + +// Fav adds a submission to the logged-in user's favorites. Idempotent: if +// the submission is already favorited, the call is a no-op. +// +// Implementation note: FA gates this with a one-shot CSRF key that lives +// on the "+Fav" anchor on the submission page. We fetch the submission to +// scrape the key, then follow the link. The whole exchange happens +// through the rate-limited transport. +func (c *Client) Fav(ctx context.Context, id SubmissionID) error { + return c.toggleFavorite(ctx, id, true) +} + +// Unfav removes a submission from the logged-in user's favorites. +// Idempotent: if not favorited, no-op. +func (c *Client) Unfav(ctx context.Context, id SubmissionID) error { + return c.toggleFavorite(ctx, id, false) +} + +// toggleFavorite implements both Fav and Unfav: scrape the per-state link +// off the submission page and follow it. wantFav=true means "fav if not +// already faved"; wantFav=false means "unfav if currently faved". +func (c *Client) toggleFavorite(ctx context.Context, id SubmissionID, wantFav bool) error { + if id <= 0 { + return fmt.Errorf("fa: toggleFavorite: id must be > 0") + } + var actionURL string + var alreadyInDesiredState bool + err := c.fetch(ctx, urls.Submission(int64(id)), func(doc *goquery.Document) error { + fav, unfav := findFavLinks(doc, int64(id)) + switch { + case wantFav && fav != "": + actionURL = fav + case wantFav && fav == "" && unfav != "": + alreadyInDesiredState = true + case !wantFav && unfav != "": + actionURL = unfav + case !wantFav && unfav == "" && fav != "": + alreadyInDesiredState = true + default: + return fmt.Errorf("%w: submission %d: no fav/unfav link on page (not logged in?)", ErrUnauthorized, id) + } + return nil + }) + if err != nil { + return err + } + if alreadyInDesiredState { + return nil + } + return c.followAction(ctx, actionURL) +} + +// Watch starts watching a user. Idempotent: if already watching, no-op. +// The key + endpoint live on a button on the user's profile (or any page +// that user is the "owner" of, like a journal). We scrape the profile. +func (c *Client) Watch(ctx context.Context, name string) error { + return c.toggleWatch(ctx, name, true) +} + +// Unwatch stops watching a user. Idempotent. +func (c *Client) Unwatch(ctx context.Context, name string) error { + return c.toggleWatch(ctx, name, false) +} + +// toggleWatch fetches the user page, picks watch or unwatch link by state. +func (c *Client) toggleWatch(ctx context.Context, name string, wantWatch bool) error { + name = strings.TrimSpace(name) + if name == "" { + return fmt.Errorf("fa: toggleWatch: empty name") + } + var actionURL string + var alreadyInDesiredState bool + err := c.fetch(ctx, urls.User(name), func(doc *goquery.Document) error { + watch, unwatch := findWatchLinks(doc, name) + switch { + case wantWatch && watch != "": + actionURL = watch + case wantWatch && watch == "" && unwatch != "": + alreadyInDesiredState = true + case !wantWatch && unwatch != "": + actionURL = unwatch + case !wantWatch && unwatch == "" && watch != "": + alreadyInDesiredState = true + default: + return fmt.Errorf("%w: user %q: no watch/unwatch link on page", ErrUnauthorized, name) + } + return nil + }) + if err != nil { + return err + } + if alreadyInDesiredState { + return nil + } + return c.followAction(ctx, actionURL) +} + +// findFavLinks scans a submission view page for the "+Fav" and "−Fav" +// anchors that FA renders side by side (only one is real at a time — +// whichever matches your current favorite state). Returns absolute URLs; +// either may be "" if the page is anonymous-mode or doesn't show controls. +func findFavLinks(doc *goquery.Document, subID int64) (favURL, unfavURL string) { + subStr := fmt.Sprintf("/fav/%d/", subID) + unfavStr := fmt.Sprintf("/unfav/%d/", subID) + doc.Find("a[href*='/fav/'], a[href*='/unfav/']").Each(func(_ int, a *goquery.Selection) { + href, _ := a.Attr("href") + switch { + case strings.HasPrefix(href, subStr): + favURL = urls.AbsoluteCDN(href) + case strings.HasPrefix(href, unfavStr): + unfavURL = urls.AbsoluteCDN(href) + } + }) + return favURL, unfavURL +} + +// findWatchLinks scans a user page for the Watch / Unwatch button. +// FA renders id="watch-button" on the active anchor with href +// "/watch/{name}/?key=..." or "/unwatch/{name}/?key=...". +func findWatchLinks(doc *goquery.Document, name string) (watchURL, unwatchURL string) { + wPrefix := "/watch/" + strings.ToLower(name) + "/" + uwPrefix := "/unwatch/" + strings.ToLower(name) + "/" + doc.Find("a[href*='/watch/'], a[href*='/unwatch/']").Each(func(_ int, a *goquery.Selection) { + href, _ := a.Attr("href") + switch { + case strings.HasPrefix(href, wPrefix): + watchURL = urls.AbsoluteCDN(href) + case strings.HasPrefix(href, uwPrefix): + unwatchURL = urls.AbsoluteCDN(href) + } + }) + return watchURL, unwatchURL +} + +// followAction performs a one-shot GET to a fav/watch/etc. action URL and +// classifies the response. FA typically redirects to the originating page +// on success (handled transparently by the stdlib client), so a 2xx final +// status means the action took effect. +// +// 4xx is surfaced as ErrUnauthorized / ErrNotFound / ErrSystemMessage via +// the transport+classifier; 5xx becomes HTTPError. We don't parse the +// response body FA's success states are too varied to verify reliably +// from HTML alone. +func (c *Client) followAction(ctx context.Context, actionURL string) error { + if actionURL == "" { + return fmt.Errorf("fa: followAction: empty URL") + } + req, err := http.NewRequestWithContext(ctx, http.MethodGet, actionURL, nil) + if err != nil { + return err + } + // Rate limit + retries are handled by the transport on c.http. + resp, err := c.http.Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + + // Drain and classify. If the response is FA's System Error template we + // surface that; otherwise a 2xx response is taken as success. + body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20)) + if resp.StatusCode == http.StatusOK || resp.StatusCode == http.StatusFound { + // Parse out a possible system-message wrapper. + if doc, derr := goquery.NewDocumentFromReader(strings.NewReader(string(body))); derr == nil { + if smErr := classifySystemMessage(doc); smErr != nil { + return smErr + } + } + return nil + } + return &HTTPError{StatusCode: resp.StatusCode, URL: actionURL} +} + +// postForm is the shared form-POST helper used by PostComment, SendNote, +// and any other M3 write action. It honours the rate limiter, sets the +// proper Content-Type, and surfaces system-message errors from the +// response body. +// +// Returns the response body for callers that need to parse a confirmation +// (e.g., to extract a newly-posted comment's ID). +func (c *Client) postForm(ctx context.Context, rawURL string, form url.Values) ([]byte, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodPost, rawURL, strings.NewReader(form.Encode())) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := c.http.Do(req) + if err != nil { + return nil, err + } + defer resp.Body.Close() + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) + if resp.StatusCode >= 400 { + return body, &HTTPError{StatusCode: resp.StatusCode, URL: rawURL} + } + if doc, derr := goquery.NewDocumentFromReader(strings.NewReader(string(body))); derr == nil { + if smErr := classifySystemMessage(doc); smErr != nil { + return body, smErr + } + } + return body, nil +} diff --git a/actions_test.go b/actions_test.go new file mode 100644 index 0000000..a5ac590 --- /dev/null +++ b/actions_test.go @@ -0,0 +1,401 @@ +package fa + +import ( + "bytes" + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "net/url" + "strconv" + "strings" + "sync/atomic" + "testing" + + "github.com/PuerkitoBio/goquery" +) + +// fakeSubmissionPage builds a minimal /view/{id}/ response that has either +// a Fav or Unfav anchor (controlled by faved). Sufficient to satisfy the +// classifySystemMessage check (title is non-System-Error) and the +// findFavLinks selector. +func fakeSubmissionPage(id int, faved bool) string { + prefix := "/fav/" + label := "+Fav" + if faved { + prefix = "/unfav/" + label = "-Fav" + } + href := prefix + strconv.Itoa(id) + "/?key=k1" + return `Test submission +
+ +
+

T

+
x
+
+
+` + label + ` +` +} + +func fakeUserPage(name string, watching bool) string { + href := "/watch/" + name + "/?key=k2" + text := "Watch" + if watching { + href = "/unwatch/" + name + "/?key=k2" + text = "Unwatch" + } + return `Userpage +

` + name + `

+` + text + ` +` +} + +func TestFav_FetchesAndFollowsFavLink(t *testing.T) { + var hits atomic.Int32 + mux := http.NewServeMux() + mux.HandleFunc("/view/123/", func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + _, _ = w.Write([]byte(fakeSubmissionPage(123, false))) + }) + mux.HandleFunc("/fav/123/", func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + if r.URL.Query().Get("key") != "k1" { + t.Errorf("missing key on /fav/: %q", r.URL.RawQuery) + } + w.WriteHeader(http.StatusOK) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + client := newE2EClient(t, srv) + if err := client.Fav(context.Background(), 123); err != nil { + t.Fatalf("Fav: %v", err) + } + if hits.Load() != 2 { + t.Errorf("hits = %d; want 2 (fetch + follow)", hits.Load()) + } +} + +func TestFav_AlreadyFavedIsNoOp(t *testing.T) { + var follows atomic.Int32 + mux := http.NewServeMux() + mux.HandleFunc("/view/77/", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(fakeSubmissionPage(77, true))) + }) + mux.HandleFunc("/fav/77/", func(w http.ResponseWriter, r *http.Request) { + follows.Add(1) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + client := newE2EClient(t, srv) + if err := client.Fav(context.Background(), 77); err != nil { + t.Fatalf("Fav: %v", err) + } + if follows.Load() != 0 { + t.Errorf("/fav/ was hit %d times; want 0 (already faved)", follows.Load()) + } +} + +func TestUnfav_FollowsUnfavLink(t *testing.T) { + var hits atomic.Int32 + mux := http.NewServeMux() + mux.HandleFunc("/view/55/", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(fakeSubmissionPage(55, true))) + }) + mux.HandleFunc("/unfav/55/", func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + if r.URL.Query().Get("key") != "k1" { + t.Errorf("missing key on /unfav/") + } + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + client := newE2EClient(t, srv) + if err := client.Unfav(context.Background(), 55); err != nil { + t.Fatalf("Unfav: %v", err) + } + if hits.Load() != 1 { + t.Errorf("/unfav/ hits = %d; want 1", hits.Load()) + } +} + +func TestWatch_FollowsWatchLink(t *testing.T) { + var hits atomic.Int32 + mux := http.NewServeMux() + mux.HandleFunc("/user/alice/", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(fakeUserPage("alice", false))) + }) + mux.HandleFunc("/watch/alice/", func(w http.ResponseWriter, r *http.Request) { + hits.Add(1) + if r.URL.Query().Get("key") != "k2" { + t.Errorf("missing key on /watch/") + } + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + client := newE2EClient(t, srv) + if err := client.Watch(context.Background(), "alice"); err != nil { + t.Fatalf("Watch: %v", err) + } + if hits.Load() != 1 { + t.Errorf("/watch/ hits = %d", hits.Load()) + } +} + +func TestUnwatch_AlreadyNotWatching_NoOp(t *testing.T) { + var follows atomic.Int32 + mux := http.NewServeMux() + mux.HandleFunc("/user/bob/", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(fakeUserPage("bob", false))) + }) + mux.HandleFunc("/unwatch/bob/", func(w http.ResponseWriter, r *http.Request) { + follows.Add(1) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + client := newE2EClient(t, srv) + if err := client.Unwatch(context.Background(), "bob"); err != nil { + t.Fatalf("Unwatch: %v", err) + } + if follows.Load() != 0 { + t.Errorf("/unwatch/ was hit; want no-op when not watching") + } +} + +func TestPostSubmissionComment_POSTsCorrectForm(t *testing.T) { + var got url.Values + mux := http.NewServeMux() + mux.HandleFunc("/view/200/", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + http.Error(w, "want POST", http.StatusBadRequest) + return + } + body, _ := io.ReadAll(r.Body) + got, _ = url.ParseQuery(string(body)) + _, _ = w.Write([]byte("
posted
")) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + client := newE2EClient(t, srv) + err := client.PostSubmissionComment(context.Background(), 200, "Nice work!", PostCommentOptions{}) + if err != nil { + t.Fatalf("PostSubmissionComment: %v", err) + } + if got.Get("action") != "reply" { + t.Errorf("action = %q", got.Get("action")) + } + if got.Get("reply") != "Nice work!" { + t.Errorf("reply = %q", got.Get("reply")) + } + if got.Get("replyto") != "" { + t.Errorf("replyto should be empty for top-level; got %q", got.Get("replyto")) + } +} + +func TestPostSubmissionComment_ReplytoSetForThreadedReply(t *testing.T) { + var got url.Values + mux := http.NewServeMux() + mux.HandleFunc("/view/200/", func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + got, _ = url.ParseQuery(string(body)) + _, _ = w.Write([]byte("ok")) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + client := newE2EClient(t, srv) + err := client.PostSubmissionComment(context.Background(), 200, "reply text", PostCommentOptions{ParentID: 999}) + if err != nil { + t.Fatalf("PostSubmissionComment: %v", err) + } + if got.Get("replyto") != "999" { + t.Errorf("replyto = %q; want 999", got.Get("replyto")) + } +} + +func TestPostJournalComment_TargetsJournalURL(t *testing.T) { + var hit string + mux := http.NewServeMux() + mux.HandleFunc("/journal/400/", func(w http.ResponseWriter, r *http.Request) { + hit = r.URL.Path + _, _ = w.Write([]byte("ok")) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + client := newE2EClient(t, srv) + err := client.PostJournalComment(context.Background(), 400, "hi", PostCommentOptions{}) + if err != nil { + t.Fatalf("PostJournalComment: %v", err) + } + if hit != "/journal/400/" { + t.Errorf("hit = %q", hit) + } +} + +func TestSendNote_ScrapesKeyAndPosts(t *testing.T) { + inboxHTML := `Inbox +
+` + var sendBody url.Values + mux := http.NewServeMux() + mux.HandleFunc("/msg/pms/", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(inboxHTML)) + }) + mux.HandleFunc("/msg/send/", func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Errorf("want POST, got %s", r.Method) + } + body, _ := io.ReadAll(r.Body) + sendBody, _ = url.ParseQuery(string(body)) + _, _ = w.Write([]byte("sent")) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + client := newE2EClient(t, srv) + err := client.SendNote(context.Background(), "vampexx", "Re: hi", "body text") + if err != nil { + t.Fatalf("SendNote: %v", err) + } + if sendBody.Get("key") != "SCRAPED_KEY" { + t.Errorf("key = %q; want SCRAPED_KEY", sendBody.Get("key")) + } + if sendBody.Get("to") != "vampexx" { + t.Errorf("to = %q", sendBody.Get("to")) + } + if sendBody.Get("subject") != "Re: hi" { + t.Errorf("subject = %q", sendBody.Get("subject")) + } + if sendBody.Get("message") != "body text" { + t.Errorf("message = %q", sendBody.Get("message")) + } +} + +func TestSendNote_NoKeyOnInboxPage_Unauthorized(t *testing.T) { + mux := http.NewServeMux() + mux.HandleFunc("/msg/pms/", func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`Inboxno form here`)) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + client := newE2EClient(t, srv) + err := client.SendNote(context.Background(), "x", "s", "b") + if !errors.Is(err, ErrUnauthorized) { + t.Fatalf("got %v; want ErrUnauthorized", err) + } +} + +func TestBuildBrowseURL_NoFiltersUsesSimpleForm(t *testing.T) { + u := buildBrowseURL(1, BrowseOptions{}) + if u != "https://www.furaffinity.net/browse/" { + t.Errorf("page=1 default = %q", u) + } + u = buildBrowseURL(2, BrowseOptions{}) + if u != "https://www.furaffinity.net/browse/?page=2" { + t.Errorf("page=2 default = %q", u) + } +} + +func TestBuildBrowseURL_RatingsAndCategoryFilters(t *testing.T) { + got := buildBrowseURL(1, BrowseOptions{ + Ratings: []Rating{RatingGeneral, RatingMature}, + Category: 2, + PerPage: 48, + }) + q := mustQuery(t, got) + if q.Get("rating_general") != "1" || q.Get("rating_mature") != "1" { + t.Errorf("ratings not encoded: %v", q) + } + if q.Get("rating_adult") != "" { + t.Errorf("rating_adult should not be set when not requested") + } + if q.Get("cat") != "2" { + t.Errorf("cat = %q", q.Get("cat")) + } + if q.Get("perpage") != "48" { + t.Errorf("perpage = %q", q.Get("perpage")) + } +} + +func TestE2E_Browse_RatingsFilterFlowsThroughIterator(t *testing.T) { + var seenRatings []string + mux := http.NewServeMux() + mux.HandleFunc("/browse/", func(w http.ResponseWriter, r *http.Request) { + seenRatings = []string{ + r.URL.Query().Get("rating_general"), + r.URL.Query().Get("rating_mature"), + r.URL.Query().Get("rating_adult"), + } + w.Header().Set("Content-Type", "text/html") + _, _ = w.Write([]byte(``)) + }) + srv := httptest.NewServer(mux) + defer srv.Close() + + client := newE2EClient(t, srv) + for _, err := range client.Browse(context.Background(), BrowseOptions{ + Ratings: []Rating{RatingGeneral}, + }) { + if err != nil { + t.Fatalf("iter: %v", err) + } + } + if seenRatings[0] != "1" || seenRatings[1] != "" || seenRatings[2] != "" { + t.Errorf("seenRatings = %v; want [1, '', '']", seenRatings) + } +} + +// TestFindFavLinks_RealFixture confirms findFavLinks scrapes the +Fav anchor +// out of a real captured /view/ page. Guards against FA changing the fav-link +// markup (issue #5: favourite action doing nothing). +func TestFindFavLinks_RealFixture(t *testing.T) { + raw := loadFixture(t, "submission.html") + doc, err := goquery.NewDocumentFromReader(bytes.NewReader(raw)) + if err != nil { + t.Fatalf("read doc: %v", err) + } + // submission.html was captured for submission 65052636 (a "+Fav" page). + favURL, unfavURL := findFavLinks(doc, 65052636) + if favURL == "" { + t.Error("findFavLinks: favURL empty +Fav anchor not found in real markup") + } + if !strings.Contains(favURL, "/fav/65052636/") || !strings.Contains(favURL, "key=") { + t.Errorf("findFavLinks: favURL = %q; want a /fav/65052636/?key=... URL", favURL) + } + if unfavURL != "" { + t.Errorf("findFavLinks: unfavURL = %q; want empty on a not-yet-faved page", unfavURL) + } +} + +// TestFindWatchLinks_RealFixture confirms findWatchLinks scrapes the +// watch-button anchor out of a real captured userpage-style page. Guards +// against FA changing the watch-button markup (issue #10). +func TestFindWatchLinks_RealFixture(t *testing.T) { + raw := loadFixture(t, "gallery_page1.html") + doc, err := goquery.NewDocumentFromReader(bytes.NewReader(raw)) + if err != nil { + t.Fatalf("read doc: %v", err) + } + // gallery_page1.html was captured for kazucreations, whom the capturing + // account watches so the header shows an Unwatch button. + watchURL, unwatchURL := findWatchLinks(doc, "kazucreations") + if unwatchURL == "" { + t.Error("findWatchLinks: unwatchURL empty watch-button anchor not found in real markup") + } + if unwatchURL != "" && (!strings.Contains(unwatchURL, "/unwatch/kazucreations/") || !strings.Contains(unwatchURL, "key=")) { + t.Errorf("findWatchLinks: unwatchURL = %q; want a /unwatch/kazucreations/?key=... URL", unwatchURL) + } + if watchURL != "" { + t.Errorf("findWatchLinks: watchURL = %q; want empty when already watching", watchURL) + } +} diff --git a/browse.go b/browse.go new file mode 100644 index 0000000..e639071 --- /dev/null +++ b/browse.go @@ -0,0 +1,148 @@ +package fa + +import ( + "context" + "iter" + "net/url" + "strconv" + + "github.com/PuerkitoBio/goquery" + + "git.anthrove.art/public/go-fa-api/internal/urls" +) + +// browsePerPage is FA's default page size for /browse/. We use it as the +// "this page is full → there's likely another one" threshold because the +// browse feed paginates via POST forms in the UI; detectNextPage's anchor- +// based heuristic doesn't fire on browse responses. +const browsePerPage = 72 + +// BrowseOptions configures /browse/ filters. Zero-value defaults match +// FA's web UI default: all ratings on, all categories, all art types, +// any species, 72 per page. +// +// The filter fields use FA's internal numeric IDs (1 = "All" / "Any" for +// category, atype, species). The exact list of valid values is huge and +// changes over time; for now we expose them as raw ints rather than +// pretending to enumerate them callers wanting a typed Category enum +// should grab the value off the browse form's