Compare commits

..

14 Commits

Author SHA1 Message Date
322bb41a97 refactor: basic implementation of favorites
Signed-off-by: soxx <soxx@fenpa.ws>
2023-11-27 22:37:36 +01:00
be44a669d9 refactor: start rework of the high level API
Signed-off-by: soxx <soxx@fenpa.ws>
2023-11-27 08:12:58 +01:00
585c94b97a refactor: remove unneeded date formatting
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 15:25:49 +01:00
a916da8f15 docs: removed unused links
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 15:12:24 +01:00
fb00542c71 feat: added LICENSE
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 15:10:36 +01:00
cdf042d79d docs: reworked README
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 15:07:35 +01:00
8c662f78fd docs: added more & unified documentation format
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 14:41:16 +01:00
9cee99ecb5 docs: added more & unified documentation format
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 14:37:44 +01:00
c6be78419c refactor: added docs & limit types
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 14:18:51 +01:00
208b9a3baa refactor: added more accurate types
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 14:05:21 +01:00
95e1db6ce6 refactor: removed unused files
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 14:02:47 +01:00
9669eb8ddf refactor: removed code duplication
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 14:02:15 +01:00
8e76fa709d feat: added partial implementation for low, mid and high level api for db exports
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-15 13:21:13 +01:00
6124a3fc61 feat: added low level API for Database exports
Signed-off-by: SoXX <soxx@fenpa.ws>
2023-11-13 11:45:39 +01:00
89 changed files with 21739 additions and 20651 deletions

2
.gitignore vendored
View File

@ -190,5 +190,3 @@ $RECYCLE.BIN/
# End of https://www.toptal.com/developers/gitignore/api/windows,linux,goland+all,macos,go
/.scannerwork/
*.env

674
LICENSE.md Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

274
README.md
View File

@ -1,67 +1,207 @@
# Go-e621 SDK
An unofficial e621 SDK (Client) library to interact with **e621**, **e923** and **e6ai**. Maintained by the Anthrove Development Team.
- Caching?
- Auto pagination
- sync
- async
- connected/inelegant calls
- more docs
# Completeness
_Legend_
| Symbol | Meaning |
|:------------------:|:----------------------|
| :x: | Not implemented |
| :heavy_minus_sign: | Partially implemented |
| :heavy_check_mark: | Fully implemented |
_High Level API_
| Area | Complete | Comment |
|:-----------------|:------------------:|:--------|
| Authentication | :x: | |
| Posts | :heavy_minus_sign: | |
| Tags | :heavy_minus_sign: | |
| Tag aliases | :x: | |
| Tag implications | :x: | |
| Notes | :x: | |
| Pools | :x: | |
| Users | :heavy_check_mark: | |
| Favorites | :heavy_minus_sign: | |
| DB export | :x: | |
_Mid Level API_
| Area | Get | Set |
|:-----------------|:------------------:|:----|
| Authentication | :x: | |
| Posts | :heavy_check_mark: | |
| Tags | :heavy_check_mark: | |
| Tag aliases | :x: | |
| Tag implications | :x: | |
| Notes | :heavy_check_mark: | |
| Pools | :heavy_check_mark: | |
| Users | :heavy_check_mark: | |
| Favorites | :heavy_check_mark: | |
| DB export | :x: |
| DMails | :heavy_minus_sign: | |
_Low Level API_
| Area | Get | Set |
|:-----------------|:------------------:|:----|
| Authentication | :x: | |
| Posts | :heavy_check_mark: | |
| Tags | :heavy_check_mark: | |
| Tag aliases | :x: | |
| Tag implications | :x: | |
| Notes | :heavy_check_mark: | |
| Pools | :heavy_check_mark: | |
| Users | :heavy_check_mark: | |
| Favorites | :heavy_check_mark: | |
| DB export | :x: | |
| DMails | :heavy_check_mark: | |
# Go-e621 SDK
An unofficial e621 SDK (Client) library to interact with **e621**, **e923** and **e6ai**.
Maintained by the Anthrove Development Team.
## Table of Contents
- [Installation](#installation)
- [Usage](#usage)
- [Examples](#examples)
- [Feature Completeness](#feature-completeness)
## Installation
Include instructions on how to install or get your Golang client API. This might include:
```bash
go get -u git.dragse.it/anthrove/e621-sdk-go
```
## Usage
```golang
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621"
"log"
)
func main() {
ApiUser := ""
ApiKey := ""
e621User := ""
client := e621.NewClient(ApiUser, ApiKey)
user, err := client.GetUserByName(e621User).Execute()
if err != nil {
log.Panic(err)
}
log.Printf("User ID of user %s: %d ", user.Name, user.ID)
}
```
## Examples
This SDK Supports three levels of usage, Low Level, Mid Level & High Level.
All of those are available to you, you find some examples in the example directory.
High Level:
````go
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621"
"log"
)
func main() {
ApiUser := ""
ApiKey := ""
e621User := ""
client := e621.NewClient(ApiUser, ApiKey)
user, err := client.GetUserByName(e621User).Execute()
if err != nil {
log.Panic(err)
}
log.Printf("User ID of user %s: %d ", user.Name, user.ID)
}
````
Mid Level:
````go
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"log"
"net/http"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "API_USER", // Replace with your username
APIKey: "API_KEY", // Replace with your API key
}
// Specify the username for retrieval.
username := "" // Replace with the desired username.
// Call the GetUser function to retrieve the specified user.
userBuilder := builder.NewGetUserBuilder(requestContext)
user, err := userBuilder.SetUsername(username).Execute()
if err != nil {
panic(err)
}
log.Printf("User ID of user %s: %d ", user.Name, user.ID)
}
````
Low Level:
````go
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"log"
"net/http"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "API_USER", // Replace with your username
APIKey: "API_KEY", // Replace with your API key
}
// Specify the username for retrieval.
username := "" // Replace with the desired username.
// Call the GetUser function to retrieve the specified user.
user, err := endpoints.GetUser(requestContext, username)
if err != nil {
panic(err)
}
log.Printf("User ID of user %s: %d ", user.Name, user.ID)
}
````
## Feature Completeness
_Legend_
| Symbol | Meaning |
|:------------------:|:----------------------|
| :x: | Not implemented |
| :heavy_minus_sign: | Partially implemented |
| :heavy_check_mark: | Fully implemented |
_High Level API_
| Area | Complete | Comment |
|:-----------------|:------------------:|:--------|
| Authentication | :heavy_check_mark: | |
| Posts | :heavy_minus_sign: | |
| Tags | :heavy_minus_sign: | |
| Tag aliases | :x: | |
| Tag implications | :x: | |
| Notes | :x: | |
| Pools | :x: | |
| Users | :heavy_check_mark: | |
| Favorites | :heavy_minus_sign: | |
| DB export | :x: | |
_Mid Level API_
| Area | Get | Set |
|:-----------------|:------------------:|:----|
| Authentication | :heavy_check_mark: | |
| Posts | :heavy_check_mark: | |
| Tags | :heavy_check_mark: | |
| Tag aliases | :x: | |
| Tag implications | :x: | |
| Notes | :heavy_check_mark: | |
| Pools | :heavy_check_mark: | |
| Users | :heavy_check_mark: | |
| Favorites | :heavy_check_mark: | |
| DB export | :heavy_check_mark: |
_Low Level API_
| Area | Get | Set |
|:-----------------|:------------------:|:----|
| Authentication | :heavy_check_mark: | |
| Posts | :heavy_check_mark: | |
| Tags | :heavy_check_mark: | |
| Tag aliases | :x: | |
| Tag implications | :x: | |
| Notes | :heavy_check_mark: | |
| Pools | :heavy_check_mark: | |
| Users | :heavy_check_mark: | |
| Favorites | :heavy_check_mark: | |
| DB export | :heavy_check_mark: | |

65
README.md.OLD Normal file
View File

@ -0,0 +1,65 @@
# Go-e621 SDK
An unofficial e621 SDK (Client) library to interact with **e621**, **e923** and **e6ai**. Maintained by the Anthrove Development Team.
- Caching?
- Auto pagination
- sync
- async
- connected/inelegant calls
- more docs
# Completeness
_Legend_
| Symbol | Meaning |
|:------------------:|:----------------------|
| :x: | Not implemented |
| :heavy_minus_sign: | Partially implemented |
| :heavy_check_mark: | Fully implemented |
_High Level API_
| Area | Complete | Comment |
|:-----------------|:------------------:|:--------|
| Authentication | :x: | |
| Posts | :heavy_minus_sign: | |
| Tags | :heavy_minus_sign: | |
| Tag aliases | :x: | |
| Tag implications | :x: | |
| Notes | :x: | |
| Pools | :x: | |
| Users | :heavy_check_mark: | |
| Favorites | :heavy_minus_sign: | |
| DB export | :x: | |
_Mid Level API_
| Area | Get | Set |
|:-----------------|:------------------:|:----|
| Authentication | :x: | |
| Posts | :heavy_check_mark: | |
| Tags | :heavy_check_mark: | |
| Tag aliases | :x: | |
| Tag implications | :x: | |
| Notes | :heavy_check_mark: | |
| Pools | :heavy_check_mark: | |
| Users | :heavy_check_mark: | |
| Favorites | :heavy_check_mark: | |
| DB export | :x: |
_Low Level API_
| Area | Get | Set |
|:-----------------|:------------------:|:----|
| Authentication | :x: | |
| Posts | :heavy_check_mark: | |
| Tags | :heavy_check_mark: | |
| Tag aliases | :x: | |
| Tag implications | :x: | |
| Notes | :heavy_check_mark: | |
| Pools | :heavy_check_mark: | |
| Users | :heavy_check_mark: | |
| Favorites | :heavy_check_mark: | |
| DB export | :x: | |

View File

@ -0,0 +1,46 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621"
_ "github.com/joho/godotenv/autoload"
"log"
"os"
)
func main() {
client := e621.NewClient(os.Getenv("API_USER"), os.Getenv("API_KEY"))
{
fileName, _, err := client.GetLatestPoolsDBExportDataAsBytes()
if err != nil {
panic(err)
}
log.Println(fileName)
}
{
latestDBPoolExport, err := client.GetLatestPoolsDBExportDataAsStruct()
if err != nil {
panic(err)
}
log.Println(latestDBPoolExport[0])
}
{
fileName, _, err := client.GetLatestPostsDBExportDataAsBytes()
if err != nil {
panic(err)
}
log.Println(fileName)
}
{
latestDBPoolExport, err := client.GetLatestPostsDBExportDataAsStruct()
if err != nil {
panic(err)
}
log.Println(latestDBPoolExport[0])
}
}

View File

@ -1,53 +1,60 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621"
_ "github.com/joho/godotenv/autoload"
"log"
"os"
)
func main() {
client := e621.NewClient(os.Getenv("API_USER"), os.Getenv("API_KEY"))
{
favorites, err := client.GetFavoritesForUser("selloo")
if err != nil {
log.Panic(err)
}
posts, err := favorites.Execute()
if err != nil {
log.Panic(err)
}
log.Printf("URL of favorite post 0 is: %s", posts[0].File.URL)
}
{
favoritesBuilder, _ := client.GetFavoritesForUser("selloo")
favorites, err := client.GetNFavoritesForUser(10, favoritesBuilder)
if err != nil {
log.Panic(err)
}
log.Println(len(favorites))
}
{
favoritesBuilder, _ := client.GetFavoritesForUser("selloo")
favorites, err := client.GetAllFavoritesForUser(favoritesBuilder)
if err != nil {
log.Panic(err)
}
log.Println(len(favorites))
}
{
favoritesWithTags := client.GetFavoritesForUserWithTags("selloo", "fennec male solo")
posts, err := favoritesWithTags.Execute()
if err != nil {
log.Panic(err)
}
log.Printf("URL of favorite post 0 with tags is: %s", posts[0].File.URL)
}
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"os"
)
func main() {
client := e621.NewClient(os.Getenv("API_USER"), os.Getenv("API_KEY"))
{
username := "selloo"
favoritesBuilder := client.NewFavoritesBuilder().FromUsername(username)
posts, err := favoritesBuilder.Execute()
if err != nil {
log.Panic(err)
}
log.Printf("URL of favorite post 0 for user with name %s is: %s", username, posts[0].File.URL)
}
{
userID := 123456
favoritesBuilder := client.NewFavoritesBuilder().FromUserID(model.UserID(userID))
posts, err := favoritesBuilder.Execute()
if err != nil {
log.Panic(err)
}
log.Printf("URL of favorite post 0 for user with id %d is: %s", userID, posts[0].File.URL)
}
{
username := "selloo"
tags := []string{"fennec", "male", "solo"}
favoritesBuilder := client.NewFavoritesBuilder().FromUsername(username).WithTags(tags)
posts, err := favoritesBuilder.Execute()
if err != nil {
log.Panic(err)
}
log.Printf("Found %d favorites in %s users favorites", len(posts), username)
}
{
userID := 123456
tags := []string{"fennec", "male", "solo"}
limit := 5
favoritesBuilder := client.NewFavoritesBuilder().FromUserID(model.UserID(userID)).WithTags(tags).Limit(limit)
posts, err := favoritesBuilder.Execute()
if err != nil {
log.Panic(err)
}
log.Printf("returning %d posts with tags %s for user with id %d", len(posts), tags, userID)
}
}

View File

@ -1,45 +1,45 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621"
_ "github.com/joho/godotenv/autoload"
"log"
"os"
)
func main() {
client := e621.NewClient(os.Getenv("API_USER"), os.Getenv("API_KEY"))
posts, err := client.GetPosts().Execute()
if err != nil {
log.Panic(err)
}
log.Printf("Post 0 has following tags: %s", posts[0].Tags)
postWithTags, err := client.GetPosts().Tags("fennec male solo order:score").Execute()
if err != nil {
log.Panic(err)
}
log.Printf("Post 0 with tags has following ID: %d", postWithTags[0].ID)
post, err := client.GetPostByID(1337).Execute()
if err != nil {
log.Panic(err)
}
log.Printf("Post 1337 has following tags: %s", post.Tags)
postBuilder := client.GetPosts()
posts1, err := client.GetNPosts(600, postBuilder)
if err != nil {
log.Panic(err)
}
log.Println(len(posts1))
postBuilder = client.GetPosts().Tags("how_to_dragon_your_train")
posts, err = client.GetAllPosts(postBuilder)
if err != nil {
log.Panic(err)
}
log.Println(len(posts))
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621"
_ "github.com/joho/godotenv/autoload"
"log"
"os"
)
func main() {
client := e621.NewClient(os.Getenv("API_USER"), os.Getenv("API_KEY"))
posts, err := client.GetPosts().Execute()
if err != nil {
log.Panic(err)
}
log.Printf("Post 0 has following tags: %s", posts[0].Tags)
postWithTags, err := client.GetPosts().Tags("fennec male solo order:score").Execute()
if err != nil {
log.Panic(err)
}
log.Printf("Post 0 with tags has following ID: %d", postWithTags[0].ID)
post, err := client.GetPostByID(1337).Execute()
if err != nil {
log.Panic(err)
}
log.Printf("Post 1337 has following tags: %s", post.Tags)
postBuilder := client.GetPosts()
posts1, err := client.GetNPosts(600, postBuilder)
if err != nil {
log.Panic(err)
}
log.Println(len(posts1))
postBuilder = client.GetPosts().Tags("how_to_dragon_your_train")
posts, err = client.GetAllPosts(postBuilder)
if err != nil {
log.Panic(err)
}
log.Println(len(posts))
}

View File

@ -1,23 +1,23 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621"
_ "github.com/joho/godotenv/autoload"
"log"
"os"
)
func main() {
client := e621.NewClient(os.Getenv("API_USER"), os.Getenv("API_KEY"))
user, err := client.GetUserByName("selloo").Execute()
if err != nil {
log.Panic(err)
}
log.Printf("User ID of user %s: %d ", user.Name, user.ID)
user, err = client.GetUserByID(1337).Execute()
if err != nil {
log.Panic(err)
}
log.Printf("User Name of user with ID %d: %s ", user.ID, user.Name)
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621"
_ "github.com/joho/godotenv/autoload"
"log"
"os"
)
func main() {
client := e621.NewClient(os.Getenv("API_USER"), os.Getenv("API_KEY"))
user, err := client.GetUserByName("selloo").Execute()
if err != nil {
log.Panic(err)
}
log.Printf("User ID of user %s: %d ", user.Name, user.ID)
user, err = client.GetUserByID(1337).Execute()
if err != nil {
log.Panic(err)
}
log.Printf("User Name of user with ID %d: %s ", user.ID, user.Name)
}

View File

@ -0,0 +1,50 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
log.Println("Getting a list of DB Exports: ")
dbExportFiles, err := endpoints.GetDBExportList(requestContext)
if err != nil {
panic(err)
}
log.Printf("%d files found", len(dbExportFiles))
for _, v := range dbExportFiles {
log.Printf("File found: %s", v)
}
exportFileName := dbExportFiles[0]
log.Println("Downloading DB export")
log.Printf("File to download: %s", exportFileName)
rawFile, err := endpoints.GetDBExportFile(requestContext, exportFileName)
file, err := os.Create(exportFileName)
if err != nil {
panic(err)
}
defer file.Close()
err = os.WriteFile(exportFileName, rawFile, 0644)
if err != nil {
panic(err)
}
log.Printf("File %s downloaded", exportFileName)
}

View File

@ -1,65 +0,0 @@
package main
import (
"log"
"net/http"
"os"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
)
func main() {
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"),
APIKey: os.Getenv("API_KEY"),
}
log.Println("Getting a DMail by ID:")
dmail, err := endpoints.GetDmail(requestContext, 1)
if err != nil {
log.Println(err)
} else {
log.Println(dmail.Body)
}
log.Println("----------")
log.Println("Deleting a DMail by ID:")
err = endpoints.DeleteDmail(requestContext, 1)
if err != nil {
log.Println(err)
}
log.Println("----------")
log.Println("Marking a DMail as read by ID:")
err = endpoints.MarkAsReadDmail(requestContext, 1)
if err != nil {
log.Println(err)
}
log.Println("----------")
log.Println("Getting all DMails:")
query := map[string]string{
"limit": "5",
}
dmails, err := endpoints.GetAllDmails(requestContext, query)
if err != nil {
log.Println(err)
} else {
for _, dmail := range dmails {
log.Println(dmail.Body)
}
}
log.Println("----------")
log.Println("Marking all DMails as read:")
err = endpoints.MarkAsReadAllDmails(requestContext)
if err != nil {
log.Println(err)
}
log.Println("----------")
}

View File

@ -1,60 +1,60 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting favorites from the API.
log.Println("Getting favorites API user: ")
// Define query parameters for retrieving favorites.
query := map[string]string{
"limit": "5",
}
// Call the GetFavorites function to retrieve favorite posts.
posts, err := endpoints.GetFavorites(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the URL of the first favorite post.
log.Println(posts[0].File.URL)
}
log.Println("----------")
// Log: Getting favorites for a specific user.
log.Println("Getting favorites for user: ")
// Update the query parameters to include a specific user's ID.
query = map[string]string{
"user_id": "25483", // Replace with the desired user's ID
"limit": "5",
}
// Call the GetFavorites function to retrieve favorite posts for the specified user.
posts, err = endpoints.GetFavorites(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the URL of the first favorite post.
log.Println(posts[0].File.URL)
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting favorites from the API.
log.Println("Getting favorites API user: ")
// Define query parameters for retrieving favorites.
query := map[string]string{
"limit": "5",
}
// Call the GetFavorites function to retrieve favorite posts.
posts, err := endpoints.GetFavorites(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the URL of the first favorite post.
log.Println(posts[0].File.URL)
}
log.Println("----------")
// Log: Getting favorites for a specific user.
log.Println("Getting favorites for user: ")
// Update the query parameters to include a specific user's ID.
query = map[string]string{
"user_id": "25483", // Replace with the desired user's ID
"limit": "5",
}
// Call the GetFavorites function to retrieve favorite posts for the specified user.
posts, err = endpoints.GetFavorites(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the URL of the first favorite post.
log.Println(posts[0].File.URL)
}
log.Println("----------")
}

View File

@ -1,57 +1,57 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single note.
log.Println("Getting single note: ")
// Specify the note ID for retrieval.
noteID := "36957" // Replace with the desired note's ID.
// Call the GetNote function to retrieve the specified note.
note, err := endpoints.GetNote(requestContext, noteID)
if err != nil {
log.Println(err)
} else {
// Log the body of the retrieved note.
log.Println(note.Body)
}
log.Println("----------")
// Log: Getting a list of notes.
log.Println("Getting a list of notes: ")
// Define query parameters for retrieving a list of notes.
query := map[string]string{
"limit": "5",
}
// Call the GetNotes function to retrieve a list of notes based on the query parameters.
notes, err := endpoints.GetNotes(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the number of notes retrieved.
log.Println(len(notes))
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single note.
log.Println("Getting single note: ")
// Specify the note ID for retrieval.
noteID := "36957" // Replace with the desired note's ID.
// Call the GetNote function to retrieve the specified note.
note, err := endpoints.GetNote(requestContext, noteID)
if err != nil {
log.Println(err)
} else {
// Log the body of the retrieved note.
log.Println(note.Body)
}
log.Println("----------")
// Log: Getting a list of notes.
log.Println("Getting a list of notes: ")
// Define query parameters for retrieving a list of notes.
query := map[string]string{
"limit": "5",
}
// Call the GetNotes function to retrieve a list of notes based on the query parameters.
notes, err := endpoints.GetNotes(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the number of notes retrieved.
log.Println(len(notes))
}
log.Println("----------")
}

View File

@ -1,57 +1,57 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single pool.
log.Println("Getting single pool: ")
// Specify the pool ID for retrieval.
poolID := "36957" // Replace with the desired pool's ID.
// Call the GetPool function to retrieve the specified pool.
pool, err := endpoints.GetPool(requestContext, poolID)
if err != nil {
log.Println(err)
} else {
// Log the name of the retrieved pool.
log.Println(pool.Name)
}
log.Println("----------")
// Log: Getting a list of pools.
log.Println("Getting a list of pools: ")
// Define query parameters for retrieving a list of pools.
query := map[string]string{
"limit": "5",
}
// Call the GetPools function to retrieve a list of pools based on the query parameters.
pools, err := endpoints.GetPools(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the number of pools retrieved.
log.Println(len(pools))
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single pool.
log.Println("Getting single pool: ")
// Specify the pool ID for retrieval.
poolID := "36957" // Replace with the desired pool's ID.
// Call the GetPool function to retrieve the specified pool.
pool, err := endpoints.GetPool(requestContext, poolID)
if err != nil {
log.Println(err)
} else {
// Log the name of the retrieved pool.
log.Println(pool.Name)
}
log.Println("----------")
// Log: Getting a list of pools.
log.Println("Getting a list of pools: ")
// Define query parameters for retrieving a list of pools.
query := map[string]string{
"limit": "5",
}
// Call the GetPools function to retrieve a list of pools based on the query parameters.
pools, err := endpoints.GetPools(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the number of pools retrieved.
log.Println(len(pools))
}
log.Println("----------")
}

View File

@ -1,57 +1,57 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single post.
log.Println("Getting single post: ")
// Specify the post ID for retrieval.
postID := "4353480" // Replace with the desired post's ID.
// Call the GetPost function to retrieve the specified post.
post, err := endpoints.GetPost(requestContext, postID)
if err != nil {
log.Println(err)
} else {
// Log the URL of the retrieved post.
log.Println(post.File.URL)
}
log.Println("----------")
// Log: Getting a list of posts.
log.Println("Getting a list of posts: ")
// Define query parameters for retrieving a list of posts.
query := map[string]string{
"limit": "5",
}
// Call the GetPosts function to retrieve a list of posts based on the query parameters.
posts, err := endpoints.GetPosts(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the number of posts retrieved.
log.Println(len(posts))
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single post.
log.Println("Getting single post: ")
// Specify the post ID for retrieval.
postID := "4353480" // Replace with the desired post's ID.
// Call the GetPost function to retrieve the specified post.
post, err := endpoints.GetPost(requestContext, postID)
if err != nil {
log.Println(err)
} else {
// Log the URL of the retrieved post.
log.Println(post.File.URL)
}
log.Println("----------")
// Log: Getting a list of posts.
log.Println("Getting a list of posts: ")
// Define query parameters for retrieving a list of posts.
query := map[string]string{
"limit": "5",
}
// Call the GetPosts function to retrieve a list of posts based on the query parameters.
posts, err := endpoints.GetPosts(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the number of posts retrieved.
log.Println(len(posts))
}
log.Println("----------")
}

View File

@ -1,97 +1,97 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single tag.
log.Println("Getting a single tag: ")
// Specify the tag ID for retrieval.
tagID := "1530" // Replace with the desired tag's ID.
// Call the GetTag function to retrieve the specified tag.
tag, err := endpoints.GetTag(requestContext, tagID)
if err != nil {
log.Println(err)
} else {
// Log the name of the retrieved tag.
log.Println(tag.Name)
}
log.Println("----------")
// Log: Getting a list of tags.
log.Println("Getting a list of tags: ")
// Define query parameters for retrieving a list of tags.
query := map[string]string{
"limit": "5",
}
// Call the GetTags function to retrieve a list of tags based on the query parameters.
tagList, err := endpoints.GetTags(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the number of tags retrieved.
log.Println(len(tagList))
}
log.Println("----------")
// Log: Searching for tags containing "cat."
log.Println("Searching for tags containing 'cat': ")
// Define query parameters for searching tags that match "cat."
query = map[string]string{
"limit": "5",
"search[name_matches]": "cat*",
}
// Call the GetTags function with the search query to retrieve matching tags.
tagList, err = endpoints.GetTags(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the retrieved tags.
log.Println(tagList)
}
log.Println("----------")
// Log: Searching for tags with the category "artist."
log.Println("Searching for tags with the category 'artist': ")
// Define query parameters for searching tags in the "artist" category.
query = map[string]string{
"limit": "5",
"search[category]": "1",
}
// Call the GetTags function with the category filter to retrieve artist tags.
tagList, err = endpoints.GetTags(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the retrieved artist tags.
log.Println(tagList)
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single tag.
log.Println("Getting a single tag: ")
// Specify the tag ID for retrieval.
tagID := "1530" // Replace with the desired tag's ID.
// Call the GetTag function to retrieve the specified tag.
tag, err := endpoints.GetTag(requestContext, tagID)
if err != nil {
log.Println(err)
} else {
// Log the name of the retrieved tag.
log.Println(tag.Name)
}
log.Println("----------")
// Log: Getting a list of tags.
log.Println("Getting a list of tags: ")
// Define query parameters for retrieving a list of tags.
query := map[string]string{
"limit": "5",
}
// Call the GetTags function to retrieve a list of tags based on the query parameters.
tagList, err := endpoints.GetTags(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the number of tags retrieved.
log.Println(len(tagList))
}
log.Println("----------")
// Log: Searching for tags containing "cat."
log.Println("Searching for tags containing 'cat': ")
// Define query parameters for searching tags that match "cat."
query = map[string]string{
"limit": "5",
"search[name_matches]": "cat*",
}
// Call the GetTags function with the search query to retrieve matching tags.
tagList, err = endpoints.GetTags(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the retrieved tags.
log.Println(tagList)
}
log.Println("----------")
// Log: Searching for tags with the category "artist."
log.Println("Searching for tags with the category 'artist': ")
// Define query parameters for searching tags in the "artist" category.
query = map[string]string{
"limit": "5",
"search[category]": "1",
}
// Call the GetTags function with the category filter to retrieve artist tags.
tagList, err = endpoints.GetTags(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the retrieved artist tags.
log.Println(tagList)
}
log.Println("----------")
}

View File

@ -1,57 +1,57 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single user.
log.Println("Getting a single user: ")
// Specify the username for retrieval.
username := "selloo" // Replace with the desired username.
// Call the GetUser function to retrieve the specified user.
user, err := endpoints.GetUser(requestContext, username)
if err != nil {
log.Println(err)
} else {
// Log the ID of the retrieved user.
log.Println(user.ID)
}
log.Println("----------")
// Log: Getting a list of users.
log.Println("Getting a list of users: ")
// Define query parameters for retrieving a list of users.
query := map[string]string{
"limit": "5",
}
// Call the GetUsers function to retrieve a list of users based on the query parameters.
userList, err := endpoints.GetUsers(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the number of users retrieved.
log.Println(len(userList))
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single user.
log.Println("Getting a single user: ")
// Specify the username for retrieval.
username := "selloo" // Replace with the desired username.
// Call the GetUser function to retrieve the specified user.
user, err := endpoints.GetUser(requestContext, username)
if err != nil {
log.Println(err)
} else {
// Log the ID of the retrieved user.
log.Println(user.ID)
}
log.Println("----------")
// Log: Getting a list of users.
log.Println("Getting a list of users: ")
// Define query parameters for retrieving a list of users.
query := map[string]string{
"limit": "5",
}
// Call the GetUsers function to retrieve a list of users based on the query parameters.
userList, err := endpoints.GetUsers(requestContext, query)
if err != nil {
log.Println(err)
} else {
// Log the number of users retrieved.
log.Println(len(userList))
}
log.Println("----------")
}

View File

@ -0,0 +1,55 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder/basic"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
log.Println("Getting a list of DB Exports: ")
getDBExportList := basic.NewGetDBExportListBuilder(requestContext)
dbExportFiles, err := getDBExportList.Execute()
if err != nil {
panic(err)
}
log.Printf("%d files found", len(dbExportFiles))
for _, v := range dbExportFiles {
log.Printf("File found: %s", v)
}
log.Println(dbExportFiles)
exportFileName := dbExportFiles[0]
log.Println("Downloading DB export")
log.Printf("File to download: %s", exportFileName)
getDBExportFile := basic.NewGetDBExportFileBuilder(requestContext)
rawFile, err := getDBExportFile.SetFile(exportFileName).Execute()
file, err := os.Create(exportFileName)
if err != nil {
panic(err)
}
defer file.Close()
err = os.WriteFile(exportFileName, rawFile, 0644)
if err != nil {
panic(err)
}
log.Printf("File %s downloaded", exportFileName)
}

View File

@ -1,43 +0,0 @@
package main
import (
"log"
"net/http"
"os"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
)
func main() {
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"),
APIKey: os.Getenv("API_KEY"),
}
log.Println("Getting DMails API user: ")
getDMails := builder.NewGetDMailsBuilder(requestContext)
dMails, err := getDMails.SetLimit(5).Execute()
if err != nil {
log.Println(err)
} else {
log.Println(dMails[0].Title)
}
log.Println("----------")
log.Println("Getting DMails for user: ")
dMails, err = getDMails.SetLimit(5).ByToName("specificUser").Execute()
if err != nil {
log.Println(err)
} else {
log.Println(dMails[0].Title)
}
log.Println("----------")
}

View File

@ -1,49 +1,49 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting favorites from the API.
log.Println("Getting favorites API user: ")
// Call the GetFavorites function to retrieve favorite posts.
getFavorites := builder.NewGetFavoritesBuilder(requestContext)
posts, err := getFavorites.SetLimit(5).Execute()
if err != nil {
log.Println(err)
} else {
// Log the URL of the first favorite post.
log.Println(posts[0].File.URL)
}
log.Println("----------")
// Log: Getting favorites for a specific user.
log.Println("Getting favorites for user: ")
// Call the GetFavorites function to retrieve favorite posts for the specified user.
posts, err = getFavorites.SetLimit(5).SetUserID(1337).Execute()
if err != nil {
log.Println(err)
} else {
// Log the URL of the first favorite post.
log.Println(posts[0].File.URL)
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder/basic"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting favorites from the API.
log.Println("Getting favorites API user: ")
// Call the GetFavorites function to retrieve favorite posts.
getFavorites := basic.NewGetFavoritesBuilder(requestContext)
posts, err := getFavorites.SetLimit(5).Execute()
if err != nil {
log.Println(err)
} else {
// Log the URL of the first favorite post.
log.Println(posts[0].File.URL)
}
log.Println("----------")
// Log: Getting favorites for a specific user.
log.Println("Getting favorites for user: ")
// Call the GetFavorites function to retrieve favorite posts for the specified user.
posts, err = getFavorites.SetLimit(5).SetUserID(1337).Execute()
if err != nil {
log.Println(err)
} else {
// Log the URL of the first favorite post.
log.Println(posts[0].File.URL)
}
log.Println("----------")
}

View File

@ -1,58 +1,58 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
"strconv"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single note.
log.Println("Getting single note: ")
// Specify the note ID for retrieval.
noteID := 36957 // Replace with the desired note's ID.
// Call the GetNote function to retrieve the specified note.
getNote := builder.NewGetNoteBuilder(requestContext)
note, err := getNote.SetNoteID(noteID).Execute()
if err != nil {
log.Println(err)
} else {
// Log the body of the retrieved note.
log.Println(note.Body)
}
log.Println("----------")
// Log: Getting a list of notes.
log.Println("Getting a list of notes: ")
// Call the GetNotes function to retrieve a list of notes based on the query parameters.
getNotes := builder.NewGetNotesBuilder(requestContext)
notes, err := getNotes.SetLimit(5).Active(true).SearchInBody("furry").Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of notes retrieved.
log.Println(len(notes))
for _, note := range notes {
log.Printf("Note by %s - %s : %s", note.CreatorName, note.Body, strconv.FormatInt(note.ID, 10))
}
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder/basic"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
"strconv"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single note.
log.Println("Getting single note: ")
// Specify the note ID for retrieval.
noteID := 36957 // Replace with the desired note's ID.
// Call the GetNote function to retrieve the specified note.
getNote := basic.NewGetNoteBuilder(requestContext)
note, err := getNote.SetNoteID(noteID).Execute()
if err != nil {
log.Println(err)
} else {
// Log the body of the retrieved note.
log.Println(note.Body)
}
log.Println("----------")
// Log: Getting a list of notes.
log.Println("Getting a list of notes: ")
// Call the GetNotes function to retrieve a list of notes based on the query parameters.
getNotes := basic.NewGetNotesBuilder(requestContext)
notes, err := getNotes.SetLimit(5).Active(true).SearchInBody("furry").Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of notes retrieved.
log.Println(len(notes))
for _, note := range notes {
log.Printf("Note by %s - %s : %s", note.CreatorName, note.Body, strconv.FormatInt(note.ID, 10))
}
}
log.Println("----------")
}

View File

@ -1,57 +1,57 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single pool.
log.Println("Getting single pool: ")
// Specify the pool ID for retrieval.
poolID := 36957 // Replace with the desired pool's ID.
// Call the GetPool function to retrieve the specified pool.
getPool := builder.NewGetPoolBuilder(requestContext)
pool, err := getPool.ID(poolID).Execute()
if err != nil {
log.Println(err)
} else {
// Log the name of the retrieved pool.
log.Println(pool.Name)
}
log.Println("----------")
// Log: Getting a list of pools.
log.Println("Getting a list of pools: ")
// Call the GetPools function to retrieve a list of pools based on the query parameters.
getPools := builder.NewGetPoolsBuilder(requestContext)
pools, err := getPools.SetLimit(5).Active(true).SearchDescription("mass effect").Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of pools retrieved.
log.Println(len(pools))
log.Println(pools[1].Name)
log.Println(pools[1].ID)
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder/basic"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single pool.
log.Println("Getting single pool: ")
// Specify the pool ID for retrieval.
poolID := 36957 // Replace with the desired pool's ID.
// Call the GetPool function to retrieve the specified pool.
getPool := basic.NewGetPoolBuilder(requestContext)
pool, err := getPool.ID(poolID).Execute()
if err != nil {
log.Println(err)
} else {
// Log the name of the retrieved pool.
log.Println(pool.Name)
}
log.Println("----------")
// Log: Getting a list of pools.
log.Println("Getting a list of pools: ")
// Call the GetPools function to retrieve a list of pools based on the query parameters.
getPools := basic.NewGetPoolsBuilder(requestContext)
pools, err := getPools.SetLimit(5).Active(true).SearchDescription("mass effect").Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of pools retrieved.
log.Println(len(pools))
log.Println(pools[1].Name)
log.Println(pools[1].ID)
}
log.Println("----------")
}

View File

@ -1,68 +1,68 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single post.
log.Println("Getting single post: ")
// Specify the post ID for retrieval.
var postID model.PostID = 4353480 // Replace with the desired post's ID.
// Call the GetPost function to retrieve the specified post.
getPost := builder.NewGetPostBuilder(requestContext)
post, err := getPost.SetPostID(postID).Execute()
if err != nil {
log.Println(err)
} else {
// Log the URL of the retrieved post.
log.Println(post.File.URL)
}
log.Println("----------")
// Log: Getting a list of posts.
log.Println("Getting a list of posts: ")
// Call the GetPosts function to retrieve a list of posts based on the query parameters.
getPosts := builder.NewGetPostsBuilder(requestContext)
posts, err := getPosts.SetLimit(5).Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of posts retrieved.
log.Println(len(posts))
}
log.Println("----------")
// Log: Getting a list of posts with tags.
log.Println("Getting a list of posts: ")
// Call the GetPosts function to retrieve a list of posts based on the query parameters.
posts, err = getPosts.SetLimit(5).Tags("fennec").Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of posts retrieved.
log.Println(len(posts))
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder/basic"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single post.
log.Println("Getting single post: ")
// Specify the post ID for retrieval.
var postID model.PostID = 4353480 // Replace with the desired post's ID.
// Call the GetPost function to retrieve the specified post.
getPost := basic.NewGetPostBuilder(requestContext)
post, err := getPost.SetPostID(postID).Execute()
if err != nil {
log.Println(err)
} else {
// Log the URL of the retrieved post.
log.Println(post.File.URL)
}
log.Println("----------")
// Log: Getting a list of posts.
log.Println("Getting a list of posts: ")
// Call the GetPosts function to retrieve a list of posts based on the query parameters.
getPosts := basic.NewGetPostsBuilder(requestContext)
posts, err := getPosts.SetLimit(5).Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of posts retrieved.
log.Println(len(posts))
}
log.Println("----------")
// Log: Getting a list of posts with tags.
log.Println("Getting a list of posts: ")
// Call the GetPosts function to retrieve a list of posts based on the query parameters.
posts, err = getPosts.SetLimit(5).Tags("fennec").Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of posts retrieved.
log.Println(len(posts))
}
log.Println("----------")
}

View File

@ -1,81 +1,81 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single tag.
log.Println("Getting a single tag: ")
// Specify the tag ID for retrieval.
tagID := 1530 // Replace with the desired tag's ID.
// Call the GetTag function to retrieve the specified tag.
getTag := builder.NewGetTagBuilder(requestContext)
tag, err := getTag.SetTagID(tagID).Execute()
if err != nil {
log.Println(err)
} else {
// Log the name of the retrieved tag.
log.Println(tag.Name)
}
log.Println("----------")
// Log: Getting a list of tags.
log.Println("Getting a list of tags: ")
// Call the GetTags function to retrieve a list of tags based on the query parameters.
getTags := builder.NewGetTagsBuilder(requestContext)
tagList, err := getTags.SetLimit(5).Artist(false).Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of tags retrieved.
log.Println(len(tagList))
}
log.Println("----------")
// Log: Searching for tags containing "cat."
log.Println("Searching for tags containing 'cat': ")
// Call the GetTags function with the search query to retrieve matching tags.
tagList, err = getTags.SetLimit(5).SearchName("cat*").Execute()
if err != nil {
log.Println(err)
} else {
// Log the retrieved tags.
log.Println(tagList)
}
log.Println("----------")
// Log: Searching for tags with the category "artist."
log.Println("Searching for tags with the category 'artist': ")
// Call the GetTags function with the category filter to retrieve artist tags.
tagList, err = getTags.SetLimit(5).SearchCategory(model.Artist).Execute()
if err != nil {
log.Println(err)
} else {
// Log the retrieved artist tags.
log.Println(tagList)
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder/basic"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single tag.
log.Println("Getting a single tag: ")
// Specify the tag ID for retrieval.
tagID := 1530 // Replace with the desired tag's ID.
// Call the GetTag function to retrieve the specified tag.
getTag := basic.NewGetTagBuilder(requestContext)
tag, err := getTag.SetTagID(tagID).Execute()
if err != nil {
log.Println(err)
} else {
// Log the name of the retrieved tag.
log.Println(tag.Name)
}
log.Println("----------")
// Log: Getting a list of tags.
log.Println("Getting a list of tags: ")
// Call the GetTags function to retrieve a list of tags based on the query parameters.
getTags := basic.NewGetTagsBuilder(requestContext)
tagList, err := getTags.SetLimit(5).Artist(false).Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of tags retrieved.
log.Println(len(tagList))
}
log.Println("----------")
// Log: Searching for tags containing "cat."
log.Println("Searching for tags containing 'cat': ")
// Call the GetTags function with the search query to retrieve matching tags.
tagList, err = getTags.SetLimit(5).SearchName("cat*").Execute()
if err != nil {
log.Println(err)
} else {
// Log the retrieved tags.
log.Println(tagList)
}
log.Println("----------")
// Log: Searching for tags with the category "artist."
log.Println("Searching for tags with the category 'artist': ")
// Call the GetTags function with the category filter to retrieve artist tags.
tagList, err = getTags.SetLimit(5).SearchCategory(model.Artist).Execute()
if err != nil {
log.Println(err)
} else {
// Log the retrieved artist tags.
log.Println(tagList)
}
log.Println("----------")
}

View File

@ -1,54 +1,54 @@
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single user.
log.Println("Getting a single user: ")
// Specify the username for retrieval.
username := "selloo" // Replace with the desired username.
// Call the GetUser function to retrieve the specified user.
userBuilder := builder.NewGetUserBuilder(requestContext)
user, err := userBuilder.SetUsername(username).Execute()
if err != nil {
log.Println(err)
} else {
// Log the ID of the retrieved user.
log.Println(user.ID)
}
log.Println("----------")
// Log: Getting a list of users.
log.Println("Getting a list of users: ")
// Call the GetUsers function to retrieve a list of users based on the query parameters.
usersBuilder := builder.NewGetUsersBuilder(requestContext)
userList, err := usersBuilder.SetLimit(5).Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of users retrieved.
log.Println(len(userList))
}
log.Println("----------")
}
package main
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder/basic"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"log"
"net/http"
"os"
)
func main() {
// Define the request context with essential information.
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: os.Getenv("API_USER"), // Replace with your username
APIKey: os.Getenv("API_KEY"), // Replace with your API key
}
// Log: Getting a single user.
log.Println("Getting a single user: ")
// Specify the username for retrieval.
username := "selloo" // Replace with the desired username.
// Call the GetUser function to retrieve the specified user.
userBuilder := basic.NewGetUserBuilder(requestContext)
user, err := userBuilder.SetUsername(username).Execute()
if err != nil {
log.Println(err)
} else {
// Log the ID of the retrieved user.
log.Println(user.ID)
}
log.Println("----------")
// Log: Getting a list of users.
log.Println("Getting a list of users: ")
// Call the GetUsers function to retrieve a list of users based on the query parameters.
usersBuilder := basic.NewGetUsersBuilder(requestContext)
userList, err := usersBuilder.SetLimit(5).Execute()
if err != nil {
log.Println(err)
} else {
// Log the number of users retrieved.
log.Println(len(userList))
}
log.Println("----------")
}

25
go.mod
View File

@ -1,11 +1,14 @@
module git.dragse.it/anthrove/e621-sdk-go
go 1.21.3
require (
github.com/jarcoal/httpmock v1.3.1
github.com/joho/godotenv v1.5.1
golang.org/x/time v0.3.0
)
require golang.org/x/net v0.18.0 // indirect
module git.dragse.it/anthrove/e621-sdk-go
go 1.21.3
require (
github.com/jarcoal/httpmock v1.3.1
github.com/joho/godotenv v1.5.1
golang.org/x/time v0.3.0
)
require (
github.com/gocarina/gocsv v0.0.0-20230616125104-99d496ca653d // indirect
golang.org/x/net v0.18.0 // indirect
)

26
go.sum
View File

@ -1,12 +1,14 @@
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/jarcoal/httpmock v1.3.1 h1:iUx3whfZWVf3jT01hQTO/Eo5sAYtB2/rqaUuOtpInww=
github.com/jarcoal/httpmock v1.3.1/go.mod h1:3yb8rc4BI7TCBhFY8ng0gjuLKJNquuDNiPaZjnENuYg=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/maxatome/go-testdeep v1.12.0 h1:Ql7Go8Tg0C1D/uMMX59LAoYK7LffeJQ6X2T04nTH68g=
github.com/maxatome/go-testdeep v1.12.0/go.mod h1:lPZc/HAcJMP92l7yI6TRz1aZN5URwUBUAfUNvrclaNM=
golang.org/x/net v0.18.0 h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg=
golang.org/x/net v0.18.0/go.mod h1:/czyP5RqHAH4odGYxBJ1qz0+CE5WZ+2j1YgoEo8F2jQ=
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gocarina/gocsv v0.0.0-20230616125104-99d496ca653d h1:KbPOUXFUDJxwZ04vbmDOc3yuruGvVO+LOa7cVER3yWw=
github.com/gocarina/gocsv v0.0.0-20230616125104-99d496ca653d/go.mod h1:5YoVOkjYAQumqlV356Hj3xeYh4BdZuLE0/nRkf2NKkI=
github.com/jarcoal/httpmock v1.3.1 h1:iUx3whfZWVf3jT01hQTO/Eo5sAYtB2/rqaUuOtpInww=
github.com/jarcoal/httpmock v1.3.1/go.mod h1:3yb8rc4BI7TCBhFY8ng0gjuLKJNquuDNiPaZjnENuYg=
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
github.com/maxatome/go-testdeep v1.12.0 h1:Ql7Go8Tg0C1D/uMMX59LAoYK7LffeJQ6X2T04nTH68g=
github.com/maxatome/go-testdeep v1.12.0/go.mod h1:lPZc/HAcJMP92l7yI6TRz1aZN5URwUBUAfUNvrclaNM=
golang.org/x/net v0.18.0 h1:mIYleuAkSbHh0tCv7RvjL3F6ZVbLjq4+R7zbOn3Kokg=
golang.org/x/net v0.18.0/go.mod h1:/czyP5RqHAH4odGYxBJ1qz0+CE5WZ+2j1YgoEo8F2jQ=
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=

View File

@ -1,4 +0,0 @@
package main
func main() {
}

View File

@ -0,0 +1,54 @@
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
)
// DBExportFileBuilder defines an interface for building and executing requests to retrieve a specific exported database file.
type DBExportFileBuilder interface {
// SetFile sets the name of the file to be retrieved.
SetFile(fileName string) DBExportFileBuilder
// Execute sends the request and returns the content of the exported database file or an error if the request fails.
Execute() ([]byte, error)
}
// NewGetDBExportFileBuilder creates a new instance of DBExportFileBuilder.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - DBExportFileBuilder: An instance of the DBExportFileBuilder interface.
func NewGetDBExportFileBuilder(requestContext model.RequestContext) DBExportFileBuilder {
return &getDBExportFile{
requestContext: requestContext,
}
}
// getDBExportFile is an implementation of the DBExportFileBuilder interface.
type getDBExportFile struct {
requestContext model.RequestContext
fileName string
}
// SetFile sets the name of the file to be retrieved.
//
// Parameters:
// - fileName: The name of the exported database file.
//
// Returns:
// - DBExportFileBuilder: The instance of the DBExportFileBuilder for method chaining.
func (g *getDBExportFile) SetFile(fileName string) DBExportFileBuilder {
g.fileName = fileName
return g
}
// Execute sends the API request to retrieve the content of a specific exported database file.
//
// Returns:
// - []byte: The content of the exported database file.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getDBExportFile) Execute() ([]byte, error) {
return endpoints.GetDBExportFile(g.requestContext, g.fileName)
}

View File

@ -0,0 +1,39 @@
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
)
// DBExportListBuilder defines an interface for building and executing requests to retrieve a list of exported databases.
type DBExportListBuilder interface {
// Execute sends the request and returns a list of exported databases or an error if the request fails.
Execute() ([]string, error)
}
// NewGetDBExportListBuilder creates a new instance of DBExportListBuilder.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - DBExportListBuilder: An instance of the DBExportListBuilder interface.
func NewGetDBExportListBuilder(requestContext model.RequestContext) DBExportListBuilder {
return &getDBExportList{
requestContext: requestContext,
}
}
// getDBExportList is an implementation of the DBExportListBuilder interface.
type getDBExportList struct {
requestContext model.RequestContext
}
// Execute sends the API request to retrieve a list of exported databases.
//
// Returns:
// - []string: A list of exported databases.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getDBExportList) Execute() ([]string, error) {
return endpoints.GetDBExportList(g.requestContext)
}

View File

@ -0,0 +1,95 @@
package basic
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// FavoritesBuilder represents a builder for constructing queries to retrieve user's favorite posts.
type FavoritesBuilder interface {
// SetUserID sets the user ID for the query.
SetUserID(userID model.UserID) FavoritesBuilder
// SetLimit sets the maximum number of favorite posts to retrieve.
SetLimit(limitFavorites int) FavoritesBuilder
// Page sets the page number for paginated results.
Page(pageNumber int) FavoritesBuilder
// Execute sends the constructed query and returns a slice of favorite posts and an error if any.
Execute() ([]model.Post, error)
}
// NewGetFavoritesBuilder creates a new instance of FavoritesBuilder with the provided RequestContext.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - FavoritesBuilder: An instance of the FavoritesBuilder interface.
func NewGetFavoritesBuilder(requestContext model.RequestContext) FavoritesBuilder {
return &getFavorites{
requestContext: requestContext,
query: make(map[string]string),
}
}
// getFavorites is an implementation of the FavoritesBuilder interface.
type getFavorites struct {
query map[string]string
requestContext model.RequestContext
}
// SetUserID sets the user ID for the query.
//
// Parameters:
// - userID: The ID of the user whose favorite posts are to be retrieved.
//
// Returns:
// - FavoritesBuilder: The instance of the FavoritesBuilder for method chaining.
func (g *getFavorites) SetUserID(userID model.UserID) FavoritesBuilder {
g.query["user_id"] = strconv.Itoa(int(userID))
return g
}
// SetLimit sets the maximum number of favorite posts to retrieve.
//
// Parameters:
// - limitFavorites: The maximum number of favorite posts to retrieve.
//
// Returns:
// - FavoritesBuilder: The instance of the FavoritesBuilder for method chaining.
func (g *getFavorites) SetLimit(limitFavorites int) FavoritesBuilder {
g.query["limit"] = strconv.Itoa(limitFavorites)
return g
}
// Page sets the page number for paginated results.
//
// Parameters:
// - pageNumber: The page number for paginated results.
//
// Returns:
// - FavoritesBuilder: The instance of the FavoritesBuilder for method chaining.
func (g *getFavorites) Page(pageNumber int) FavoritesBuilder {
g.query["page"] = strconv.Itoa(pageNumber)
return g
}
// Execute sends the constructed query and returns a slice of favorite posts and an error if any.
//
// Returns:
// - []model.Post: A slice of favorite posts.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getFavorites) Execute() ([]model.Post, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
favorites, err := endpoints.GetFavorites(g.requestContext, g.query)
if err != nil {
return nil, err
}
return favorites, nil
}

View File

@ -1,48 +1,48 @@
package builder
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetFavorites(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.PostResponse]("../../../tests/posts.json")
if err != nil {
t.Error(err)
return
}
jsonResponser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/favorites.json", jsonResponser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getFavorites := NewGetFavoritesBuilder(requestContext)
posts, err := getFavorites.SetLimit(3).Execute()
if err != nil {
t.Error(err)
return
}
if posts[0].ID == response.Posts[0].ID && posts[1].File.Md5 == response.Posts[1].File.Md5 && posts[2].File.EXT == response.Posts[2].File.EXT {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", posts, response)
}
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetFavorites(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.PostResponse]("../../../tests/posts.json")
if err != nil {
t.Error(err)
return
}
jsonResponser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/favorites.json", jsonResponser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getFavorites := NewGetFavoritesBuilder(requestContext)
posts, err := getFavorites.SetLimit(3).Execute()
if err != nil {
t.Error(err)
return
}
if posts[0].ID == response.Posts[0].ID && posts[1].File.Md5 == response.Posts[1].File.Md5 && posts[2].File.EXT == response.Posts[2].File.EXT {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", posts, response)
}

View File

@ -1,47 +1,64 @@
package builder
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// NoteBuilder represents a builder for constructing queries to retrieve a specific note.
type NoteBuilder interface {
// SetNoteID sets the note ID for the query.
SetNoteID(noteID int) NoteBuilder
// Execute sends the constructed query and returns the requested note and an error, if any.
Execute() (*model.Note, error)
}
// NewGetNoteBuilder creates a new NoteBuilder with the provided RequestContext.
func NewGetNoteBuilder(requestContext model.RequestContext) NoteBuilder {
return &getNote{requestContext: requestContext}
}
type getNote struct {
requestContext model.RequestContext
noteID int
}
// SetNoteID sets the note ID for the query.
func (g *getNote) SetNoteID(noteID int) NoteBuilder {
g.noteID = noteID
return g
}
// Execute sends the constructed query and returns the requested note and an error, if any.
func (g *getNote) Execute() (*model.Note, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
note, err := endpoints.GetNote(g.requestContext, strconv.Itoa(g.noteID))
if err != nil {
return nil, err
}
return &note, nil
}
package basic
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// NoteBuilder represents a builder for constructing queries to retrieve a specific note.
type NoteBuilder interface {
// SetNoteID sets the note ID for the query.
SetNoteID(noteID int) NoteBuilder
// Execute sends the constructed query and returns the requested note and an error, if any.
Execute() (*model.Note, error)
}
// NewGetNoteBuilder creates a new instance of NoteBuilder with the provided RequestContext.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - NoteBuilder: An instance of the NoteBuilder interface.
func NewGetNoteBuilder(requestContext model.RequestContext) NoteBuilder {
return &getNote{requestContext: requestContext}
}
// getNote is an implementation of the NoteBuilder interface.
type getNote struct {
requestContext model.RequestContext
noteID int
}
// SetNoteID sets the note ID for the query.
//
// Parameters:
// - noteID: The ID of the note to be retrieved.
//
// Returns:
// - NoteBuilder: The instance of the NoteBuilder for method chaining.
func (g *getNote) SetNoteID(noteID int) NoteBuilder {
g.noteID = noteID
return g
}
// Execute sends the constructed query and returns the requested note and an error, if any.
//
// Returns:
// - *model.Note: The requested note.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getNote) Execute() (*model.Note, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
note, err := endpoints.GetNote(g.requestContext, strconv.Itoa(g.noteID))
if err != nil {
return nil, err
}
return &note, nil
}

View File

@ -1,49 +1,49 @@
package builder
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetNote(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Note]("../../../tests/note.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/notes/36957.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getNote := NewGetNoteBuilder(requestContext)
pool, err := getNote.SetNoteID(36957).Execute()
if err != nil {
t.Error(err)
return
}
if pool.ID == response.ID && pool.Body == response.Body {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pool, response)
}
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetNote(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Note]("../../../tests/note.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/notes/36957.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getNote := NewGetNoteBuilder(requestContext)
pool, err := getNote.SetNoteID(36957).Execute()
if err != nil {
t.Error(err)
return
}
if pool.ID == response.ID && pool.Body == response.Body {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pool, response)
}

View File

@ -1,98 +1,151 @@
package builder
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// NotesBuilder represents a builder for constructing queries to retrieve notes.
type NotesBuilder interface {
// SearchInBody sets the query to search for notes containing a specific text in their body.
SearchInBody(body string) NotesBuilder
// NoteID sets the query to search for a note with a specific note ID.
NoteID(noteID int) NotesBuilder
// SearchTags sets the query to search for notes containing specific tags.
SearchTags(tags string) NotesBuilder
// SearchCreatorID sets the query to search for notes created by a specific user (by their user ID).
SearchCreatorID(creatorID int) NotesBuilder
// SearchCreatorName sets the query to search for notes created by a specific user (by their username).
SearchCreatorName(creatorName string) NotesBuilder
// Active sets whether to search for active or inactive notes.
Active(isActive bool) NotesBuilder
// SetLimit sets the maximum number of notes to retrieve.
SetLimit(limitNotes int) NotesBuilder
// Execute sends the constructed query and returns a slice of notes and an error, if any.
Execute() ([]model.Note, error)
}
// NewGetNotesBuilder creates a new NotesBuilder with the provided RequestContext.
func NewGetNotesBuilder(requestContext model.RequestContext) NotesBuilder {
return &getNotes{
requestContext: requestContext,
query: make(map[string]string),
}
}
type getNotes struct {
requestContext model.RequestContext
query map[string]string
}
// SearchInBody sets the query to search for notes containing a specific text in their body.
func (g *getNotes) SearchInBody(body string) NotesBuilder {
g.query["search[body_matches]"] = body
return g
}
// NoteID sets the query to search for a note with a specific note ID.
func (g *getNotes) NoteID(noteID int) NotesBuilder {
g.query["search[post_id]"] = strconv.Itoa(noteID)
return g
}
// SearchTags sets the query to search for notes containing specific tags.
func (g *getNotes) SearchTags(tags string) NotesBuilder {
g.query["search[post_tags_match]"] = tags
return g
}
// SearchCreatorID sets the query to search for notes created by a specific user (by their user ID).
func (g *getNotes) SearchCreatorID(creatorID int) NotesBuilder {
g.query["search[creator_id]"] = strconv.Itoa(creatorID)
return g
}
// SearchCreatorName sets the query to search for notes created by a specific user (by their username).
func (g *getNotes) SearchCreatorName(creatorName string) NotesBuilder {
g.query["search[creator_name]"] = creatorName
return g
}
// Active sets whether to search for active or inactive notes.
func (g *getNotes) Active(isActive bool) NotesBuilder {
g.query["search[is_active]"] = strconv.FormatBool(isActive)
return g
}
// SetLimit sets the maximum number of notes to retrieve.
func (g *getNotes) SetLimit(limitNotes int) NotesBuilder {
g.query["limit"] = strconv.Itoa(limitNotes)
return g
}
// Execute sends the constructed query and returns a slice of notes and an error, if any.
func (g *getNotes) Execute() ([]model.Note, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
notes, err := endpoints.GetNotes(g.requestContext, g.query)
if err != nil {
return nil, err
}
return notes, nil
}
package basic
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// NotesBuilder represents a builder for constructing queries to retrieve notes.
type NotesBuilder interface {
// SearchInBody sets the query to search for notes containing a specific text in their body.
SearchInBody(body string) NotesBuilder
// NoteID sets the query to search for a note with a specific note ID.
NoteID(noteID int) NotesBuilder
// SearchTags sets the query to search for notes containing specific tags.
SearchTags(tags string) NotesBuilder
// SearchCreatorID sets the query to search for notes created by a specific user (by their user ID).
SearchCreatorID(creatorID int) NotesBuilder
// SearchCreatorName sets the query to search for notes created by a specific user (by their username).
SearchCreatorName(creatorName string) NotesBuilder
// Active sets whether to search for active or inactive notes.
Active(isActive bool) NotesBuilder
// SetLimit sets the maximum number of notes to retrieve.
SetLimit(limitNotes int) NotesBuilder
// Execute sends the constructed query and returns a slice of notes and an error, if any.
Execute() ([]model.Note, error)
}
// NewGetNotesBuilder creates a new instance of NotesBuilder with the provided RequestContext.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - NotesBuilder: An instance of the NotesBuilder interface.
func NewGetNotesBuilder(requestContext model.RequestContext) NotesBuilder {
return &getNotes{
requestContext: requestContext,
query: make(map[string]string),
}
}
// getNotes is an implementation of the NotesBuilder interface.
type getNotes struct {
requestContext model.RequestContext
query map[string]string
}
// SearchInBody sets the query to search for notes containing a specific text in their body.
//
// Parameters:
// - body: The text to search for in the notes' body.
//
// Returns:
// - NotesBuilder: The instance of the NotesBuilder for method chaining.
func (g *getNotes) SearchInBody(body string) NotesBuilder {
g.query["search[body_matches]"] = body
return g
}
// NoteID sets the query to search for a note with a specific note ID.
//
// Parameters:
// - noteID: The ID of the note to be retrieved.
//
// Returns:
// - NotesBuilder: The instance of the NotesBuilder for method chaining.
func (g *getNotes) NoteID(noteID int) NotesBuilder {
g.query["search[post_id]"] = strconv.Itoa(noteID)
return g
}
// SearchTags sets the query to search for notes containing specific tags.
//
// Parameters:
// - tags: The tags to search for in the notes.
//
// Returns:
// - NotesBuilder: The instance of the NotesBuilder for method chaining.
func (g *getNotes) SearchTags(tags string) NotesBuilder {
g.query["search[post_tags_match]"] = tags
return g
}
// SearchCreatorID sets the query to search for notes created by a specific user (by their user ID).
//
// Parameters:
// - creatorID: The ID of the user who created the notes.
//
// Returns:
// - NotesBuilder: The instance of the NotesBuilder for method chaining.
func (g *getNotes) SearchCreatorID(creatorID int) NotesBuilder {
g.query["search[creator_id]"] = strconv.Itoa(creatorID)
return g
}
// SearchCreatorName sets the query to search for notes created by a specific user (by their username).
//
// Parameters:
// - creatorName: The username of the user who created the notes.
//
// Returns:
// - NotesBuilder: The instance of the NotesBuilder for method chaining.
func (g *getNotes) SearchCreatorName(creatorName string) NotesBuilder {
g.query["search[creator_name]"] = creatorName
return g
}
// Active sets whether to search for active or inactive notes.
//
// Parameters:
// - isActive: A boolean indicating whether to search for active notes (true) or inactive notes (false).
//
// Returns:
// - NotesBuilder: The instance of the NotesBuilder for method chaining.
func (g *getNotes) Active(isActive bool) NotesBuilder {
g.query["search[is_active]"] = strconv.FormatBool(isActive)
return g
}
// SetLimit sets the maximum number of notes to retrieve.
//
// Parameters:
// - limitNotes: The maximum number of notes to retrieve.
//
// Returns:
// - NotesBuilder: The instance of the NotesBuilder for method chaining.
func (g *getNotes) SetLimit(limitNotes int) NotesBuilder {
g.query["limit"] = strconv.Itoa(limitNotes)
return g
}
// Execute sends the constructed query and returns a slice of notes and an error, if any.
//
// Returns:
// - []model.Note: A slice of notes.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getNotes) Execute() ([]model.Note, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
notes, err := endpoints.GetNotes(g.requestContext, g.query)
if err != nil {
return nil, err
}
return notes, nil
}

View File

@ -1,49 +1,49 @@
package builder
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetNotes(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.Note]("../../../tests/notes.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/notes.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getNotes := NewGetNotesBuilder(requestContext)
pools, err := getNotes.SetLimit(3).Execute()
if err != nil {
t.Error(err)
return
}
if pools[0].ID == response[0].ID && pools[1].Body == response[1].Body && pools[2].UpdatedAt == response[2].UpdatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pools, response)
}
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetNotes(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.Note]("../../../tests/notes.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/notes.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getNotes := NewGetNotesBuilder(requestContext)
pools, err := getNotes.SetLimit(3).Execute()
if err != nil {
t.Error(err)
return
}
if pools[0].ID == response[0].ID && pools[1].Body == response[1].Body && pools[2].UpdatedAt == response[2].UpdatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pools, response)
}

View File

@ -1,47 +1,64 @@
package builder
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// PoolBuilder represents a builder for constructing queries to retrieve a specific pool.
type PoolBuilder interface {
// ID sets the pool ID for the query.
ID(poolID int) PoolBuilder
// Execute sends the constructed query and returns the requested pool and an error, if any.
Execute() (model.Pool, error)
}
// NewGetPoolBuilder creates a new PoolBuilder with the provided RequestContext.
func NewGetPoolBuilder(requestContext model.RequestContext) PoolBuilder {
return &getPool{requestContext: requestContext}
}
type getPool struct {
requestContext model.RequestContext
id int
}
// ID sets the pool ID for the query.
func (g *getPool) ID(poolID int) PoolBuilder {
g.id = poolID
return g
}
// Execute sends the constructed query and returns the requested pool and an error, if any.
func (g *getPool) Execute() (model.Pool, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return model.Pool{}, err
}
}
pool, err := endpoints.GetPool(g.requestContext, strconv.Itoa(g.id))
if err != nil {
return model.Pool{}, err
}
return pool, nil
}
package basic
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// PoolBuilder represents a builder for constructing queries to retrieve a specific pool.
type PoolBuilder interface {
// ID sets the pool ID for the query.
ID(poolID int) PoolBuilder
// Execute sends the constructed query and returns the requested pool and an error, if any.
Execute() (model.Pool, error)
}
// NewGetPoolBuilder creates a new instance of PoolBuilder with the provided RequestContext.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - PoolBuilder: An instance of the PoolBuilder interface.
func NewGetPoolBuilder(requestContext model.RequestContext) PoolBuilder {
return &getPool{requestContext: requestContext}
}
// getPool is an implementation of the PoolBuilder interface.
type getPool struct {
requestContext model.RequestContext
id int
}
// ID sets the pool ID for the query.
//
// Parameters:
// - poolID: The ID of the pool to be retrieved.
//
// Returns:
// - PoolBuilder: The instance of the PoolBuilder for method chaining.
func (g *getPool) ID(poolID int) PoolBuilder {
g.id = poolID
return g
}
// Execute sends the constructed query and returns the requested pool and an error, if any.
//
// Returns:
// - model.Pool: The requested pool.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getPool) Execute() (model.Pool, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return model.Pool{}, err
}
}
pool, err := endpoints.GetPool(g.requestContext, strconv.Itoa(g.id))
if err != nil {
return model.Pool{}, err
}
return pool, nil
}

View File

@ -1,49 +1,49 @@
package builder
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPool(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Pool]("../../../tests/pool.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/pools/36957.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getPool := NewGetPoolBuilder(requestContext)
pool, err := getPool.ID(36957).Execute()
if err != nil {
t.Error(err)
return
}
if pool.ID == response.ID && pool.Name == response.Name {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pool, response)
}
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPool(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Pool]("../../../tests/pool.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/pools/36957.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getPool := NewGetPoolBuilder(requestContext)
pool, err := getPool.ID(36957).Execute()
if err != nil {
t.Error(err)
return
}
if pool.ID == response.ID && pool.Name == response.Name {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pool, response)
}

View File

@ -1,114 +1,179 @@
package builder
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// PoolsBuilder represents a builder for constructing queries to retrieve pools.
type PoolsBuilder interface {
// SearchName sets the query to search for pools with a specific name.
SearchName(name string) PoolsBuilder
// SearchID sets the query to search for pools with specific pool IDs.
SearchID(poolIDs string) PoolsBuilder
// SearchDescription sets the query to search for pools with specific descriptions.
SearchDescription(description string) PoolsBuilder
// SearchCreatorID sets the query to search for pools created by a specific user (by their user ID).
SearchCreatorID(creatorID int) PoolsBuilder
// SearchCreatorName sets the query to search for pools created by a specific user (by their username).
SearchCreatorName(creatorName string) PoolsBuilder
// Active sets whether to search for active or inactive pools.
Active(isActive bool) PoolsBuilder
// SearchCategory sets the query to search for pools in a specific category.
SearchCategory(category model.PoolCategory) PoolsBuilder
// Order sets the ordering of the retrieved pools.
Order(order model.PoolOrder) PoolsBuilder
// SetLimit sets the maximum number of pools to retrieve.
SetLimit(limitPools int) PoolsBuilder
// Execute sends the constructed query and returns a slice of pools and an error, if any.
Execute() ([]model.Pool, error)
}
// NewGetPoolsBuilder creates a new PoolsBuilder with the provided RequestContext.
func NewGetPoolsBuilder(requestContext model.RequestContext) PoolsBuilder {
return &getPools{
requestContext: requestContext,
query: make(map[string]string),
}
}
type getPools struct {
requestContext model.RequestContext
query map[string]string
}
// SearchName sets the query to search for pools with a specific name.
func (g *getPools) SearchName(name string) PoolsBuilder {
g.query["search[name_matches]"] = name
return g
}
// SearchID sets the query to search for pools with specific pool IDs.
func (g *getPools) SearchID(poolIDs string) PoolsBuilder {
g.query["search[id]"] = poolIDs
return g
}
// SearchDescription sets the query to search for pools with specific descriptions.
func (g *getPools) SearchDescription(description string) PoolsBuilder {
g.query["search[description_matches]"] = description
return g
}
// SearchCreatorID sets the query to search for pools created by a specific user (by their user ID).
func (g *getPools) SearchCreatorID(creatorID int) PoolsBuilder {
g.query["search[creator_id]"] = strconv.Itoa(creatorID)
return g
}
// SearchCreatorName sets the query to search for pools created by a specific user (by their username).
func (g *getPools) SearchCreatorName(creatorName string) PoolsBuilder {
g.query["search[creator_name]"] = creatorName
return g
}
// Active sets whether to search for active or inactive pools.
func (g *getPools) Active(isActive bool) PoolsBuilder {
g.query["search[is_active]"] = strconv.FormatBool(isActive)
return g
}
// SearchCategory sets the query to search for pools in a specific category.
func (g *getPools) SearchCategory(category model.PoolCategory) PoolsBuilder {
g.query["search[category]"] = string(category)
return g
}
// Order sets the ordering of the retrieved pools.
func (g *getPools) Order(order model.PoolOrder) PoolsBuilder {
g.query["search[order]"] = string(order)
return g
}
// SetLimit sets the maximum number of pools to retrieve.
func (g *getPools) SetLimit(limitPools int) PoolsBuilder {
g.query["limit"] = strconv.Itoa(limitPools)
return g
}
// Execute sends the constructed query and returns a slice of pools and an error, if any.
func (g *getPools) Execute() ([]model.Pool, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
pools, err := endpoints.GetPools(g.requestContext, g.query)
if err != nil {
return nil, err
}
return pools, nil
}
package basic
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// PoolsBuilder represents a builder for constructing queries to retrieve pools.
type PoolsBuilder interface {
// SearchName sets the query to search for pools with a specific name.
SearchName(name string) PoolsBuilder
// SearchID sets the query to search for pools with specific pool IDs.
SearchID(poolIDs string) PoolsBuilder
// SearchDescription sets the query to search for pools with specific descriptions.
SearchDescription(description string) PoolsBuilder
// SearchCreatorID sets the query to search for pools created by a specific user (by their user ID).
SearchCreatorID(creatorID int) PoolsBuilder
// SearchCreatorName sets the query to search for pools created by a specific user (by their username).
SearchCreatorName(creatorName string) PoolsBuilder
// Active sets whether to search for active or inactive pools.
Active(isActive bool) PoolsBuilder
// SearchCategory sets the query to search for pools in a specific category.
SearchCategory(category model.PoolCategory) PoolsBuilder
// Order sets the ordering of the retrieved pools.
Order(order model.PoolOrder) PoolsBuilder
// SetLimit sets the maximum number of pools to retrieve.
SetLimit(limitPools int) PoolsBuilder
// Execute sends the constructed query and returns a slice of pools and an error, if any.
Execute() ([]model.Pool, error)
}
// NewGetPoolsBuilder creates a new instance of PoolsBuilder with the provided RequestContext.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - PoolsBuilder: An instance of the PoolsBuilder interface.
func NewGetPoolsBuilder(requestContext model.RequestContext) PoolsBuilder {
return &getPools{
requestContext: requestContext,
query: make(map[string]string),
}
}
// getPools is an implementation of the PoolsBuilder interface.
type getPools struct {
requestContext model.RequestContext
query map[string]string
}
// SearchName sets the query to search for pools with a specific name.
//
// Parameters:
// - name: The name to search for in the pools.
//
// Returns:
// - PoolsBuilder: The instance of the PoolsBuilder for method chaining.
func (g *getPools) SearchName(name string) PoolsBuilder {
g.query["search[name_matches]"] = name
return g
}
// SearchID sets the query to search for pools with specific pool IDs.
//
// Parameters:
// - poolIDs: The pool IDs to search for, separated by commas.
//
// Returns:
// - PoolsBuilder: The instance of the PoolsBuilder for method chaining.
func (g *getPools) SearchID(poolIDs string) PoolsBuilder {
g.query["search[id]"] = poolIDs
return g
}
// SearchDescription sets the query to search for pools with specific descriptions.
//
// Parameters:
// - description: The description to search for in the pools.
//
// Returns:
// - PoolsBuilder: The instance of the PoolsBuilder for method chaining.
func (g *getPools) SearchDescription(description string) PoolsBuilder {
g.query["search[description_matches]"] = description
return g
}
// SearchCreatorID sets the query to search for pools created by a specific user (by their user ID).
//
// Parameters:
// - creatorID: The ID of the user who created the pools.
//
// Returns:
// - PoolsBuilder: The instance of the PoolsBuilder for method chaining.
func (g *getPools) SearchCreatorID(creatorID int) PoolsBuilder {
g.query["search[creator_id]"] = strconv.Itoa(creatorID)
return g
}
// SearchCreatorName sets the query to search for pools created by a specific user (by their username).
//
// Parameters:
// - creatorName: The username of the user who created the pools.
//
// Returns:
// - PoolsBuilder: The instance of the PoolsBuilder for method chaining.
func (g *getPools) SearchCreatorName(creatorName string) PoolsBuilder {
g.query["search[creator_name]"] = creatorName
return g
}
// Active sets whether to search for active or inactive pools.
//
// Parameters:
// - isActive: A boolean indicating whether to search for active pools (true) or inactive pools (false).
//
// Returns:
// - PoolsBuilder: The instance of the PoolsBuilder for method chaining.
func (g *getPools) Active(isActive bool) PoolsBuilder {
g.query["search[is_active]"] = strconv.FormatBool(isActive)
return g
}
// SearchCategory sets the query to search for pools in a specific category.
//
// Parameters:
// - category: The category to search for in the pools.
//
// Returns:
// - PoolsBuilder: The instance of the PoolsBuilder for method chaining.
func (g *getPools) SearchCategory(category model.PoolCategory) PoolsBuilder {
g.query["search[category]"] = string(category)
return g
}
// Order sets the ordering of the retrieved pools.
//
// Parameters:
// - order: The order to apply to the retrieved pools.
//
// Returns:
// - PoolsBuilder: The instance of the PoolsBuilder for method chaining.
func (g *getPools) Order(order model.PoolOrder) PoolsBuilder {
g.query["search[order]"] = string(order)
return g
}
// SetLimit sets the maximum number of pools to retrieve.
//
// Parameters:
// - limitPools: The maximum number of pools to retrieve.
//
// Returns:
// - PoolsBuilder: The instance of the PoolsBuilder for method chaining.
func (g *getPools) SetLimit(limitPools int) PoolsBuilder {
g.query["limit"] = strconv.Itoa(limitPools)
return g
}
// Execute sends the constructed query and returns a slice of pools and an error, if any.
//
// Returns:
// - []model.Pool: A slice of pools.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getPools) Execute() ([]model.Pool, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
pools, err := endpoints.GetPools(g.requestContext, g.query)
if err != nil {
return nil, err
}
return pools, nil
}

View File

@ -1,48 +1,48 @@
package builder
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPools(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.Pool]("../../../tests/pools.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/pools.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getPools := NewGetPoolsBuilder(requestContext)
pools, err := getPools.SetLimit(4).Execute()
if err != nil {
t.Error(err)
return
}
if pools[0].ID == response[0].ID && pools[1].Name == response[1].Name && pools[2].UpdatedAt == response[2].UpdatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pools, response)
}
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPools(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.Pool]("../../../tests/pools.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/pools.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getPools := NewGetPoolsBuilder(requestContext)
pools, err := getPools.SetLimit(4).Execute()
if err != nil {
t.Error(err)
return
}
if pools[0].ID == response[0].ID && pools[1].Name == response[1].Name && pools[2].UpdatedAt == response[2].UpdatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pools, response)
}

View File

@ -1,47 +1,64 @@
package builder
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// PostBuilder represents a builder for constructing queries to retrieve a specific post.
type PostBuilder interface {
// SetPostID sets the post ID for the query.
SetPostID(postID model.PostID) PostBuilder
// Execute sends the constructed query and returns the requested post and an error, if any.
Execute() (*model.Post, error)
}
// NewGetPostBuilder creates a new PostBuilder with the provided RequestContext.
func NewGetPostBuilder(requestContext model.RequestContext) PostBuilder {
return &getPost{requestContext: requestContext}
}
type getPost struct {
requestContext model.RequestContext
postID model.PostID
}
// SetPostID sets the post ID for the query.
func (g *getPost) SetPostID(postID model.PostID) PostBuilder {
g.postID = postID
return g
}
// Execute sends the constructed query and returns the requested post and an error, if any.
func (g *getPost) Execute() (*model.Post, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
post, err := endpoints.GetPost(g.requestContext, strconv.Itoa(int(g.postID)))
if err != nil {
return nil, err
}
return &post, nil
}
package basic
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// PostBuilder represents a builder for constructing queries to retrieve a specific post.
type PostBuilder interface {
// SetPostID sets the post ID for the query.
SetPostID(postID model.PostID) PostBuilder
// Execute sends the constructed query and returns the requested post and an error, if any.
Execute() (*model.Post, error)
}
// NewGetPostBuilder creates a new instance of PostBuilder with the provided RequestContext.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - PostBuilder: An instance of the PostBuilder interface.
func NewGetPostBuilder(requestContext model.RequestContext) PostBuilder {
return &getPost{requestContext: requestContext}
}
// getPost is an implementation of the PostBuilder interface.
type getPost struct {
requestContext model.RequestContext
postID model.PostID
}
// SetPostID sets the post ID for the query.
//
// Parameters:
// - postID: The ID of the post to be retrieved.
//
// Returns:
// - PostBuilder: The instance of the PostBuilder for method chaining.
func (g *getPost) SetPostID(postID model.PostID) PostBuilder {
g.postID = postID
return g
}
// Execute sends the constructed query and returns the requested post and an error, if any.
//
// Returns:
// - *model.Post: The requested post.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getPost) Execute() (*model.Post, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
post, err := endpoints.GetPost(g.requestContext, strconv.Itoa(int(g.postID)))
if err != nil {
return nil, err
}
return &post, nil
}

View File

@ -1,54 +1,54 @@
package builder
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPost(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
data, err := utils.LoadJsonTestData[model.Post]("../../../tests/post.json")
if err != nil {
t.Error(err)
return
}
response := model.PostResponse{
Post: data,
Posts: nil,
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/posts/658415636580.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getPost := NewGetPostBuilder(requestContext)
post, err := getPost.SetPostID(658415636580).Execute()
if err != nil {
t.Error(err)
return
}
if post.ID == response.Post.ID && post.File.URL == response.Post.File.URL {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", post, response)
}
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPost(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
data, err := utils.LoadJsonTestData[model.Post]("../../../tests/post.json")
if err != nil {
t.Error(err)
return
}
response := model.PostResponse{
Post: data,
Posts: nil,
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/posts/658415636580.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getPost := NewGetPostBuilder(requestContext)
post, err := getPost.SetPostID(658415636580).Execute()
if err != nil {
t.Error(err)
return
}
if post.ID == response.Post.ID && post.File.URL == response.Post.File.URL {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", post, response)
}

View File

@ -1,85 +1,126 @@
package builder
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"strconv"
)
// PostsBuilder represents a builder for constructing queries to retrieve posts.
type PostsBuilder interface {
// Tags sets the query to search for posts with specific tags.
Tags(tags string) PostsBuilder
// PageAfter sets the query to retrieve posts after a specific post ID.
PageAfter(postID model.PostID) PostsBuilder
// PageBefore sets the query to retrieve posts before a specific post ID.
PageBefore(postID model.PostID) PostsBuilder
// PageNumber sets the query to retrieve posts on a specific page number.
PageNumber(number int) PostsBuilder
// SetLimit sets the maximum number of posts to retrieve.
SetLimit(limitUser int) PostsBuilder
// Execute sends the constructed query and returns a slice of posts and an error, if any.
Execute() ([]model.Post, error)
}
// NewGetPostsBuilder creates a new PostsBuilder with the provided RequestContext.
func NewGetPostsBuilder(requestContext model.RequestContext) PostsBuilder {
postBuilder := &getPosts{
requestContext: requestContext,
query: make(map[string]string),
}
return postBuilder.SetLimit(utils.E621_MAX_POST_COUNT)
}
type getPosts struct {
requestContext model.RequestContext
query map[string]string
}
// Tags sets the query to search for posts with specific tags.
func (g *getPosts) Tags(tags string) PostsBuilder {
g.query["tags"] = tags
return g
}
// PageAfter sets the query to retrieve posts after a specific post ID.
func (g *getPosts) PageAfter(postID model.PostID) PostsBuilder {
g.query["page"] = "a" + strconv.Itoa(int(postID))
return g
}
// PageBefore sets the query to retrieve posts before a specific post ID.
func (g *getPosts) PageBefore(postID model.PostID) PostsBuilder {
g.query["page"] = "b" + strconv.Itoa(int(postID))
return g
}
// PageNumber sets the query to retrieve posts on a specific page number.
func (g *getPosts) PageNumber(number int) PostsBuilder {
g.query["page"] = strconv.Itoa(number)
return g
}
// SetLimit sets the maximum number of posts to retrieve.
func (g *getPosts) SetLimit(limitUser int) PostsBuilder {
g.query["limit"] = strconv.Itoa(limitUser)
return g
}
// Execute sends the constructed query and returns a slice of posts and an error, if any.
func (g *getPosts) Execute() ([]model.Post, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
posts, err := endpoints.GetPosts(g.requestContext, g.query)
if err != nil {
return nil, err
}
return posts, err
}
package basic
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"strconv"
)
// PostsBuilder represents a builder for constructing queries to retrieve posts.
type PostsBuilder interface {
// Tags sets the query to search for posts with specific tags.
Tags(tags string) PostsBuilder
// PageAfter sets the query to retrieve posts after a specific post ID.
PageAfter(postID model.PostID) PostsBuilder
// PageBefore sets the query to retrieve posts before a specific post ID.
PageBefore(postID model.PostID) PostsBuilder
// PageNumber sets the query to retrieve posts on a specific page number.
PageNumber(number int) PostsBuilder
// SetLimit sets the maximum number of posts to retrieve.
SetLimit(limitUser int) PostsBuilder
// Execute sends the constructed query and returns a slice of posts and an error, if any.
Execute() ([]model.Post, error)
}
// NewGetPostsBuilder creates a new instance of PostsBuilder with the provided RequestContext.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - PostsBuilder: An instance of the PostsBuilder interface.
func NewGetPostsBuilder(requestContext model.RequestContext) PostsBuilder {
postBuilder := &getPosts{
requestContext: requestContext,
query: make(map[string]string),
}
return postBuilder.SetLimit(utils.E621_MAX_POST_COUNT)
}
// getPosts is an implementation of the PostsBuilder interface.
type getPosts struct {
requestContext model.RequestContext
query map[string]string
}
// Tags sets the query to search for posts with specific tags.
//
// Parameters:
// - tags: The tags to search for in the posts.
//
// Returns:
// - PostsBuilder: The instance of the PostsBuilder for method chaining.
func (g *getPosts) Tags(tags string) PostsBuilder {
g.query["tags"] = tags
return g
}
// PageAfter sets the query to retrieve posts after a specific post ID.
//
// Parameters:
// - postID: The ID of the post after which to retrieve other posts.
//
// Returns:
// - PostsBuilder: The instance of the PostsBuilder for method chaining.
func (g *getPosts) PageAfter(postID model.PostID) PostsBuilder {
g.query["page"] = "a" + strconv.Itoa(int(postID))
return g
}
// PageBefore sets the query to retrieve posts before a specific post ID.
//
// Parameters:
// - postID: The ID of the post before which to retrieve other posts.
//
// Returns:
// - PostsBuilder: The instance of the PostsBuilder for method chaining.
func (g *getPosts) PageBefore(postID model.PostID) PostsBuilder {
g.query["page"] = "b" + strconv.Itoa(int(postID))
return g
}
// PageNumber sets the query to retrieve posts on a specific page number.
//
// Parameters:
// - number: The page number to retrieve posts from.
//
// Returns:
// - PostsBuilder: The instance of the PostsBuilder for method chaining.
func (g *getPosts) PageNumber(number int) PostsBuilder {
g.query["page"] = strconv.Itoa(number)
return g
}
// SetLimit sets the maximum number of posts to retrieve.
//
// Parameters:
// - limitUser: The maximum number of posts to retrieve.
//
// Returns:
// - PostsBuilder: The instance of the PostsBuilder for method chaining.
func (g *getPosts) SetLimit(limitUser int) PostsBuilder {
g.query["limit"] = strconv.Itoa(limitUser)
return g
}
// Execute sends the constructed query and returns a slice of posts and an error, if any.
//
// Returns:
// - []model.Post: A slice of posts.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getPosts) Execute() ([]model.Post, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
posts, err := endpoints.GetPosts(g.requestContext, g.query)
if err != nil {
return nil, err
}
return posts, err
}

View File

@ -1,49 +1,49 @@
package builder
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPosts(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.PostResponse]("../../../tests/posts.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/posts.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getPosts := NewGetPostsBuilder(requestContext)
posts, err := getPosts.SetLimit(3).Execute()
if err != nil {
t.Error(err)
return
}
if posts[0].ID == response.Posts[0].ID && posts[1].File.Md5 == response.Posts[1].File.Md5 && posts[2].File.EXT == response.Posts[2].File.EXT {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", posts, response)
}
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPosts(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.PostResponse]("../../../tests/posts.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/posts.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getPosts := NewGetPostsBuilder(requestContext)
posts, err := getPosts.SetLimit(3).Execute()
if err != nil {
t.Error(err)
return
}
if posts[0].ID == response.Posts[0].ID && posts[1].File.Md5 == response.Posts[1].File.Md5 && posts[2].File.EXT == response.Posts[2].File.EXT {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", posts, response)
}

View File

@ -1,47 +1,64 @@
package builder
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// TagBuilder represents a builder for constructing queries to retrieve a specific tag.
type TagBuilder interface {
// SetTagID sets the tag ID for the query.
SetTagID(tagID int) TagBuilder
// Execute sends the constructed query and returns the requested tag and an error, if any.
Execute() (model.Tag, error)
}
// NewGetTagBuilder creates a new TagBuilder with the provided RequestContext.
func NewGetTagBuilder(requestContext model.RequestContext) TagBuilder {
return &getTag{requestContext: requestContext}
}
type getTag struct {
requestContext model.RequestContext
tagID int
}
// SetTagID sets the tag ID for the query.
func (g *getTag) SetTagID(tagID int) TagBuilder {
g.tagID = tagID
return g
}
// Execute sends the constructed query and returns the requested tag and an error, if any.
func (g *getTag) Execute() (model.Tag, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return model.Tag{}, err
}
}
tag, err := endpoints.GetTag(g.requestContext, strconv.Itoa(g.tagID))
if err != nil {
return model.Tag{}, err
}
return tag, nil
}
package basic
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// TagBuilder represents a builder for constructing queries to retrieve a specific tag.
type TagBuilder interface {
// SetTagID sets the tag ID for the query.
SetTagID(tagID int) TagBuilder
// Execute sends the constructed query and returns the requested tag and an error, if any.
Execute() (model.Tag, error)
}
// NewGetTagBuilder creates a new instance of TagBuilder with the provided RequestContext.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - TagBuilder: An instance of the TagBuilder interface.
func NewGetTagBuilder(requestContext model.RequestContext) TagBuilder {
return &getTag{requestContext: requestContext}
}
// getTag is an implementation of the TagBuilder interface.
type getTag struct {
requestContext model.RequestContext
tagID int
}
// SetTagID sets the tag ID for the query.
//
// Parameters:
// - tagID: The ID of the tag to be retrieved.
//
// Returns:
// - TagBuilder: The instance of the TagBuilder for method chaining.
func (g *getTag) SetTagID(tagID int) TagBuilder {
g.tagID = tagID
return g
}
// Execute sends the constructed query and returns the requested tag and an error, if any.
//
// Returns:
// - model.Tag: The requested tag.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getTag) Execute() (model.Tag, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return model.Tag{}, err
}
}
tag, err := endpoints.GetTag(g.requestContext, strconv.Itoa(g.tagID))
if err != nil {
return model.Tag{}, err
}
return tag, nil
}

View File

@ -1,49 +1,49 @@
package builder
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetTag(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Tag]("../../../tests/tag.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/tags/165165.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getTag := NewGetTagBuilder(requestContext)
tag, err := getTag.SetTagID(165165).Execute()
if err != nil {
t.Error(err)
return
}
if tag.ID == response.ID && tag.Name == response.Name && tag.CreatedAt == response.CreatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", tag, response)
}
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetTag(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Tag]("../../../tests/tag.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/tags/165165.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getTag := NewGetTagBuilder(requestContext)
tag, err := getTag.SetTagID(165165).Execute()
if err != nil {
t.Error(err)
return
}
if tag.ID == response.ID && tag.Name == response.Name && tag.CreatedAt == response.CreatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", tag, response)
}

View File

@ -1,103 +1,162 @@
package builder
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// TagsBuilder represents a builder for constructing queries to retrieve tags.
type TagsBuilder interface {
// SearchName sets the query to search for tags with specific names.
SearchName(name string) TagsBuilder
// SearchCategory sets the query to search for tags in a specific category.
SearchCategory(category model.TagCategory) TagsBuilder
// Order sets the query to order tags by a specific criterion.
Order(order string) TagsBuilder
// HideEmpty sets the query to filter out tags that are empty.
HideEmpty(hideEmpty bool) TagsBuilder
// Wiki sets the query to filter tags that have a wiki.
Wiki(hasWiki bool) TagsBuilder
// Artist sets the query to filter tags that have an artist page.
Artist(hasArtistPage bool) TagsBuilder
// SetPage sets the query to retrieve tags from a specific page number.
SetPage(pageNumber int) TagsBuilder
// SetLimit sets the maximum number of tags to retrieve.
SetLimit(limitUser int) TagsBuilder
// Execute sends the constructed query and returns a slice of tags and an error, if any.
Execute() ([]model.Tag, error)
}
// NewGetTagsBuilder creates a new TagsBuilder with the provided RequestContext.
func NewGetTagsBuilder(requestContext model.RequestContext) TagsBuilder {
return &getTags{requestContext: requestContext, query: make(map[string]string)}
}
type getTags struct {
requestContext model.RequestContext
query map[string]string
}
// SearchName sets the query to search for tags with specific names.
func (g *getTags) SearchName(name string) TagsBuilder {
g.query["search[name_matches]"] = name
return g
}
// SearchCategory sets the query to search for tags in a specific category.
func (g *getTags) SearchCategory(category model.TagCategory) TagsBuilder {
g.query["search[category]"] = strconv.Itoa(int(category))
return g
}
// Order sets the query to order tags by a specific criterion.
func (g *getTags) Order(order string) TagsBuilder {
g.query["search[order]"] = order
return g
}
// HideEmpty sets the query to filter out tags that are empty.
func (g *getTags) HideEmpty(hideEmpty bool) TagsBuilder {
g.query["search[hide_empty]"] = strconv.FormatBool(hideEmpty)
return g
}
// Wiki sets the query to filter tags that have a wiki.
func (g *getTags) Wiki(hasWiki bool) TagsBuilder {
g.query["search[has_wiki]"] = strconv.FormatBool(hasWiki)
return g
}
// Artist sets the query to filter tags that have an artist page.
func (g *getTags) Artist(hasArtistPage bool) TagsBuilder {
g.query["search[has_artist]"] = strconv.FormatBool(hasArtistPage)
return g
}
// SetPage sets the query to retrieve tags from a specific page number.
func (g *getTags) SetPage(pageNumber int) TagsBuilder {
g.query["page"] = strconv.Itoa(pageNumber)
return g
}
// SetLimit sets the maximum number of tags to retrieve.
func (g *getTags) SetLimit(limitUser int) TagsBuilder {
g.query["limit"] = strconv.Itoa(limitUser)
return g
}
// Execute sends the constructed query and returns a slice of tags and an error, if any.
func (g *getTags) Execute() ([]model.Tag, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
tags, err := endpoints.GetTags(g.requestContext, g.query)
if err != nil {
return nil, err
}
return tags, err
}
package basic
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// TagsBuilder represents a builder for constructing queries to retrieve tags.
type TagsBuilder interface {
// SearchName sets the query to search for tags with specific names.
SearchName(name string) TagsBuilder
// SearchCategory sets the query to search for tags in a specific category.
SearchCategory(category model.TagCategory) TagsBuilder
// Order sets the query to order tags by a specific criterion.
Order(order string) TagsBuilder
// HideEmpty sets the query to filter out tags that are empty.
HideEmpty(hideEmpty bool) TagsBuilder
// Wiki sets the query to filter tags that have a wiki.
Wiki(hasWiki bool) TagsBuilder
// Artist sets the query to filter tags that have an artist page.
Artist(hasArtistPage bool) TagsBuilder
// SetPage sets the query to retrieve tags from a specific page number.
SetPage(pageNumber int) TagsBuilder
// SetLimit sets the maximum number of tags to retrieve.
SetLimit(limitUser int) TagsBuilder
// Execute sends the constructed query and returns a slice of tags and an error, if any.
Execute() ([]model.Tag, error)
}
// NewGetTagsBuilder creates a new instance of TagsBuilder with the provided RequestContext.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - TagsBuilder: An instance of the TagsBuilder interface.
func NewGetTagsBuilder(requestContext model.RequestContext) TagsBuilder {
return &getTags{requestContext: requestContext, query: make(map[string]string)}
}
// getTags is an implementation of the TagsBuilder interface.
type getTags struct {
requestContext model.RequestContext
query map[string]string
}
// SearchName sets the query to search for tags with specific names.
//
// Parameters:
// - name: The name to search for.
//
// Returns:
// - TagsBuilder: The instance of the TagsBuilder for method chaining.
func (g *getTags) SearchName(name string) TagsBuilder {
g.query["search[name_matches]"] = name
return g
}
// SearchCategory sets the query to search for tags in a specific category.
//
// Parameters:
// - category: The category of tags to search for.
//
// Returns:
// - TagsBuilder: The instance of the TagsBuilder for method chaining.
func (g *getTags) SearchCategory(category model.TagCategory) TagsBuilder {
g.query["search[category]"] = strconv.Itoa(int(category))
return g
}
// Order sets the query to order tags by a specific criterion.
//
// Parameters:
// - order: The criterion to order tags by.
//
// Returns:
// - TagsBuilder: The instance of the TagsBuilder for method chaining.
func (g *getTags) Order(order string) TagsBuilder {
g.query["search[order]"] = order
return g
}
// HideEmpty sets the query to filter out tags that are empty.
//
// Parameters:
// - hideEmpty: A boolean indicating whether to filter out empty tags.
//
// Returns:
// - TagsBuilder: The instance of the TagsBuilder for method chaining.
func (g *getTags) HideEmpty(hideEmpty bool) TagsBuilder {
g.query["search[hide_empty]"] = strconv.FormatBool(hideEmpty)
return g
}
// Wiki sets the query to filter tags that have a wiki.
//
// Parameters:
// - hasWiki: A boolean indicating whether to filter tags with a wiki.
//
// Returns:
// - TagsBuilder: The instance of the TagsBuilder for method chaining.
func (g *getTags) Wiki(hasWiki bool) TagsBuilder {
g.query["search[has_wiki]"] = strconv.FormatBool(hasWiki)
return g
}
// Artist sets the query to filter tags that have an artist page.
//
// Parameters:
// - hasArtistPage: A boolean indicating whether to filter tags with an artist page.
//
// Returns:
// - TagsBuilder: The instance of the TagsBuilder for method chaining.
func (g *getTags) Artist(hasArtistPage bool) TagsBuilder {
g.query["search[has_artist]"] = strconv.FormatBool(hasArtistPage)
return g
}
// SetPage sets the query to retrieve tags from a specific page number.
//
// Parameters:
// - pageNumber: The page number to retrieve tags from.
//
// Returns:
// - TagsBuilder: The instance of the TagsBuilder for method chaining.
func (g *getTags) SetPage(pageNumber int) TagsBuilder {
g.query["page"] = strconv.Itoa(pageNumber)
return g
}
// SetLimit sets the maximum number of tags to retrieve.
//
// Parameters:
// - limitUser: The maximum number of tags to retrieve.
//
// Returns:
// - TagsBuilder: The instance of the TagsBuilder for method chaining.
func (g *getTags) SetLimit(limitUser int) TagsBuilder {
g.query["limit"] = strconv.Itoa(limitUser)
return g
}
// Execute sends the constructed query and returns a slice of tags and an error, if any.
//
// Returns:
// - []model.Tag: A slice of tags.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getTags) Execute() ([]model.Tag, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
tags, err := endpoints.GetTags(g.requestContext, g.query)
if err != nil {
return nil, err
}
return tags, err
}

View File

@ -1,46 +1,63 @@
package builder
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
)
// UserBuilder represents a builder for constructing queries to retrieve user information.
type UserBuilder interface {
// SetUsername sets the username for the query to retrieve user information.
SetUsername(username string) UserBuilder
// Execute sends the constructed query and returns the requested user information and an error, if any.
Execute() (model.User, error)
}
// NewGetUserBuilder creates a new UserBuilder with the provided RequestContext.
func NewGetUserBuilder(requestContext model.RequestContext) UserBuilder {
return &getUser{requestContext: requestContext}
}
type getUser struct {
requestContext model.RequestContext
username string
}
// SetUsername sets the username for the query to retrieve user information.
func (g *getUser) SetUsername(username string) UserBuilder {
g.username = username
return g
}
// Execute sends the constructed query and returns the requested user information and an error, if any.
func (g *getUser) Execute() (model.User, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return model.User{}, err
}
}
user, err := endpoints.GetUser(g.requestContext, g.username)
if err != nil {
return model.User{}, err
}
return user, nil
}
package basic
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
)
// UserBuilder represents a builder for constructing queries to retrieve user information.
type UserBuilder interface {
// SetUsername sets the username for the query to retrieve user information.
SetUsername(username string) UserBuilder
// Execute sends the constructed query and returns the requested user information and an error, if any.
Execute() (model.User, error)
}
// NewGetUserBuilder creates a new instance of UserBuilder with the provided RequestContext.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - UserBuilder: An instance of the UserBuilder interface.
func NewGetUserBuilder(requestContext model.RequestContext) UserBuilder {
return &getUser{requestContext: requestContext}
}
// getUser is an implementation of the UserBuilder interface.
type getUser struct {
requestContext model.RequestContext
username string
}
// SetUsername sets the username for the query to retrieve user information.
//
// Parameters:
// - username: The username to retrieve information for.
//
// Returns:
// - UserBuilder: The instance of the UserBuilder for method chaining.
func (g *getUser) SetUsername(username string) UserBuilder {
g.username = username
return g
}
// Execute sends the constructed query and returns the requested user information and an error, if any.
//
// Returns:
// - model.User: The user information.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getUser) Execute() (model.User, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return model.User{}, err
}
}
user, err := endpoints.GetUser(g.requestContext, g.username)
if err != nil {
return model.User{}, err
}
return user, nil
}

View File

@ -1,49 +1,49 @@
package builder
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetUser(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.User]("../../../tests/user.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/users/MaxMustermannDer69ste.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
GetUser := NewGetUserBuilder(requestContext)
user, err := GetUser.SetUsername("MaxMustermannDer69ste").Execute()
if err != nil {
t.Error(err)
return
}
if user.ID == response.ID && user.Name == response.Name && user.CreatedAt == response.CreatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", user, response)
}
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetUser(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.User]("../../../tests/user.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/users/MaxMustermannDer69ste.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
GetUser := NewGetUserBuilder(requestContext)
user, err := GetUser.SetUsername("MaxMustermannDer69ste").Execute()
if err != nil {
t.Error(err)
return
}
if user.ID == response.ID && user.Name == response.Name && user.CreatedAt == response.CreatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", user, response)
}

View File

@ -1,127 +1,204 @@
package builder
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// UsersBuilder represents a builder for constructing queries to retrieve user information.
type UsersBuilder interface {
// SetPage sets the page number for paginated results.
SetPage(pageNumber int) UsersBuilder
// SetLimit sets the maximum number of users to retrieve.
SetLimit(limitUser int) UsersBuilder
// SearchByName specifies a username to search for.
SearchByName(userName string) UsersBuilder
// SearchByAbout specifies a text to search in the 'about' field of user profiles.
SearchByAbout(about string) UsersBuilder
// SearchByAvatarID specifies an avatar ID to search for.
SearchByAvatarID(avatarID model.PostID) UsersBuilder
// SearchByLevel specifies a user level to filter by.
SearchByLevel(level model.UserLevel) UsersBuilder
// SearchByMinLevel specifies the minimum user level to filter by.
SearchByMinLevel(minLevel model.UserLevel) UsersBuilder
// SearchByMaxLevel specifies the maximum user level to filter by.
SearchByMaxLevel(maxLevel model.UserLevel) UsersBuilder
// SearchByCanUpload specifies whether users can upload free content.
SearchByCanUpload(canUpload bool) UsersBuilder
// SearchByIsApprover specifies whether users can approve posts.
SearchByIsApprover(isApprover bool) UsersBuilder
// SearchByOrder specifies the order in which users are retrieved.
SearchByOrder(order model.Order) UsersBuilder
// Execute sends the constructed query and returns the requested user information and an error, if any.
Execute() ([]model.User, error)
}
// NewGetUsersBuilder creates a new UsersBuilder with the provided RequestContext.
func NewGetUsersBuilder(requestContext model.RequestContext) UsersBuilder {
return &getUsers{requestContext: requestContext, query: make(map[string]string)}
}
type getUsers struct {
requestContext model.RequestContext
query map[string]string
}
// SearchByName specifies a username to search for.
func (g *getUsers) SearchByName(userName string) UsersBuilder {
g.query["search[name_matches]"] = userName
return g
}
// SearchByAbout specifies a text to search in the 'about' field of user profiles.
func (g *getUsers) SearchByAbout(about string) UsersBuilder {
g.query["search[about_me]"] = about
return g
}
// SearchByAvatarID specifies an avatar ID to search for.
func (g *getUsers) SearchByAvatarID(avatarID model.PostID) UsersBuilder {
g.query["search[avatar_id]"] = strconv.FormatInt(int64(avatarID), 10)
return g
}
// SearchByLevel specifies a user level to filter by.
func (g *getUsers) SearchByLevel(level model.UserLevel) UsersBuilder {
g.query["search[level]"] = strconv.Itoa(int(level))
return g
}
// SearchByMinLevel specifies the minimum user level to filter by.
func (g *getUsers) SearchByMinLevel(minLevel model.UserLevel) UsersBuilder {
g.query["search[min_level]"] = strconv.Itoa(int(minLevel))
return g
}
// SearchByMaxLevel specifies the maximum user level to filter by.
func (g *getUsers) SearchByMaxLevel(maxLevel model.UserLevel) UsersBuilder {
g.query["search[max_level]"] = strconv.Itoa(int(maxLevel))
return g
}
// SearchByCanUpload specifies whether users can upload free content.
func (g *getUsers) SearchByCanUpload(canUpload bool) UsersBuilder {
g.query["search[can_upload_free]"] = strconv.FormatBool(canUpload)
return g
}
// SearchByIsApprover specifies whether users can approve posts.
func (g *getUsers) SearchByIsApprover(isApprover bool) UsersBuilder {
g.query["search[can_approve_posts]"] = strconv.FormatBool(isApprover)
return g
}
// SearchByOrder specifies the order in which users are retrieved.
func (g *getUsers) SearchByOrder(order model.Order) UsersBuilder {
g.query["search[order]"] = string(order)
return g
}
// SetPage sets the page number for paginated results.
func (g *getUsers) SetPage(pageNumber int) UsersBuilder {
g.query["page"] = strconv.Itoa(pageNumber)
return g
}
// SetLimit sets the maximum number of users to retrieve.
func (g *getUsers) SetLimit(limitUser int) UsersBuilder {
g.query["limit"] = strconv.Itoa(limitUser)
return g
}
// Execute sends the constructed query and returns the requested user information and an error, if any.
func (g *getUsers) Execute() ([]model.User, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
users, err := endpoints.GetUsers(g.requestContext, g.query)
if err != nil {
return nil, err
}
return users, nil
}
package basic
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// UsersBuilder represents a builder for constructing queries to retrieve user information.
type UsersBuilder interface {
// SetPage sets the page number for paginated results.
SetPage(pageNumber int) UsersBuilder
// SetLimit sets the maximum number of users to retrieve.
SetLimit(limitUser int) UsersBuilder
// SearchByName specifies a username to search for.
SearchByName(userName string) UsersBuilder
// SearchByAbout specifies a text to search in the 'about' field of user profiles.
SearchByAbout(about string) UsersBuilder
// SearchByAvatarID specifies an avatar ID to search for.
SearchByAvatarID(avatarID model.PostID) UsersBuilder
// SearchByLevel specifies a user level to filter by.
SearchByLevel(level model.UserLevel) UsersBuilder
// SearchByMinLevel specifies the minimum user level to filter by.
SearchByMinLevel(minLevel model.UserLevel) UsersBuilder
// SearchByMaxLevel specifies the maximum user level to filter by.
SearchByMaxLevel(maxLevel model.UserLevel) UsersBuilder
// SearchByCanUpload specifies whether users can upload free content.
SearchByCanUpload(canUpload bool) UsersBuilder
// SearchByIsApprover specifies whether users can approve posts.
SearchByIsApprover(isApprover bool) UsersBuilder
// SearchByOrder specifies the order in which users are retrieved.
SearchByOrder(order model.Order) UsersBuilder
// Execute sends the constructed query and returns the requested user information and an error, if any.
Execute() ([]model.User, error)
}
// NewGetUsersBuilder creates a new UsersBuilder with the provided RequestContext.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - UsersBuilder: An instance of the UsersBuilder interface.
func NewGetUsersBuilder(requestContext model.RequestContext) UsersBuilder {
return &getUsers{requestContext: requestContext, query: make(map[string]string)}
}
// getUsers is an implementation of the UsersBuilder interface.
type getUsers struct {
requestContext model.RequestContext
query map[string]string
}
// SearchByName specifies a username to search for.
//
// Parameters:
// - userName: The username to search for.
//
// Returns:
// - UsersBuilder: The instance of the UsersBuilder for method chaining.
func (g *getUsers) SearchByName(userName string) UsersBuilder {
g.query["search[name_matches]"] = userName
return g
}
// SearchByAbout specifies a text to search in the 'about' field of user profiles.
//
// Parameters:
// - about: The text to search for in the 'about' field of user profiles.
//
// Returns:
// - UsersBuilder: The instance of the UsersBuilder for method chaining.
func (g *getUsers) SearchByAbout(about string) UsersBuilder {
g.query["search[about_me]"] = about
return g
}
// SearchByAvatarID specifies an avatar ID to search for.
//
// Parameters:
// - avatarID: The avatar ID to search for.
//
// Returns:
// - UsersBuilder: The instance of the UsersBuilder for method chaining.
func (g *getUsers) SearchByAvatarID(avatarID model.PostID) UsersBuilder {
g.query["search[avatar_id]"] = strconv.FormatInt(int64(avatarID), 10)
return g
}
// SearchByLevel specifies a user level to filter by.
//
// Parameters:
// - level: The user level to filter by.
//
// Returns:
// - UsersBuilder: The instance of the UsersBuilder for method chaining.
func (g *getUsers) SearchByLevel(level model.UserLevel) UsersBuilder {
g.query["search[level]"] = strconv.Itoa(int(level))
return g
}
// SearchByMinLevel specifies the minimum user level to filter by.
//
// Parameters:
// - minLevel: The minimum user level to filter by.
//
// Returns:
// - UsersBuilder: The instance of the UsersBuilder for method chaining.
func (g *getUsers) SearchByMinLevel(minLevel model.UserLevel) UsersBuilder {
g.query["search[min_level]"] = strconv.Itoa(int(minLevel))
return g
}
// SearchByMaxLevel specifies the maximum user level to filter by.
//
// Parameters:
// - maxLevel: The maximum user level to filter by.
//
// Returns:
// - UsersBuilder: The instance of the UsersBuilder for method chaining.
func (g *getUsers) SearchByMaxLevel(maxLevel model.UserLevel) UsersBuilder {
g.query["search[max_level]"] = strconv.Itoa(int(maxLevel))
return g
}
// SearchByCanUpload specifies whether users can upload free content.
//
// Parameters:
// - canUpload: Whether users can upload free content.
//
// Returns:
// - UsersBuilder: The instance of the UsersBuilder for method chaining.
func (g *getUsers) SearchByCanUpload(canUpload bool) UsersBuilder {
g.query["search[can_upload_free]"] = strconv.FormatBool(canUpload)
return g
}
// SearchByIsApprover specifies whether users can approve posts.
//
// Parameters:
// - isApprover: Whether users can approve posts.
//
// Returns:
// - UsersBuilder: The instance of the UsersBuilder for method chaining.
func (g *getUsers) SearchByIsApprover(isApprover bool) UsersBuilder {
g.query["search[can_approve_posts]"] = strconv.FormatBool(isApprover)
return g
}
// SearchByOrder specifies the order in which users are retrieved.
//
// Parameters:
// - order: The order in which users are retrieved.
//
// Returns:
// - UsersBuilder: The instance of the UsersBuilder for method chaining.
func (g *getUsers) SearchByOrder(order model.Order) UsersBuilder {
g.query["search[order]"] = string(order)
return g
}
// SetPage sets the page number for paginated results.
//
// Parameters:
// - pageNumber: The page number for paginated results.
//
// Returns:
// - UsersBuilder: The instance of the UsersBuilder for method chaining.
func (g *getUsers) SetPage(pageNumber int) UsersBuilder {
g.query["page"] = strconv.Itoa(pageNumber)
return g
}
// SetLimit sets the maximum number of users to retrieve.
//
// Parameters:
// - limitUser: The maximum number of users to retrieve.
//
// Returns:
// - UsersBuilder: The instance of the UsersBuilder for method chaining.
func (g *getUsers) SetLimit(limitUser int) UsersBuilder {
g.query["limit"] = strconv.Itoa(limitUser)
return g
}
// Execute sends the constructed query and returns the requested user information and an error, if any.
//
// Returns:
// - []model.User: A slice of user information.
// - error: An error, if any, encountered during the API request or response handling.
func (g *getUsers) Execute() ([]model.User, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
users, err := endpoints.GetUsers(g.requestContext, g.query)
if err != nil {
return nil, err
}
return users, nil
}

View File

@ -1,49 +1,49 @@
package builder
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetUsers(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.User]("../../../tests/users.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/users.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getUsers := NewGetUsersBuilder(requestContext)
user, err := getUsers.Execute()
if err != nil {
t.Error(err)
return
}
if user[0].ID == response[0].ID && user[1].Name == response[1].Name {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", user, response)
}
package basic
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetUsers(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.User]("../../../tests/users.json")
if err != nil {
t.Error(err)
return
}
responser, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/users.json", responser)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
getUsers := NewGetUsersBuilder(requestContext)
user, err := getUsers.Execute()
if err != nil {
t.Error(err)
return
}
if user[0].ID == response[0].ID && user[1].Name == response[1].Name {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", user, response)
}

View File

@ -1,79 +0,0 @@
package builder
import (
"context"
"strconv"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
)
type DMailsBuilder interface {
ByTitle(title string) DMailsBuilder
ByBody(body string) DMailsBuilder
ByToName(toName string) DMailsBuilder
ByFromName(fromName string) DMailsBuilder
SetLimit(limit int) DMailsBuilder
PageNumber(number int) DMailsBuilder
Execute() ([]model.DMail, error)
}
type getDMails struct {
requestContext model.RequestContext
query map[string]string
id int
}
func NewGetDMailsBuilder(requestContext model.RequestContext) DMailsBuilder {
dMailsBuilder := &getDMails{
requestContext: requestContext,
query: make(map[string]string),
}
return dMailsBuilder.SetLimit(utils.E621_MAX_POST_COUNT)
}
func (g getDMails) ByTitle(title string) DMailsBuilder {
g.query["search[title_matches]"] = title
return g
}
func (g getDMails) ByBody(body string) DMailsBuilder {
g.query["search[message_matches]"] = body
return g
}
func (g getDMails) ByToName(toName string) DMailsBuilder {
g.query["search[to_name]"] = toName
return g
}
func (g getDMails) ByFromName(fromName string) DMailsBuilder {
g.query["search[from_name]"] = fromName
return g
}
func (g getDMails) SetLimit(limit int) DMailsBuilder {
g.query["limit"] = strconv.Itoa(limit)
return g
}
func (g getDMails) PageNumber(number int) DMailsBuilder {
g.query["page"] = strconv.Itoa(number)
return g
}
func (g getDMails) Execute() ([]model.DMail, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
favorites, err := endpoints.GetAllDmails(g.requestContext, g.query)
if err != nil {
return nil, err
}
return favorites, nil
}

View File

@ -1,66 +1,132 @@
package builder
import (
"context"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/endpoints"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strconv"
)
// FavoritesBuilder represents a builder for constructing queries to retrieve user's favorite posts.
type FavoritesBuilder interface {
// SetUserID sets the user ID for the query.
SetUserID(userID model.UserID) FavoritesBuilder
// SetLimit sets the maximum number of favorite posts to retrieve.
SetLimit(limitFavorites int) FavoritesBuilder
// Page sets the page number for paginated results.
Page(pageNumber int) FavoritesBuilder
// Execute sends the constructed query and returns a slice of favorite posts and an error if any.
Execute() ([]model.Post, error)
}
// NewGetFavoritesBuilder creates a new FavoritesBuilder with the provided RequestContext.
func NewGetFavoritesBuilder(requestContext model.RequestContext) FavoritesBuilder {
return &getFavorites{
requestContext: requestContext,
query: make(map[string]string),
}
}
type getFavorites struct {
query map[string]string
requestContext model.RequestContext
}
// SetUserID sets the user ID for the query.
func (g *getFavorites) SetUserID(userID model.UserID) FavoritesBuilder {
g.query["user_id"] = strconv.Itoa(int(userID))
return g
}
// SetLimit sets the maximum number of favorite posts to retrieve.
func (g *getFavorites) SetLimit(limitFavorites int) FavoritesBuilder {
g.query["limit"] = strconv.Itoa(limitFavorites)
return g
}
// Page sets the page number for paginated results.
func (g *getFavorites) Page(pageNumber int) FavoritesBuilder {
g.query["page"] = strconv.Itoa(pageNumber)
return g
}
// Execute sends the constructed query and returns a slice of favorite posts and an error if any.
func (g *getFavorites) Execute() ([]model.Post, error) {
if g.requestContext.RateLimiter != nil {
err := g.requestContext.RateLimiter.Wait(context.Background())
if err != nil {
return nil, err
}
}
favorites, err := endpoints.GetFavorites(g.requestContext, g.query)
if err != nil {
return nil, err
}
return favorites, nil
}
package builder
import (
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder/basic"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"strings"
)
type FavoritesBuilder interface {
FromUsername(username string) FavoritesBuilder
FromUserID(userID model.UserID) FavoritesBuilder
WithTags(tags []string) FavoritesBuilder
Limit(amount int) FavoritesBuilder
Execute() ([]model.Post, error)
}
func NewGetFavoritesBuilder(requestContext model.RequestContext) FavoritesBuilder {
return &getFavorites{
requestContext: requestContext,
}
}
type getFavorites struct {
requestContext model.RequestContext
user model.User
tags string
limit int
error error
}
func (g *getFavorites) FromUsername(username string) FavoritesBuilder {
user := model.User{Name: username}
g.user = user
return g
}
func (g *getFavorites) FromUserID(userID model.UserID) FavoritesBuilder {
user := model.User{ID: userID}
g.user = user
return g
}
func (g *getFavorites) WithTags(tagList []string) FavoritesBuilder {
tags := strings.Join(tagList, ",")
g.tags = tags
return g
}
func (g *getFavorites) Limit(amount int) FavoritesBuilder {
g.limit = amount
return g
}
func (g getFavorites) Execute() ([]model.Post, error) {
var err error
basicFavoritesBuilder := basic.NewGetFavoritesBuilder(g.requestContext)
var userFavorites []model.Post
if g.user.ID == 0 && g.user.Name == "" {
return nil, fmt.Errorf("no UserID or UserName given")
}
if g.user.Name != "" {
g.user, err = basic.NewGetUserBuilder(g.requestContext).SetUsername(g.user.Name).Execute()
if err != nil {
return nil, err
}
}
if g.user.ID != 0 {
basicFavoritesBuilder.SetUserID(g.user.ID)
}
if g.limit != 0 {
basicFavoritesBuilder.SetLimit(g.limit)
}
if g.tags == "" {
userFavorites, err = basicFavoritesBuilder.Execute()
}
if g.tags != "" {
// TODO: implement with tags (channels)
} else {
return basicFavoritesBuilder.Execute()
}
return userFavorites, err
}
/*
// GetNFavoritesForUser retrieves a specified number of favorites for a user.
func (c *CLient) GetNFavoritesForUser(n int, favoriteBuilder basic.FavoritesBuilder) ([]model.Post, error) {
// Retrieves a specified number of favorite posts for a user.
if n < utils.E621_MAX_POST_COUNT {
favoriteBuilder.SetLimit(n)
}
var favorites []model.Post
var page = 1
for len(favorites) < n {
favoriteBuilder.Page(page)
favoriteBuilder.SetLimit(n - len(favorites))
newFavorites, err := favoriteBuilder.Execute()
if err != nil {
return nil, err
}
if len(newFavorites) == 0 {
break
}
favorites = append(favorites, newFavorites...)
page = page + 1
}
return favorites, nil
}
// GetAllFavoritesForUser retrieves all favorites for a user.
func (c *Client) GetAllFavoritesForUser(favoriteBuilder basic.FavoritesBuilder) ([]model.Post, error) {
// Retrieves all favorite posts for a user.
return c.GetNFavoritesForUser(math.MaxInt, favoriteBuilder)
}
// GetFavoritesForUserWithTags returns a posts builder for a user's favorites with specific tags.
func (c *Client) GetFavoritesForUserWithTags(username string, tags string) basic.PostsBuilder {
// Returns a posts builder for a user's favorites with specific tags.
favoritesBuilder := basic.NewGetPostsBuilder(c.RequestContext).Tags(fmt.Sprintf("fav:%s %s", username, tags))
return favoritesBuilder
}
*/

View File

@ -1,244 +1,372 @@
package e621
import (
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
_ "github.com/joho/godotenv/autoload"
"golang.org/x/time/rate"
"math"
"net/http"
"strconv"
)
// Client is the main client for interacting with the e621 API.
type Client struct {
RequestContext model.RequestContext
}
// NewClient creates a new e621 client with the provided username and API key.
func NewClient(username string, apiKey string) Client {
// Create a new e621 client with the given username and API key.
return Client{
RequestContext: model.RequestContext{
Client: http.Client{},
RateLimiter: rate.NewLimiter(1, 2),
Host: "https://e621.net",
UserAgent: fmt.Sprintf("Go-e621-SDK used by %s | (made by the Anthrove Team)", username),
Username: username,
APIKey: apiKey,
},
}
}
// GetUserBuilder returns a UserBuilder instance for creating and executing requests to retrieve user information from the e621 API.
//
// Returns:
// - builder.UserBuilder: An instance of the UserBuilder.
func (c *Client) GetUserBuilder() builder.UserBuilder {
return builder.NewGetUserBuilder(c.RequestContext)
}
// GetUsersBuilder returns a UsersBuilder instance for creating and executing requests to retrieve multiple users' information from the e621 API.
//
// Returns:
// - builder.UsersBuilder: An instance of the UsersBuilder.
func (c *Client) GetUsersBuilder() builder.UsersBuilder {
return builder.NewGetUsersBuilder(c.RequestContext)
}
// GetFavoritesBuilder returns a FavoritesBuilder instance for creating and executing requests to retrieve a user's favorite posts from the e621 API.
//
// Returns:
// - builder.FavoritesBuilder: An instance of the FavoritesBuilder.
func (c *Client) GetFavoritesBuilder() builder.FavoritesBuilder {
return builder.NewGetFavoritesBuilder(c.RequestContext)
}
// GetPostBuilder returns a PostBuilder instance for creating and executing requests to retrieve post information from the e621 API.
//
// Returns:
// - builder.PostBuilder: An instance of the PostBuilder.
func (c *Client) GetPostBuilder() builder.PostBuilder {
return builder.NewGetPostBuilder(c.RequestContext)
}
// GetPostsBuilder returns a PostsBuilder instance for creating and executing requests to retrieve multiple posts' information from the e621 API.
//
// Returns:
// - builder.PostsBuilder: An instance of the PostsBuilder.
func (c *Client) GetPostsBuilder() builder.PostsBuilder {
return builder.NewGetPostsBuilder(c.RequestContext)
}
// GetNoteBuilder returns a NoteBuilder instance for creating and executing requests to retrieve note information from the e621 API.
//
// Returns:
// - builder.NoteBuilder: An instance of the NoteBuilder.
func (c *Client) GetNoteBuilder() builder.NoteBuilder {
return builder.NewGetNoteBuilder(c.RequestContext)
}
// GetNotesBuilder returns a NotesBuilder instance for creating and executing requests to retrieve multiple notes' information from the e621 API.
//
// Returns:
// - builder.NotesBuilder: An instance of the NotesBuilder.
func (c *Client) GetNotesBuilder() builder.NotesBuilder {
return builder.NewGetNotesBuilder(c.RequestContext)
}
// GetPoolBuilder returns a PoolBuilder instance for creating and executing requests to retrieve pool information from the e621 API.
//
// Returns:
// - builder.PoolBuilder: An instance of the PoolBuilder.
func (c *Client) GetPoolBuilder() builder.PoolBuilder {
return builder.NewGetPoolBuilder(c.RequestContext)
}
// GetPoolsBuilder returns a PoolsBuilder instance for creating and executing requests to retrieve multiple pools' information from the e621 API.
//
// Returns:
// - builder.PoolsBuilder: An instance of the PoolsBuilder.
func (c *Client) GetPoolsBuilder() builder.PoolsBuilder {
return builder.NewGetPoolsBuilder(c.RequestContext)
}
// GetTagBuilder returns a TagBuilder instance for creating and executing requests to retrieve tag information from the e621 API.
//
// Returns:
// - builder.TagBuilder: An instance of the TagBuilder.
func (c *Client) GetTagBuilder() builder.TagBuilder {
return builder.NewGetTagBuilder(c.RequestContext)
}
// GetTagsBuilder returns a TagsBuilder instance for creating and executing requests to retrieve multiple tags' information from the e621 API.
//
// Returns:
// - builder.TagsBuilder: An instance of the TagsBuilder.
func (c *Client) GetTagsBuilder() builder.TagsBuilder {
return builder.NewGetTagsBuilder(c.RequestContext)
}
// SetHost sets the API host for the client.
func (c *Client) SetHost(host string) *Client {
// Set the API host for the client.
c.RequestContext.Host = host
return c
}
// SetAgentName sets the user agent name for the client.
func (c *Client) SetAgentName(userAgent string) *Client {
// Set the user agent name for the client.
c.RequestContext.UserAgent = userAgent
return c
}
// GetUserByName returns a user builder for a given username.
func (c *Client) GetUserByName(username string) builder.UserBuilder {
// Returns a user builder for the specified username.
return builder.NewGetUserBuilder(c.RequestContext).SetUsername(username)
}
// GetUserByID returns a user builder for a given user ID.
func (c *Client) GetUserByID(userID model.UserID) builder.UserBuilder {
// Returns a user builder for the specified user ID.
return builder.NewGetUserBuilder(c.RequestContext).SetUsername(strconv.FormatInt(int64(userID), 10))
}
// GetFavoritesForUser returns a favorites builder for a given username.
func (c *Client) GetFavoritesForUser(username string) (builder.FavoritesBuilder, error) {
// Returns a favorites builder for the specified username.
user, err := builder.NewGetUserBuilder(c.RequestContext).SetUsername(username).Execute()
if err != nil {
return nil, err
}
favoritesBuilder := builder.NewGetFavoritesBuilder(c.RequestContext).SetUserID(user.ID)
return favoritesBuilder, nil
}
// GetNFavoritesForUser retrieves a specified number of favorites for a user.
func (c *Client) GetNFavoritesForUser(n int, favoriteBuilder builder.FavoritesBuilder) ([]model.Post, error) {
// Retrieves a specified number of favorite posts for a user.
if n < utils.E621_MAX_POST_COUNT {
favoriteBuilder.SetLimit(n)
}
var favorites []model.Post
var page = 1
for len(favorites) < n {
favoriteBuilder.Page(page)
favoriteBuilder.SetLimit(n - len(favorites))
newFavorites, err := favoriteBuilder.Execute()
if err != nil {
return nil, err
}
if len(newFavorites) == 0 {
break
}
favorites = append(favorites, newFavorites...)
page = page + 1
}
return favorites, nil
}
// GetAllFavoritesForUser retrieves all favorites for a user.
func (c *Client) GetAllFavoritesForUser(favoriteBuilder builder.FavoritesBuilder) ([]model.Post, error) {
// Retrieves all favorite posts for a user.
return c.GetNFavoritesForUser(math.MaxInt, favoriteBuilder)
}
// GetFavoritesForUserWithTags returns a posts builder for a user's favorites with specific tags.
func (c *Client) GetFavoritesForUserWithTags(username string, tags string) builder.PostsBuilder {
// Returns a posts builder for a user's favorites with specific tags.
favoritesBuilder := builder.NewGetPostsBuilder(c.RequestContext).Tags(fmt.Sprintf("fav:%s %s", username, tags))
return favoritesBuilder
}
// GetPostByID returns a post builder for a specific post ID.
func (c *Client) GetPostByID(id model.PostID) builder.PostBuilder {
// Returns a post builder for a specific post ID.
return builder.NewGetPostBuilder(c.RequestContext).SetPostID(id)
}
// GetPosts returns a posts builder for general post queries.
func (c *Client) GetPosts() builder.PostsBuilder {
// Returns a posts builder for general post queries.
return builder.NewGetPostsBuilder(c.RequestContext)
}
// GetNPosts retrieves a specified number of posts.
func (c *Client) GetNPosts(n int, postBuilder builder.PostsBuilder) ([]model.Post, error) {
// Retrieves a specified number of posts using the provided post builder.
if n < utils.E621_MAX_POST_COUNT {
postBuilder.SetLimit(n)
}
posts, err := postBuilder.Execute()
if err != nil {
return nil, err
}
for len(posts) < n {
lastPostID := posts[len(posts)-1].ID
postBuilder.PageBefore(lastPostID)
postBuilder.SetLimit(n - len(posts))
newPosts, err := postBuilder.Execute()
if err != nil {
return nil, err
}
if len(newPosts) == 0 {
break
}
posts = append(posts, newPosts...)
}
return posts, nil
}
// GetAllPosts retrieves all available posts using the provided post builder.
func (c *Client) GetAllPosts(postBuilder builder.PostsBuilder) ([]model.Post, error) {
// Retrieves all available posts using the provided post builder.
return c.GetNPosts(math.MaxInt, postBuilder)
}
package e621
import (
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/builder"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
_ "github.com/joho/godotenv/autoload"
"golang.org/x/time/rate"
"net/http"
)
// Client is the main client for interacting with the e621 API.
type Client struct {
RequestContext model.RequestContext
}
// NewClient creates a new e621 client with the provided username and API key.
func NewClient(username string, apiKey string) Client {
// Create a new e621 client with the given username and API key.
return Client{
RequestContext: model.RequestContext{
Client: http.Client{},
RateLimiter: rate.NewLimiter(1, 2),
Host: "https://e621.net",
UserAgent: fmt.Sprintf("Go-e621-SDK used by %s | (made by the Anthrove Team)", username),
Username: username,
APIKey: apiKey,
},
}
}
func (c *Client) NewFavoritesBuilder() builder.FavoritesBuilder {
return builder.NewGetFavoritesBuilder(c.RequestContext)
}
/*// GetUserBuilder returns a UserBuilder instance for creating and executing requests to retrieve user information from the e621 API.
//
// Returns:
// - builder.UserBuilder: An instance of the UserBuilder.
func (c *Client) GetUserBuilder() basic.UserBuilder {
return basic.NewGetUserBuilder(c.RequestContext)
}
// GetUsersBuilder returns a UsersBuilder instance for creating and executing requests to retrieve multiple users' information from the e621 API.
//
// Returns:
// - builder.UsersBuilder: An instance of the UsersBuilder.
func (c *Client) GetUsersBuilder() basic.UsersBuilder {
return basic.NewGetUsersBuilder(c.RequestContext)
}
// GetFavoritesBuilder returns a FavoritesBuilder instance for creating and executing requests to retrieve a user's favorite posts from the e621 API.
//
// Returns:
// - builder.FavoritesBuilder: An instance of the FavoritesBuilder.
func (c *Client) GetFavoritesBuilder() basic.FavoritesBuilder {
return basic.NewGetFavoritesBuilder(c.RequestContext)
}
// GetPostBuilder returns a PostBuilder instance for creating and executing requests to retrieve post information from the e621 API.
//
// Returns:
// - builder.PostBuilder: An instance of the PostBuilder.
func (c *Client) GetPostBuilder() basic.PostBuilder {
return basic.NewGetPostBuilder(c.RequestContext)
}
// GetPostsBuilder returns a PostsBuilder instance for creating and executing requests to retrieve multiple posts' information from the e621 API.
//
// Returns:
// - builder.PostsBuilder: An instance of the PostsBuilder.
func (c *Client) GetPostsBuilder() basic.PostsBuilder {
return basic.NewGetPostsBuilder(c.RequestContext)
}
// GetNoteBuilder returns a NoteBuilder instance for creating and executing requests to retrieve note information from the e621 API.
//
// Returns:
// - builder.NoteBuilder: An instance of the NoteBuilder.
func (c *Client) GetNoteBuilder() basic.NoteBuilder {
return basic.NewGetNoteBuilder(c.RequestContext)
}
// GetNotesBuilder returns a NotesBuilder instance for creating and executing requests to retrieve multiple notes' information from the e621 API.
//
// Returns:
// - builder.NotesBuilder: An instance of the NotesBuilder.
func (c *Client) GetNotesBuilder() basic.NotesBuilder {
return basic.NewGetNotesBuilder(c.RequestContext)
}
// GetPoolBuilder returns a PoolBuilder instance for creating and executing requests to retrieve pool information from the e621 API.
//
// Returns:
// - builder.PoolBuilder: An instance of the PoolBuilder.
func (c *Client) GetPoolBuilder() basic.PoolBuilder {
return basic.NewGetPoolBuilder(c.RequestContext)
}
// GetPoolsBuilder returns a PoolsBuilder instance for creating and executing requests to retrieve multiple pools' information from the e621 API.
//
// Returns:
// - builder.PoolsBuilder: An instance of the PoolsBuilder.
func (c *Client) GetPoolsBuilder() basic.PoolsBuilder {
return basic.NewGetPoolsBuilder(c.RequestContext)
}
// GetTagBuilder returns a TagBuilder instance for creating and executing requests to retrieve tag information from the e621 API.
//
// Returns:
// - builder.TagBuilder: An instance of the TagBuilder.
func (c *Client) GetTagBuilder() basic.TagBuilder {
return basic.NewGetTagBuilder(c.RequestContext)
}
// GetTagsBuilder returns a TagsBuilder instance for creating and executing requests to retrieve multiple tags' information from the e621 API.
//
// Returns:
// - builder.TagsBuilder: An instance of the TagsBuilder.
func (c *Client) GetTagsBuilder() basic.TagsBuilder {
return basic.NewGetTagsBuilder(c.RequestContext)
}
// SetHost sets the API host for the client.
func (c *Client) SetHost(host string) *Client {
// Set the API host for the client.
c.RequestContext.Host = host
return c
}
// SetAgentName sets the user agent name for the client.
func (c *Client) SetAgentName(userAgent string) *Client {
// Set the user agent name for the client.
c.RequestContext.UserAgent = userAgent
return c
}
// GetUserByName returns a user builder for a given username.
func (c *Client) GetUserByName(username string) basic.UserBuilder {
// Returns a user builder for the specified username.
return basic.NewGetUserBuilder(c.RequestContext).SetUsername(username)
}
// GetUserByID returns a user builder for a given user ID.
func (c *Client) GetUserByID(userID model.UserID) basic.UserBuilder {
// Returns a user builder for the specified user ID.
return basic.NewGetUserBuilder(c.RequestContext).SetUsername(strconv.FormatInt(int64(userID), 10))
}
// GetFavoritesForUser returns a favorites builder for a given username.
func (c *Client) GetFavoritesForUser(username string) (basic.FavoritesBuilder, error) {
// Returns a favorites builder for the specified username.
user, err := basic.NewGetUserBuilder(c.RequestContext).SetUsername(username).Execute()
if err != nil {
return nil, err
}
favoritesBuilder := basic.NewGetFavoritesBuilder(c.RequestContext).SetUserID(user.ID)
return favoritesBuilder, nil
}
// GetNFavoritesForUser retrieves a specified number of favorites for a user.
func (c *Client) GetNFavoritesForUser(n int, favoriteBuilder basic.FavoritesBuilder) ([]model.Post, error) {
// Retrieves a specified number of favorite posts for a user.
if n < utils.E621_MAX_POST_COUNT {
favoriteBuilder.SetLimit(n)
}
var favorites []model.Post
var page = 1
for len(favorites) < n {
favoriteBuilder.Page(page)
favoriteBuilder.SetLimit(n - len(favorites))
newFavorites, err := favoriteBuilder.Execute()
if err != nil {
return nil, err
}
if len(newFavorites) == 0 {
break
}
favorites = append(favorites, newFavorites...)
page = page + 1
}
return favorites, nil
}
// GetAllFavoritesForUser retrieves all favorites for a user.
func (c *Client) GetAllFavoritesForUser(favoriteBuilder basic.FavoritesBuilder) ([]model.Post, error) {
// Retrieves all favorite posts for a user.
return c.GetNFavoritesForUser(math.MaxInt, favoriteBuilder)
}
// GetFavoritesForUserWithTags returns a posts builder for a user's favorites with specific tags.
func (c *Client) GetFavoritesForUserWithTags(username string, tags string) basic.PostsBuilder {
// Returns a posts builder for a user's favorites with specific tags.
favoritesBuilder := basic.NewGetPostsBuilder(c.RequestContext).Tags(fmt.Sprintf("fav:%s %s", username, tags))
return favoritesBuilder
}
// GetPostByID returns a post builder for a specific post ID.
func (c *Client) GetPostByID(id model.PostID) basic.PostBuilder {
// Returns a post builder for a specific post ID.
return basic.NewGetPostBuilder(c.RequestContext).SetPostID(id)
}
// GetPosts returns a posts builder for general post queries.
func (c *Client) GetPosts() basic.PostsBuilder {
// Returns a posts builder for general post queries.
return basic.NewGetPostsBuilder(c.RequestContext)
}
// GetNPosts retrieves a specified number of posts.
func (c *Client) GetNPosts(n int, postBuilder basic.PostsBuilder) ([]model.Post, error) {
// Retrieves a specified number of posts using the provided post builder.
if n < utils.E621_MAX_POST_COUNT {
postBuilder.SetLimit(n)
}
posts, err := postBuilder.Execute()
if err != nil {
return nil, err
}
for len(posts) < n {
lastPostID := posts[len(posts)-1].ID
postBuilder.PageBefore(lastPostID)
postBuilder.SetLimit(n - len(posts))
newPosts, err := postBuilder.Execute()
if err != nil {
return nil, err
}
if len(newPosts) == 0 {
break
}
posts = append(posts, newPosts...)
}
return posts, nil
}
// GetAllPosts retrieves all available posts using the provided post builder.
func (c *Client) GetAllPosts(postBuilder basic.PostsBuilder) ([]model.Post, error) {
// Retrieves all available posts using the provided post builder.
return c.GetNPosts(math.MaxInt, postBuilder)
}
func (c *Client) GetLatestPoolsDBExportDataAsBytes() (string, []byte, error) {
dbExportFileNameList, err := basic.NewGetDBExportListBuilder(c.RequestContext).Execute()
if err != nil {
return "", nil, err
}
getDBExportFile := basic.NewGetDBExportFileBuilder(c.RequestContext)
filter := func(s string) bool { return strings.HasPrefix(s, "pools") }
filteredFileNameList := utils.SliceFilter(dbExportFileNameList, filter)
regex, err := regexp.Compile("\\d{4}\\-(0?[1-9]|1[012])\\-(0?[1-9]|[12][0-9]|3[01])*")
if err != nil {
return "", nil, err
}
currentDate := time.Now()
duration := math.MaxFloat64
var fileName string
for _, listFileName := range filteredFileNameList {
if !regex.MatchString(listFileName) {
return "", nil, nil
}
fileDate, err := time.Parse("2006-04-02", regex.FindString(listFileName))
if err != nil {
return "", nil, err
}
if currentDate.Sub(fileDate).Seconds() < duration {
duration = currentDate.Sub(fileDate).Seconds()
fileName = listFileName
}
}
rawFile, err := getDBExportFile.SetFile(fileName).Execute()
if err != nil {
return "", nil, err
}
return fileName, rawFile, nil
}
func (c *Client) GetLatestPoolsDBExportDataAsStruct() ([]*model.Pool, error) {
var pools []*model.Pool
_, data, err := c.GetLatestPoolsDBExportDataAsBytes()
if err != nil {
return nil, err
}
zipReader, err := gzip.NewReader(bytes.NewReader(data))
if err != nil {
panic(err)
}
defer zipReader.Close()
// Create a CSV reader
reader := csv.NewReader(zipReader)
err = gocsv.UnmarshalCSV(reader, &pools)
if err != nil {
panic(err)
}
return pools, nil
}
func (c *Client) GetLatestPostsDBExportDataAsBytes() (string, []byte, error) {
log.Println("Please wait while the download is in progress for the post export... (file over 1GB) ")
dbExportFileNameList, err := basic.NewGetDBExportListBuilder(c.RequestContext).Execute()
if err != nil {
return "", nil, err
}
getDBExportFile := basic.NewGetDBExportFileBuilder(c.RequestContext)
filter := func(s string) bool { return strings.HasPrefix(s, "posts") }
filteredFileNameList := utils.SliceFilter(dbExportFileNameList, filter)
regex, err := regexp.Compile("\\d{4}\\-(0?[1-9]|1[012])\\-(0?[1-9]|[12][0-9]|3[01])*")
if err != nil {
return "", nil, err
}
currentDate, err := time.Parse("2006-04-02", time.Now().Format("2006-01-02"))
if err != nil {
return "", nil, err
}
duration := math.MaxFloat64
var fileName string
for _, listFileName := range filteredFileNameList {
if !regex.MatchString(listFileName) {
return "", nil, nil
}
fileDate, err := time.Parse("2006-04-02", regex.FindString(listFileName))
if err != nil {
return "", nil, err
}
if currentDate.Sub(fileDate).Seconds() < duration {
duration = currentDate.Sub(fileDate).Seconds()
fileName = listFileName
}
}
rawFile, err := getDBExportFile.SetFile(fileName).Execute()
if err != nil {
return "", nil, err
}
return fileName, rawFile, nil
}
func (c *Client) GetLatestPostsDBExportDataAsStruct() ([]*model.Post, error) {
var post []*model.Post
// TODO: Implement this function; tags in CSV are just a string with no categories assignment, needs special parsing
return post, nil
}
*/

View File

@ -1,117 +1,118 @@
package endpoints
import (
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"golang.org/x/net/html"
"net/http"
"strings"
)
// GetDBExportList retrieves a list of files available in the e621 database export.
//
// This function performs an HTTP GET request to the e621 database export endpoint and parses
// the HTML content to extract the links to export files with the ".csv.gz" extension.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - []string: A slice of file names with the ".csv.gz" extension.
// - error: An error, if any, encountered during the API request, response handling, or HTML parsing.
func GetDBExportList(requestContext model.RequestContext) ([]string, error) {
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("https://e621.net/db_export/"), nil)
if err != nil {
return nil, err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return nil, utils.StatusCodesToError(resp.StatusCode)
}
// Parse the HTML content
tokenizer := html.NewTokenizer(resp.Body)
var files []string
// Iterate through the HTML tokens
for {
tokenType := tokenizer.Next()
switch tokenType {
case html.ErrorToken:
// End of the HTML document
return files, nil
case html.StartTagToken, html.SelfClosingTagToken:
token := tokenizer.Token()
if token.Data == "a" {
// Check if the anchor tag has an href attribute
for _, attr := range token.Attr {
if attr.Key == "href" {
// Filter out the parent directory link and only add links with ".csv.gz" extension
if !strings.HasPrefix(attr.Val, "../") && strings.HasSuffix(attr.Val, ".csv.gz") {
files = append(files, attr.Val)
}
break
}
}
}
}
}
}
// GetDBExportFile retrieves a specific file from the e621 database export.
//
// This function performs an HTTP GET request to the e621 database export endpoint to fetch a
// particular file identified by its name.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - file: The name of the file to be fetched from the database export.
//
// Returns:
// - *http.Response: The HTTP response containing the requested file (probably a csv.gz).
// - error: An error, if any, encountered during the API request or response handling.
func GetDBExportFile(requestContext model.RequestContext, file string) (*http.Response, error) {
if file == "" {
return nil, fmt.Errorf("no file specified")
}
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("https://e621.net/db_export/%s", file), nil)
if err != nil {
return nil, err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return nil, utils.StatusCodesToError(resp.StatusCode)
}
return resp, nil
}
package endpoints
import (
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"golang.org/x/net/html"
"io"
"net/http"
"strings"
)
// GetDBExportList retrieves a list of files available in the e621 database export.
//
// This function performs an HTTP GET request to the e621 database export endpoint and parses
// the HTML content to extract the links to export files with the ".csv.gz" extension.
//
// Parameters:
// - model.RequestContext: The context for the API request, including the host, user agent, username, and API key.
//
// Returns:
// - []string: A slice of file names with the ".csv.gz" extension.
// - error: An error, if any, encountered during the API request, response handling, or HTML parsing.
func GetDBExportList(requestContext model.RequestContext) ([]string, error) {
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("https://e621.net/db_export/"), nil)
if err != nil {
return nil, err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return nil, utils.StatusCodesToError(resp.StatusCode)
}
// Parse the HTML content
tokenizer := html.NewTokenizer(resp.Body)
var files []string
// Iterate through the HTML tokens
for {
tokenType := tokenizer.Next()
switch tokenType {
case html.ErrorToken:
// End of the HTML document
return files, nil
case html.StartTagToken, html.SelfClosingTagToken:
token := tokenizer.Token()
if token.Data == "a" {
// Check if the anchor tag has an href attribute
for _, attr := range token.Attr {
if attr.Key == "href" {
// Filter out the parent directory link and only add links with ".csv.gz" extension
if !strings.HasPrefix(attr.Val, "../") && strings.HasSuffix(attr.Val, ".csv.gz") {
files = append(files, attr.Val)
}
break
}
}
}
}
}
}
// GetDBExportFile retrieves a specific file from the e621 database export.
//
// This function performs an HTTP GET request to the e621 database export endpoint to fetch a
// particular file identified by its name.
//
// Parameters:
// - model.RequestContext: The context for the API request, including the host, user agent, username, and API key.
// - file: The name of the file to be fetched from the database export.
//
// Returns:
// - []byte: A byte array representation of the file.
// - error: An error, if any, encountered during the API request or response handling.
func GetDBExportFile(requestContext model.RequestContext, file string) ([]byte, error) {
if file == "" {
return nil, fmt.Errorf("no file specified")
}
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("https://e621.net/db_export/%s", file), nil)
if err != nil {
return nil, err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return nil, utils.StatusCodesToError(resp.StatusCode)
}
return io.ReadAll(resp.Body)
}

View File

@ -1,234 +0,0 @@
package endpoints
import (
"encoding/json"
"fmt"
"net/http"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
)
// GetDmail retrieves a specific DMail by its ID.
//
// This function performs an HTTP GET request to the e621 DMail endpoint and parses
// the JSON content to extract the DMail data.
//
// Parameters:
// - requestContext: The model.RequestContext for the API request.
// - ID: The ID of the DMail to be fetched.
//
// Returns:
// - model.DMail: A struct containing the DMail data.
// - error: An error, if any, encountered during the API request or response handling.
func GetDmail(requestContext model.RequestContext, ID int) (model.DMail, error) {
// Create a new HTTP GET request to fetch the post information.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/dmails/%d.json", requestContext.Host, ID), nil)
if err != nil {
// Log the error and return an empty Post struct and the error.
return model.DMail{}, err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Post struct and the error.
return model.DMail{}, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return model.DMail{}, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a Post struct to store the response data.
var postResponse model.DMail
// Decode the JSON response into the PostResponse struct.
err = json.NewDecoder(resp.Body).Decode(&postResponse)
if err != nil {
// Log the error and return an empty Post struct and the error.
return model.DMail{}, err
}
// Return the post information and no error (nil).
return postResponse, nil
}
// DeleteDmail deletes a specific DMail by its ID.
//
// This function performs an HTTP DELETE request to the e621 DMail endpoint.
//
// Parameters:
// - requestContext: The model.RequestContext for the API request.
// - ID: The ID of the DMail to be deleted.
//
// Returns:
// - error: An error, if any, encountered during the API request or response handling.
func DeleteDmail(requestContext model.RequestContext, ID int) error {
// Create a new HTTP GET request to fetch the post information.
r, err := http.NewRequest("DELETE", fmt.Sprintf("%s/dmails/%d.json", requestContext.Host, ID), nil)
if err != nil {
// Log the error and return an empty Post struct and the error.
return err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Post struct and the error.
return err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return utils.StatusCodesToError(resp.StatusCode)
}
// Return the post information and no error (nil).
return nil
}
// MarkAsReadDmail marks a specific DMail as read by its ID.
//
// This function performs an HTTP PUT request to the e621 DMail endpoint.
//
// Parameters:
// - requestContext: The model.RequestContext for the API request.
// - ID: The ID of the DMail to be marked as read.
//
// Returns:
// - error: An error, if any, encountered during the API request or response handling.
func MarkAsReadDmail(requestContext model.RequestContext, ID int) error {
// Create a new HTTP GET request to fetch the post information.
r, err := http.NewRequest("PUT", fmt.Sprintf("%s/dmails/%d/mark_as_read.json", requestContext.Host, ID), nil)
if err != nil {
// Log the error and return an empty Post struct and the error.
return err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Post struct and the error.
return err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return utils.StatusCodesToError(resp.StatusCode)
}
// Return the post information and no error (nil).
return nil
}
// GetAllDmails retrieves all DMails.
//
// This function performs an HTTP GET request to the e621 DMail endpoint and parses
// the JSON content to extract the DMail data.
//
// Parameters:
// - requestContext: The model.RequestContext for the API request.
// - query: A map containing the query parameters for the request.
//
// Returns:
// - []model.DMail: A slice of structs containing the DMail data.
// - error: An error, if any, encountered during the API request or response handling.
func GetAllDmails(requestContext model.RequestContext, query map[string]string) ([]model.DMail, error) {
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/dmails.json", requestContext.Host), nil)
if err != nil {
return nil, err
}
// Append query parameters to the request URL.
q := r.URL.Query()
for k, v := range query {
q.Add(k, v)
}
r.URL.RawQuery = q.Encode()
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return nil, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a slice of Post struct to store the response data.
var postResponse []model.DMail
// Decode the JSON response into the PostResponse struct.
err = json.NewDecoder(resp.Body).Decode(&postResponse)
if err != nil {
// Log the error and return an empty slice and the error.
return []model.DMail{}, nil
}
// Return the list of posts and no error (nil).
return postResponse, nil
}
// MarkAsReadAllDmails marks all DMails as read.
//
// This function performs an HTTP PUT request to the e621 DMail endpoint.
//
// Parameters:
// - requestContext: The model.RequestContext for the API request.
//
// Returns:
// - error: An error, if any, encountered during the API request or response handling.
func MarkAsReadAllDmails(requestContext model.RequestContext) error {
// Create a new HTTP GET request to fetch the post information.
r, err := http.NewRequest("PUT", fmt.Sprintf("%s/dmails/mark_all_as_read.json", requestContext.Host), nil)
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Post struct and the error.
return err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return utils.StatusCodesToError(resp.StatusCode)
}
// Return the post information and no error (nil).
return nil
}

View File

@ -0,0 +1,89 @@
package endpoints
import (
"encoding/json"
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"net/http"
)
type RequestTypes interface {
model.User |
model.Tag |
model.Post |
model.PostResponse |
model.Pool |
model.Note |
[]model.User |
[]model.Tag |
[]model.Post |
[]model.Pool |
[]model.Note
}
// getRequest performs an HTTP GET request to the specified e621 API endpoint and unmarshals the JSON response into the provided type T.
//
// This generic function is designed to fetch data from the e621 API using an HTTP GET request.
// It supports generic types and can unmarshal the JSON response into the provided type T.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - e621Endpoint: The specific e621 API endpoint to be called.
// - query: A map containing additional query parameters for the API request. (Optional)
//
// Type Parameters:
// - T: The type into which the JSON response will be unmarshaled.
// - supported types are (also as slice): model.User, model.Tag, model.Post, model.PostResponse, model.Pool, model.Note
//
// Returns:
// - T: The result of unmarshaling the JSON response into the provided type.
// - error: An error, if any, encountered during the API request, response handling, or JSON unmarshaling.
func getRequest[T RequestTypes](requestContext model.RequestContext, e621Endpoint string, query map[string]string) (T, error) {
var base T
// Create a new HTTP GET request to fetch user information from the specified 'host' and 'username'.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/%s", requestContext.Host, e621Endpoint), nil)
if err != nil {
// Log the error and return an empty User struct and the error.
return base, err
}
// Append query parameters to the request URL.
if query != nil {
q := r.URL.Query()
for k, v := range query {
q.Add(k, v)
}
r.URL.RawQuery = q.Encode()
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty User struct and the error.
return base, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return base, utils.StatusCodesToError(resp.StatusCode)
}
// Decode the JSON response into the User struct.
err = json.NewDecoder(resp.Body).Decode(&base)
if err != nil {
// Log the error and return an empty User struct and the error.
return base, err
}
// Return the user information and no error (nil).
return base, nil
}

View File

@ -1,64 +1,22 @@
package endpoints
import (
"encoding/json"
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"net/http"
)
// GetFavorites retrieves a user's favorite posts from the e621 API.
//
// The user_id parameter is required to get the favorites of a user.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Returns:
// - []model.Post: A slice of favorite posts.
// - error: An error, if any, encountered during the API request or response handling.
func GetFavorites(requestContext model.RequestContext, query map[string]string) ([]model.Post, error) {
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/favorites.json", requestContext.Host), nil)
if err != nil {
return nil, err
}
// Append query parameters to the request URL.
q := r.URL.Query()
for k, v := range query {
q.Add(k, v)
}
r.URL.RawQuery = q.Encode()
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return nil, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a User struct to store the response data.
var favoriteResponse model.PostResponse
// Decode the JSON response into the user struct.
err = json.NewDecoder(resp.Body).Decode(&favoriteResponse)
if err != nil {
// Log the error and return an empty User struct and the error.
return nil, err
}
return favoriteResponse.Posts, nil
}
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
)
// GetFavorites retrieves a user's favorite posts from the e621 API.
//
// The user_id parameter is required to get the favorites of a user.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Returns:
// - []model.Post: A slice of favorite posts.
// - error: An error, if any, encountered during the API request or response handling.
func GetFavorites(requestContext model.RequestContext, query map[string]string) ([]model.Post, error) {
endpoint := "favorites.json"
data, err := getRequest[model.PostResponse](requestContext, endpoint, query)
return data.Posts, err
}

View File

@ -1,48 +1,48 @@
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetFavorites(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.PostResponse]("../../../tests/posts.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/favorites.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
posts, err := GetFavorites(requestContext, map[string]string{})
if err != nil {
t.Error(err)
return
}
if posts[0].ID == response.Posts[0].ID && posts[1].File.Md5 == response.Posts[1].File.Md5 && posts[2].File.EXT == response.Posts[2].File.EXT {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", posts, response)
}
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetFavorites(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.PostResponse]("../../../tests/posts.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/favorites.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
posts, err := GetFavorites(requestContext, map[string]string{})
if err != nil {
t.Error(err)
return
}
if posts[0].ID == response.Posts[0].ID && posts[1].File.Md5 == response.Posts[1].File.Md5 && posts[2].File.EXT == response.Posts[2].File.EXT {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", posts, response)
}

View File

@ -1,121 +1,34 @@
package endpoints
import (
"encoding/json"
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"io"
"net/http"
"strings"
)
// GetNote retrieves a single note by its ID from the e621 API.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - ID: The ID of the note to retrieve.
//
// Returns:
// - model.Note: The retrieved note.
// - error: An error, if any, encountered during the API request or response handling.
func GetNote(requestContext model.RequestContext, ID string) (model.Note, error) {
// Create a new HTTP GET request to fetch the note information.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/notes/%s.json", requestContext.Host, ID), nil)
if err != nil {
// Log the error and return an empty Note struct and the error.
return model.Note{}, err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Note struct and the error.
return model.Note{}, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return model.Note{}, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a Note struct to store the response data.
var noteResponse model.Note
// Decode the JSON response into the Note struct.
err = json.NewDecoder(resp.Body).Decode(&noteResponse)
if err != nil {
// Log the error and return an empty Note struct and the error.
return model.Note{}, err
}
// Return the note information and no error (nil).
return noteResponse, nil
}
// GetNotes retrieves a list of notes from the e621 API based on query parameters.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Returns:
// - []model.Note: A slice of notes.
// - error: An error, if any, encountered during the API request or response handling.
func GetNotes(requestContext model.RequestContext, query map[string]string) ([]model.Note, error) {
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/notes.json", requestContext.Host), nil)
if err != nil {
return nil, err
}
// Append query parameters to the request URL.
q := r.URL.Query()
for k, v := range query {
q.Add(k, v)
}
r.URL.RawQuery = q.Encode()
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return nil, utils.StatusCodesToError(resp.StatusCode)
}
respBodyBytes, err := io.ReadAll(resp.Body)
if strings.Contains(string(respBodyBytes), "{\"notes\":[]}") {
return nil, nil
}
// Initialize a slice of Note struct to store the response data.
var notesResponse []model.Note
// Decode the JSON response into the slice of Note structs.
err = json.Unmarshal(respBodyBytes, &notesResponse)
if err != nil {
// Log the error and return an empty slice and the error.
return nil, err
}
// Return the list of notes and no error (nil).
return notesResponse, nil
}
package endpoints
import (
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
)
// GetNote retrieves a single note by its ID from the e621 API.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - ID: The ID of the note to retrieve.
//
// Returns:
// - model.Note: The retrieved note.
// - error: An error, if any, encountered during the API request or response handling.
func GetNote(requestContext model.RequestContext, ID string) (model.Note, error) {
endpoint := fmt.Sprintf("notes/%s.json", ID)
return getRequest[model.Note](requestContext, endpoint, nil)
}
// GetNotes retrieves a list of notes from the e621 API based on query parameters.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Returns:
// - []model.Note: A slice of notes.
// - error: An error, if any, encountered during the API request or response handling.
func GetNotes(requestContext model.RequestContext, query map[string]string) ([]model.Note, error) {
endpoint := "notes.json"
return getRequest[[]model.Note](requestContext, endpoint, query)
}

View File

@ -1,87 +1,87 @@
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetNote(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Note]("../../../tests/note.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/notes/1337.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
pool, err := GetNote(requestContext, "1337")
if err != nil {
t.Error(err)
return
}
if pool.ID == response.ID && pool.Body == response.Body {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pool, response)
}
func TestGetNotes(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.Note]("../../../tests/notes.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/notes.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
pools, err := GetNotes(requestContext, map[string]string{})
if err != nil {
t.Error(err)
return
}
if pools[0].ID == response[0].ID && pools[1].Body == response[1].Body && pools[2].UpdatedAt == response[2].UpdatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pools, response)
}
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetNote(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Note]("../../../tests/note.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/notes/1337.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
pool, err := GetNote(requestContext, "1337")
if err != nil {
t.Error(err)
return
}
if pool.ID == response.ID && pool.Body == response.Body {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pool, response)
}
func TestGetNotes(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.Note]("../../../tests/notes.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/notes.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
pools, err := GetNotes(requestContext, map[string]string{})
if err != nil {
t.Error(err)
return
}
if pools[0].ID == response[0].ID && pools[1].Body == response[1].Body && pools[2].UpdatedAt == response[2].UpdatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pools, response)
}

View File

@ -1,114 +1,34 @@
package endpoints
import (
"encoding/json"
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"net/http"
)
// GetPool retrieves a pool by its ID from the e621 API.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - ID: The ID of the pool to retrieve.
//
// Returns:
// - model.Pool: The retrieved pool.
// - error: An error, if any, encountered during the API request or response handling.
func GetPool(requestContext model.RequestContext, ID string) (model.Pool, error) {
// Create a new HTTP GET request to fetch the pool information.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/pools/%s.json", requestContext.Host, ID), nil)
if err != nil {
// Log the error and return an empty Pool struct and the error.
return model.Pool{}, err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Pool struct and the error.
return model.Pool{}, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return model.Pool{}, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a Pool struct to store the response data.
var poolResponse model.Pool
// Decode the JSON response into the Pool struct.
err = json.NewDecoder(resp.Body).Decode(&poolResponse)
if err != nil {
// Log the error and return an empty Pool struct and the error.
return model.Pool{}, err
}
// Return the pool information and no error (nil).
return poolResponse, nil
}
// GetPools retrieves a list of pools from the e621 API based on query parameters.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Returns:
// - []model.Pool: A slice of pools.
// - error: An error, if any, encountered during the API request or response handling.
func GetPools(requestContext model.RequestContext, query map[string]string) ([]model.Pool, error) {
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/pools.json", requestContext.Host), nil)
if err != nil {
return nil, err
}
// Append query parameters to the request URL.
q := r.URL.Query()
for k, v := range query {
q.Add(k, v)
}
r.URL.RawQuery = q.Encode()
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return nil, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a slice of Pool struct to store the response data.
var poolsResponse []model.Pool
// Decode the JSON response into the slice of Pool structs.
err = json.NewDecoder(resp.Body).Decode(&poolsResponse)
if err != nil {
// Log the error and return an empty slice and the error.
return nil, err
}
// Return the list of pools and no error (nil).
return poolsResponse, nil
}
package endpoints
import (
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
)
// GetPool retrieves a pool by its ID from the e621 API.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - ID: The ID of the pool to retrieve.
//
// Returns:
// - model.Pool: The retrieved pool.
// - error: An error, if any, encountered during the API request or response handling.
func GetPool(requestContext model.RequestContext, ID string) (model.Pool, error) {
endpoint := fmt.Sprintf("pools/%s.json", ID)
return getRequest[model.Pool](requestContext, endpoint, nil)
}
// GetPools retrieves a list of pools from the e621 API based on query parameters.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Returns:
// - []model.Pool: A slice of pools.
// - error: An error, if any, encountered during the API request or response handling.
func GetPools(requestContext model.RequestContext, query map[string]string) ([]model.Pool, error) {
endpoint := "pools.json"
return getRequest[[]model.Pool](requestContext, endpoint, query)
}

View File

@ -1,87 +1,87 @@
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPool(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Pool]("../../../tests/pool.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/pools/36957.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
pool, err := GetPool(requestContext, "36957")
if err != nil {
t.Error(err)
return
}
if pool.ID == response.ID && pool.Name == response.Name {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pool, response)
}
func TestGetPools(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.Pool]("../../../tests/pools.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/pools.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
pools, err := GetPools(requestContext, map[string]string{})
if err != nil {
t.Error(err)
return
}
if pools[0].ID == response[0].ID && pools[1].Name == response[1].Name && pools[2].UpdatedAt == response[2].UpdatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pools, response)
}
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPool(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Pool]("../../../tests/pool.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/pools/36957.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
pool, err := GetPool(requestContext, "36957")
if err != nil {
t.Error(err)
return
}
if pool.ID == response.ID && pool.Name == response.Name {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pool, response)
}
func TestGetPools(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.Pool]("../../../tests/pools.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/pools.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
pools, err := GetPools(requestContext, map[string]string{})
if err != nil {
t.Error(err)
return
}
if pools[0].ID == response[0].ID && pools[1].Name == response[1].Name && pools[2].UpdatedAt == response[2].UpdatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", pools, response)
}

View File

@ -1,113 +1,34 @@
package endpoints
import (
"encoding/json"
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"net/http"
)
// GetPost retrieves a single post by its ID from the e621 API.
//
// Parameters: // - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - ID: The ID of the post to retrieve.
//
// Returns:
// - model.Post: The retrieved post.
// - error: An error, if any, encountered during the API request or response handling.
func GetPost(requestContext model.RequestContext, ID string) (model.Post, error) {
// Create a new HTTP GET request to fetch the post information.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/posts/%s.json", requestContext.Host, ID), nil)
if err != nil {
// Log the error and return an empty Post struct and the error.
return model.Post{}, err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Post struct and the error.
return model.Post{}, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return model.Post{}, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a Post struct to store the response data.
var postResponse model.PostResponse
// Decode the JSON response into the PostResponse struct.
err = json.NewDecoder(resp.Body).Decode(&postResponse)
if err != nil {
// Log the error and return an empty Post struct and the error.
return model.Post{}, err
}
// Return the post information and no error (nil).
return postResponse.Post, nil
}
// GetPosts retrieves a list of posts from the e621 API based on query parameters.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Returns:
// - []model.Post: A slice of posts.
// - error: An error, if any, encountered during the API request or response handling.
func GetPosts(requestContext model.RequestContext, query map[string]string) ([]model.Post, error) {
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/posts.json", requestContext.Host), nil)
if err != nil {
return nil, err
}
// Append query parameters to the request URL.
q := r.URL.Query()
for k, v := range query {
q.Add(k, v)
}
r.URL.RawQuery = q.Encode()
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return nil, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a slice of Post struct to store the response data.
var postResponse model.PostResponse
// Decode the JSON response into the PostResponse struct.
err = json.NewDecoder(resp.Body).Decode(&postResponse)
if err != nil {
// Log the error and return an empty slice and the error.
return nil, err
}
// Return the list of posts and no error (nil).
return postResponse.Posts, nil
}
package endpoints
import (
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
)
// GetPost retrieves a single post by its ID from the e621 API.
//
// Parameters: // - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - ID: The ID of the post to retrieve.
//
// Returns:
// - model.Post: The retrieved post.
// - error: An error, if any, encountered during the API request or response handling.
func GetPost(requestContext model.RequestContext, ID string) (model.Post, error) {
endpoint := fmt.Sprintf("posts/%s.json", ID)
return getRequest[model.Post](requestContext, endpoint, nil)
}
// GetPosts retrieves a list of posts from the e621 API based on query parameters.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Returns:
// - []model.Post: A slice of posts.
// - error: An error, if any, encountered during the API request or response handling.
func GetPosts(requestContext model.RequestContext, query map[string]string) ([]model.Post, error) {
endpoint := "posts.json"
data, err := getRequest[model.PostResponse](requestContext, endpoint, query)
return data.Posts, err
}

View File

@ -1,92 +1,92 @@
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPost(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
data, err := utils.LoadJsonTestData[model.Post]("../../../tests/post.json")
if err != nil {
t.Error(err)
return
}
response := model.PostResponse{
Post: data,
Posts: nil,
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/posts/1337.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
post, err := GetPost(requestContext, "1337")
if err != nil {
t.Error(err)
return
}
if post.ID == response.Post.ID && post.File.URL == response.Post.File.URL {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", post, response)
}
func TestGetPosts(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.PostResponse]("../../../tests/posts.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/posts.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
posts, err := GetPosts(requestContext, map[string]string{})
if err != nil {
t.Error(err)
return
}
if posts[0].ID == response.Posts[0].ID && posts[1].File.Md5 == response.Posts[1].File.Md5 && posts[2].File.EXT == response.Posts[2].File.EXT {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", posts, response)
}
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetPost(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
data, err := utils.LoadJsonTestData[model.Post]("../../../tests/post.json")
if err != nil {
t.Error(err)
return
}
response := model.PostResponse{
Post: data,
Posts: nil,
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/posts/1337.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
post, err := GetPost(requestContext, "1337")
if err != nil {
t.Error(err)
return
}
if post.ID == response.Post.ID && post.File.URL == response.Post.File.URL {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", post, response)
}
func TestGetPosts(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.PostResponse]("../../../tests/posts.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/posts.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
posts, err := GetPosts(requestContext, map[string]string{})
if err != nil {
t.Error(err)
return
}
if posts[0].ID == response.Posts[0].ID && posts[1].File.Md5 == response.Posts[1].File.Md5 && posts[2].File.EXT == response.Posts[2].File.EXT {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", posts, response)
}

View File

@ -1,125 +1,44 @@
package endpoints
import (
"encoding/json"
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"net/http"
)
// GetTag retrieves a tag by its ID from the e621 API.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - ID: The ID of the tag to retrieve.
//
// Returns:
// - model.Tag: The retrieved tag.
// - error: An error, if any, encountered during the API request or response handling.
func GetTag(requestContext model.RequestContext, ID string) (model.Tag, error) {
// Create a new HTTP GET request to fetch tag information.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/tags/%s.json", requestContext.Host, ID), nil)
if err != nil {
// Log the error and return an empty Tag struct and the error.
return model.Tag{}, err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application.json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty Tag struct and the error.
return model.Tag{}, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return model.Tag{}, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a Tag struct to store the response data.
var tag model.Tag
// Decode the JSON response into the Tag struct.
err = json.NewDecoder(resp.Body).Decode(&tag)
if err != nil {
// Log the error and return an empty Tag struct and the error.
return model.Tag{}, err
}
// Return the tag information and no error (nil).
return tag, nil
}
// GetTags retrieves a list of tags from the e621 API based on query parameters.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Query:
// - search[name_matches]: A tag name expression to match against, which can include * as a wildcard.
// - search[category]: Filters results to a particular category. Default value is blank (show all tags). 0 general; 1 artist; 3 copyright; 4 character; 5 species; 6 invalid; 7 meta; 8 lore
// - search[order]: Changes the sort order. Pass one of date (default), count, or name.
// - search[hide_empty]: Hide tags with zero visible posts. Pass true (default) or false.
// - search[has_wiki]: Show only tags with, or without, a wiki page. Pass true, false, or blank (default).
// - search[has_artist]: Show only tags with, or without an artist page. Pass true, false, or blank (default).
// - limit: Maximum number of results to return per query. Default is 75. There is a hard upper limit of 320.
// - page: The page that will be returned. Can also be used with a or b + tag_id to get the tags after or before the specified tag ID. For example a13 gets every tag after tag_id 13 up to the limit. This overrides the specified search ordering, date is always used instead.
//
// Returns:
// - []model.Tag: A slice of tags.
// - error: An error, if any, encountered during the API request or response handling.
func GetTags(requestContext model.RequestContext, query map[string]string) ([]model.Tag, error) {
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/tags.json", requestContext.Host), nil)
if err != nil {
return nil, err
}
// Append query parameters to the request URL.
q := r.URL.Query()
for k, v := range query {
q.Add(k, v)
}
r.URL.RawQuery = q.Encode()
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return []model.Tag{}, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a slice of Tag struct to store the response data.
var tags []model.Tag
// Decode the JSON response into the slice of Tag structs.
err = json.NewDecoder(resp.Body).Decode(&tags)
if err != nil {
// Log the error and return an empty slice and the error.
return []model.Tag{}, err
}
// Return the list of tags and no error (nil).
return tags, nil
}
package endpoints
import (
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
)
// GetTag retrieves a tag by its ID from the e621 API.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - ID: The ID of the tag to retrieve.
//
// Returns:
// - model.Tag: The retrieved tag.
// - error: An error, if any, encountered during the API request or response handling.
func GetTag(requestContext model.RequestContext, ID string) (model.Tag, error) {
endpoint := fmt.Sprintf("tags/%s.json", ID)
return getRequest[model.Tag](requestContext, endpoint, nil)
}
// GetTags retrieves a list of tags from the e621 API based on query parameters.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Query:
// - search[name_matches]: A tag name expression to match against, which can include * as a wildcard.
// - search[category]: Filters results to a particular category. Default value is blank (show all tags). 0 general; 1 artist; 3 copyright; 4 character; 5 species; 6 invalid; 7 meta; 8 lore
// - search[order]: Changes the sort order. Pass one of date (default), count, or name.
// - search[hide_empty]: Hide tags with zero visible posts. Pass true (default) or false.
// - search[has_wiki]: Show only tags with, or without, a wiki page. Pass true, false, or blank (default).
// - search[has_artist]: Show only tags with, or without an artist page. Pass true, false, or blank (default).
// - limit: Maximum number of results to return per query. Default is 75. There is a hard upper limit of 320.
// - page: The page that will be returned. Can also be used with a or b + tag_id to get the tags after or before the specified tag ID. For example a13 gets every tag after tag_id 13 up to the limit. This overrides the specified search ordering, date is always used instead.
//
// Returns:
// - []model.Tag: A slice of tags.
// - error: An error, if any, encountered during the API request or response handling.
func GetTags(requestContext model.RequestContext, query map[string]string) ([]model.Tag, error) {
endpoint := "tags.json"
return getRequest[[]model.Tag](requestContext, endpoint, query)
}

View File

@ -1,48 +1,48 @@
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetTag(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Tag]("../../../tests/tag.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/tags/165165.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
tag, err := GetTag(requestContext, "165165")
if err != nil {
t.Error(err)
return
}
if tag.ID == response.ID && tag.Name == response.Name && tag.CreatedAt == response.CreatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", tag, response)
}
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetTag(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.Tag]("../../../tests/tag.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/tags/165165.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
tag, err := GetTag(requestContext, "165165")
if err != nil {
t.Error(err)
return
}
if tag.ID == response.ID && tag.Name == response.Name && tag.CreatedAt == response.CreatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", tag, response)
}

View File

@ -1,114 +1,34 @@
package endpoints
import (
"encoding/json"
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"net/http"
)
// GetUser retrieves user information from e621.net based on the provided username.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - username: The username of the user to retrieve.
//
// Returns:
// - model.User: The retrieved user.
// - error: An error, if any, encountered during the API request or response handling.
func GetUser(requestContext model.RequestContext, username string) (model.User, error) {
// Create a new HTTP GET request to fetch user information from the specified 'host' and 'username'.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/users/%s.json", requestContext.Host, username), nil)
if err != nil {
// Log the error and return an empty User struct and the error.
return model.User{}, err
}
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
// Log the error and return an empty User struct and the error.
return model.User{}, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return model.User{}, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a User struct to store the response data.
var user model.User
// Decode the JSON response into the User struct.
err = json.NewDecoder(resp.Body).Decode(&user)
if err != nil {
// Log the error and return an empty User struct and the error.
return model.User{}, err
}
// Return the user information and no error (nil).
return user, nil
}
// GetUsers retrieves a list of users from e621.net based on query parameters.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Returns:
// - []model.User: A slice of users.
// - error: An error, if any, encountered during the API request or response handling.
func GetUsers(requestContext model.RequestContext, query map[string]string) ([]model.User, error) {
// Create a new HTTP GET request.
r, err := http.NewRequest("GET", fmt.Sprintf("%s/users.json", requestContext.Host), nil)
if err != nil {
return nil, err
}
// Append query parameters to the request URL.
q := r.URL.Query()
for k, v := range query {
q.Add(k, v)
}
r.URL.RawQuery = q.Encode()
r.Header.Set("User-Agent", requestContext.UserAgent)
r.Header.Add("Accept", "application/json")
r.SetBasicAuth(requestContext.Username, requestContext.APIKey)
// Send the request using the provided http.Client.
resp, err := requestContext.Client.Do(r)
if err != nil {
return nil, err
}
// Check if the HTTP response status code indicates success (2xx range).
if resp.StatusCode < 200 || resp.StatusCode > 300 {
// If the status code is outside the 2xx range, return an error based on the status code.
return []model.User{}, utils.StatusCodesToError(resp.StatusCode)
}
// Initialize a slice of User struct to store the response data.
var users []model.User
// Decode the JSON response into the slice of User structs.
err = json.NewDecoder(resp.Body).Decode(&users)
if err != nil {
// Log the error and return an empty slice and the error.
return []model.User{}, err
}
// Return the list of users and no error (nil).
return users, nil
}
package endpoints
import (
"fmt"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
)
// GetUser retrieves user information from e621.net based on the provided username.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - username: The username of the user to retrieve.
//
// Returns:
// - model.User: The retrieved user.
// - error: An error, if any, encountered during the API request or response handling.
func GetUser(requestContext model.RequestContext, username string) (model.User, error) {
endpoint := fmt.Sprintf("users/%s.json", username)
return getRequest[model.User](requestContext, endpoint, nil)
}
// GetUsers retrieves a list of users from e621.net based on query parameters.
//
// Parameters:
// - requestContext: The context for the API request, including the host, user agent, username, and API key.
// - query: A map containing additional query parameters for the API request.
//
// Returns:
// - []model.User: A slice of users.
// - error: An error, if any, encountered during the API request or response handling.
func GetUsers(requestContext model.RequestContext, query map[string]string) ([]model.User, error) {
endpoint := "users.json"
return getRequest[[]model.User](requestContext, endpoint, query)
}

View File

@ -1,87 +1,87 @@
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetUser(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.User]("../../../tests/user.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/users/selloo.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
user, err := GetUser(requestContext, "selloo")
if err != nil {
t.Error(err)
return
}
if user.ID == response.ID && user.Name == response.Name && user.CreatedAt == response.CreatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", user, response)
}
func TestGetUsers(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.User]("../../../tests/users.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/users.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
user, err := GetUsers(requestContext, map[string]string{})
if err != nil {
t.Error(err)
return
}
if user[0].ID == response[0].ID && user[1].Name == response[1].Name {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", user, response)
}
package endpoints
import (
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/model"
"git.dragse.it/anthrove/e621-sdk-go/pkg/e621/utils"
"github.com/jarcoal/httpmock"
"net/http"
"testing"
)
func TestGetUser(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[model.User]("../../../tests/user.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/users/selloo.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
user, err := GetUser(requestContext, "selloo")
if err != nil {
t.Error(err)
return
}
if user.ID == response.ID && user.Name == response.Name && user.CreatedAt == response.CreatedAt {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", user, response)
}
func TestGetUsers(t *testing.T) {
httpmock.Activate()
defer httpmock.DeactivateAndReset()
response, err := utils.LoadJsonTestData[[]model.User]("../../../tests/users.json")
if err != nil {
t.Error(err)
return
}
responder, err := httpmock.NewJsonResponder(200, response)
if err != nil {
t.Error(err)
return
}
httpmock.RegisterResponder("GET", "https://e621.net/users.json", responder)
requestContext := model.RequestContext{
Client: http.Client{},
Host: "https://e621.net",
UserAgent: "Go-e621-SDK (@username)",
Username: "memo",
APIKey: "123456",
}
user, err := GetUsers(requestContext, map[string]string{})
if err != nil {
t.Error(err)
return
}
if user[0].ID == response[0].ID && user[1].Name == response[1].Name {
return
}
t.Errorf("Respons did not match mock data:\nOriginal: %v\nMock: %v", user, response)
}

View File

@ -1,15 +1,15 @@
package model
import (
"golang.org/x/time/rate"
"net/http"
)
type RequestContext struct {
Client http.Client
RateLimiter *rate.Limiter
Host string
UserAgent string
Username string
APIKey string
}
package model
import (
"golang.org/x/time/rate"
"net/http"
)
type RequestContext struct {
Client http.Client
RateLimiter *rate.Limiter
Host string
UserAgent string
Username string
APIKey string
}

View File

@ -1,16 +0,0 @@
package model
import "time"
type DMail struct {
Body string `json:"body"`
CreatedAt time.Time `json:"created_at"`
FromId int `json:"from_id"`
Id int `json:"id"`
IsDeleted bool `json:"is_deleted"`
IsRead bool `json:"is_read"`
OwnerId int `json:"owner_id"`
Title string `json:"title"`
ToId int `json:"to_id"`
UpdatedAt time.Time `json:"updated_at"`
}

View File

@ -1,17 +1,17 @@
package model
type Note struct {
ID int64 `json:"id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
CreatorID int64 `json:"creator_id"`
X int64 `json:"x"`
Y int64 `json:"y"`
Width int64 `json:"width"`
Height int64 `json:"height"`
Version int64 `json:"version"`
IsActive bool `json:"is_active"`
PostID int64 `json:"post_id"`
Body string `json:"body"`
CreatorName string `json:"creator_name"`
}
package model
type Note struct {
ID int64 `json:"id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
CreatorID int64 `json:"creator_id"`
X int64 `json:"x"`
Y int64 `json:"y"`
Width int64 `json:"width"`
Height int64 `json:"height"`
Version int64 `json:"version"`
IsActive bool `json:"is_active"`
PostID int64 `json:"post_id"`
Body string `json:"body"`
CreatorName string `json:"creator_name"`
}

View File

@ -1,30 +1,74 @@
package model
type PoolCategory string
type PoolOrder string
const (
Series PoolCategory = "series"
Collection PoolCategory = "collection"
)
const (
PoolName PoolOrder = "name"
CreatedAt PoolOrder = "created_at"
UpdatedAt PoolOrder = "updated_at"
PostCount PoolOrder = "post_count"
)
type Pool struct {
ID int64 `json:"id"`
Name string `json:"name"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
CreatorID int64 `json:"creator_id"`
Description string `json:"description"`
IsActive bool `json:"is_active"`
Category PoolCategory `json:"category"`
PostIDS []int64 `json:"post_ids"`
CreatorName string `json:"creator_name"`
PostCount int64 `json:"post_count"`
}
package model
import (
"fmt"
"strconv"
"strings"
)
type PoolCategory string
type PoolOrder string
type PoolIDs []int64
const (
Series PoolCategory = "series"
Collection PoolCategory = "collection"
)
const (
PoolName PoolOrder = "name"
CreatedAt PoolOrder = "created_at"
UpdatedAt PoolOrder = "updated_at"
PostCount PoolOrder = "post_count"
)
type Pool struct {
ID int64 `json:"id" csv:"id"`
Name string `json:"name" csv:"name"`
CreatedAt string `json:"created_at" csv:"created_at"`
UpdatedAt string `json:"updated_at" csv:"updated_at"`
CreatorID int64 `json:"creator_id" csv:"creator_id"`
Description string `json:"description" csv:"description"`
IsActive bool `json:"is_active" csv:"is_active"`
Category PoolCategory `json:"category" csv:"category"`
PostIDS PoolIDs `json:"post_ids" csv:"post_ids"`
CreatorName string `json:"creator_name" csv:"-"`
PostCount int64 `json:"post_count" csv:"-"`
}
// UnmarshalCSV parses a CSV-formatted string containing pool IDs and populates the PoolIDs receiver.
//
// This method is designed to unmarshal a CSV-formatted string, where pool IDs are separated by commas.
// It trims the surrounding curly braces and splits the string to extract individual pool IDs.
// The parsed IDs are then converted to int64 and assigned to the PoolIDs receiver.
//
// Parameters:
// - csv: The CSV-formatted string containing pool IDs.
//
// Returns:
// - error: An error encountered during the unmarshaling process, if any.
func (poolIDs *PoolIDs) UnmarshalCSV(csv string) error {
// Trim the surrounding curly braces
csv = strings.TrimPrefix(csv, "{")
csv = strings.TrimSuffix(csv, "}")
// Split the CSV string into individual pool IDs
ids := strings.Split(csv, ",")
var localPoolIDs PoolIDs
// Iterate through each ID, parse it to int64, and append to the localPoolIDs
for _, id := range ids {
if id != "" {
int64ID, err := strconv.ParseInt(id, 10, 64)
if err != nil {
return fmt.Errorf("failed to parse pool ID '%s': %v", id, err)
}
localPoolIDs = append(localPoolIDs, int64ID)
}
}
// Assign the parsed IDs to the receiver
*poolIDs = localPoolIDs
return nil
}

View File

@ -1,93 +1,93 @@
package model
type PostID int64
type PostResponse struct {
Post Post `json:"post"`
Posts []Post `json:"posts"`
}
type Post struct {
ID PostID `json:"id"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
File File `json:"file"`
Preview Preview `json:"preview"`
Sample Sample `json:"sample"`
Score Score `json:"score"`
Tags Tags `json:"tags"`
LockedTags []interface{} `json:"locked_tags"`
ChangeSeq int64 `json:"change_seq"`
Flags Flags `json:"flags"`
Rating string `json:"rating"`
FavCount int64 `json:"fav_count"`
Sources []string `json:"sources"`
Pools []interface{} `json:"pools"`
Relationships Relationships `json:"relationships"`
ApproverID interface{} `json:"approver_id"`
UploaderID int64 `json:"uploader_id"`
Description string `json:"description"`
CommentCount int64 `json:"comment_count"`
IsFavorited bool `json:"is_favorited"`
HasNotes bool `json:"has_notes"`
Duration interface{} `json:"duration"`
}
type File struct {
Width int64 `json:"width"`
Height int64 `json:"height"`
EXT string `json:"ext"`
Size int64 `json:"size"`
Md5 string `json:"md5"`
URL string `json:"url"`
}
type Flags struct {
Pending bool `json:"pending"`
Flagged bool `json:"flagged"`
NoteLocked bool `json:"note_locked"`
StatusLocked bool `json:"status_locked"`
RatingLocked bool `json:"rating_locked"`
Deleted bool `json:"deleted"`
}
type Preview struct {
Width int64 `json:"width"`
Height int64 `json:"height"`
URL string `json:"url"`
}
type Relationships struct {
ParentID interface{} `json:"parent_id"`
HasChildren bool `json:"has_children"`
HasActiveChildren bool `json:"has_active_children"`
Children []interface{} `json:"children"`
}
type Sample struct {
Has bool `json:"has"`
Height int64 `json:"height"`
Width int64 `json:"width"`
URL string `json:"url"`
Alternates Alternates `json:"alternates"`
}
type Alternates struct {
}
type Score struct {
Up int64 `json:"up"`
Down int64 `json:"down"`
Total int64 `json:"total"`
}
type Tags struct {
General []string `json:"general"`
Artist []string `json:"artist"`
Copyright []string `json:"copyright"`
Character []string `json:"character"`
Species []string `json:"species"`
Invalid []string `json:"invalid"`
Meta []string `json:"meta"`
Lore []string `json:"lore"`
}
package model
type PostID int64
type PostResponse struct {
Post Post `json:"post"`
Posts []Post `json:"posts"`
}
type Post struct {
ID PostID `json:"id" csv:"id"`
CreatedAt string `json:"created_at" csv:"created_at"`
UpdatedAt string `json:"updated_at" csv:"updated_at"`
File File `json:"file" csv:"file"`
Preview Preview `json:"preview" csv:"-"`
Sample Sample `json:"sample" csv:"-"`
Score Score `json:"score" csv:"score"`
Tags Tags `json:"tags" csv:"tag_string"`
LockedTags []interface{} `json:"locked_tags" csv:"locked_tags"`
ChangeSeq int64 `json:"change_seq" csv:"change_seq"`
Flags Flags `json:"flags" csv:"-"`
Rating string `json:"rating" csv:"rating"`
FavCount int64 `json:"fav_count" csv:"fav_count"`
Sources []string `json:"sources" csv:"source"`
Pools []interface{} `json:"pools" csv:"-"`
Relationships Relationships `json:"relationships" csv:"-"`
ApproverID UserID `json:"approver_id" csv:"approver_id"`
UploaderID UserID `json:"uploader_id" csv:"uploader_id"`
Description string `json:"description" csv:"description"`
CommentCount int64 `json:"comment_count" csv:"comment_count"`
IsFavorited bool `json:"is_favorited" csv:"-"`
HasNotes bool `json:"has_notes" csv:"-"`
Duration interface{} `json:"duration" csv:"duration"`
}
type File struct {
Width int64 `json:"width" csv:"image_width"`
Height int64 `json:"height" csv:"image_height"`
EXT string `json:"ext" csv:"file_ext"`
Size int64 `json:"size" csv:"file_size"`
Md5 string `json:"md5" csv:"md5"`
URL string `json:"url" csv:"-"`
}
type Flags struct {
Pending bool `json:"pending" csv:"is_pending"`
Flagged bool `json:"flagged" csv:"is_flagged"`
NoteLocked bool `json:"note_locked" csv:"is_note_locked"`
StatusLocked bool `json:"status_locked" csv:"is_status_locked"`
RatingLocked bool `json:"rating_locked" csv:"is_rating_locked"`
Deleted bool `json:"deleted" csv:"is_deleted"`
}
type Preview struct {
Width int64 `json:"width" csv:"-"`
Height int64 `json:"height" csv:"-"`
URL string `json:"url" csv:"-"`
}
type Relationships struct {
ParentID PostID `json:"parent_id" csv:"parent_id"`
HasChildren bool `json:"has_children" csv:"-"`
HasActiveChildren bool `json:"has_active_children" csv:"-"`
Children []PostID `json:"children" csv:"-"`
}
type Sample struct {
Has bool `json:"has" csv:"-"`
Height int64 `json:"height" csv:"-"`
Width int64 `json:"width" csv:"-"`
URL string `json:"url" csv:"-"`
Alternates Alternates `json:"alternates" csv:"-"`
}
type Alternates struct {
}
type Score struct {
Up int64 `json:"up" csv:"up_score"`
Down int64 `json:"down" csv:"down_score"`
Total int64 `json:"total" csv:"-"`
}
type Tags struct {
General []string `json:"general" csv:"-"`
Artist []string `json:"artist" csv:"-"`
Copyright []string `json:"copyright" csv:"-"`
Character []string `json:"character" csv:"-"`
Species []string `json:"species" csv:"-"`
Invalid []string `json:"invalid" csv:"-"`
Meta []string `json:"meta" csv:"-"`
Lore []string `json:"lore" csv:"-"`
}

View File

@ -1,26 +1,26 @@
package model
type TagCategory int
const (
General TagCategory = iota
Artist
Copyright TagCategory = iota + 1
Character
Species
Invalide
Meta
Lore
)
type Tag struct {
ID int64 `json:"id"`
Name string `json:"name"`
PostCount int64 `json:"post_count"`
RelatedTags string `json:"related_tags"`
RelatedTagsUpdatedAt string `json:"related_tags_updated_at"`
Category TagCategory `json:"category"`
IsLocked bool `json:"is_locked"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
package model
type TagCategory int
const (
General TagCategory = iota
Artist
Copyright TagCategory = iota + 1
Character
Species
Invalide
Meta
Lore
)
type Tag struct {
ID int64 `json:"id"`
Name string `json:"name"`
PostCount int64 `json:"post_count"`
RelatedTags string `json:"related_tags"`
RelatedTagsUpdatedAt string `json:"related_tags_updated_at"`
Category TagCategory `json:"category"`
IsLocked bool `json:"is_locked"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}

View File

@ -1,51 +1,51 @@
package model
type UserID int64
type UserLevel int
type Order string
const (
Anonymus UserLevel = 0
Blocked UserLevel = 10
Member UserLevel = 20
Privilaged UserLevel = 30
FormerStaff UserLevel = 34
Janitor UserLevel = 35
Moderator UserLevel = 40
Admin UserLevel = 50
)
const (
JoinDate Order = "date"
UserName Order = "name"
PostUploadCount Order = "post_upload_count"
NoteCount Order = "note_count"
PostUpdateCount Order = "post_upload_count"
)
type User struct {
WikiPageVersionCount int64 `json:"wiki_page_version_count"`
ArtistVersionCount int64 `json:"artist_version_count"`
PoolVersionCount int64 `json:"pool_version_count"`
ForumPostCount int64 `json:"forum_post_count"`
CommentCount int64 `json:"comment_count"`
FlagCount int64 `json:"flag_count"`
FavoriteCount int64 `json:"favorite_count"`
PositiveFeedbackCount int64 `json:"positive_feedback_count"`
NeutralFeedbackCount int64 `json:"neutral_feedback_count"`
NegativeFeedbackCount int64 `json:"negative_feedback_count"`
UploadLimit int64 `json:"upload_limit"`
ID UserID `json:"id"`
CreatedAt string `json:"created_at"`
Name string `json:"name"`
Level UserLevel `json:"level"`
BaseUploadLimit int64 `json:"base_upload_limit"`
PostUploadCount int64 `json:"post_upload_count"`
PostUpdateCount int64 `json:"post_update_count"`
NoteUpdateCount int64 `json:"note_update_count"`
IsBanned bool `json:"is_banned"`
CanApprovePosts bool `json:"can_approve_posts"`
CanUploadFree bool `json:"can_upload_free"`
LevelString string `json:"level_string"`
AvatarID PostID `json:"avatar_id"`
}
package model
type UserID int64
type UserLevel int
type Order string
const (
Anonymus UserLevel = 0
Blocked UserLevel = 10
Member UserLevel = 20
Privilaged UserLevel = 30
FormerStaff UserLevel = 34
Janitor UserLevel = 35
Moderator UserLevel = 40
Admin UserLevel = 50
)
const (
JoinDate Order = "date"
UserName Order = "name"
PostUploadCount Order = "post_upload_count"
NoteCount Order = "note_count"
PostUpdateCount Order = "post_upload_count"
)
type User struct {
WikiPageVersionCount int64 `json:"wiki_page_version_count"`
ArtistVersionCount int64 `json:"artist_version_count"`
PoolVersionCount int64 `json:"pool_version_count"`
ForumPostCount int64 `json:"forum_post_count"`
CommentCount int64 `json:"comment_count"`
FlagCount int64 `json:"flag_count"`
FavoriteCount int64 `json:"favorite_count"`
PositiveFeedbackCount int64 `json:"positive_feedback_count"`
NeutralFeedbackCount int64 `json:"neutral_feedback_count"`
NegativeFeedbackCount int64 `json:"negative_feedback_count"`
UploadLimit int64 `json:"upload_limit"`
ID UserID `json:"id"`
CreatedAt string `json:"created_at"`
Name string `json:"name"`
Level UserLevel `json:"level"`
BaseUploadLimit int64 `json:"base_upload_limit"`
PostUploadCount int64 `json:"post_upload_count"`
PostUpdateCount int64 `json:"post_update_count"`
NoteUpdateCount int64 `json:"note_update_count"`
IsBanned bool `json:"is_banned"`
CanApprovePosts bool `json:"can_approve_posts"`
CanUploadFree bool `json:"can_upload_free"`
LevelString string `json:"level_string"`
AvatarID PostID `json:"avatar_id"`
}

View File

@ -1,4 +1,4 @@
package utils
// E621_MAX_POST_COUNT is the maximum allowable post count for E621.
const E621_MAX_POST_COUNT = 320
package utils
// E621_MAX_POST_COUNT is the maximum allowable post count for e621.
const E621_MAX_POST_COUNT = 320

View File

@ -1,106 +1,123 @@
package utils
import "fmt"
// StatusCodesToError maps HTTP status codes to corresponding error types.
func StatusCodesToError(statusCode int) error {
var err error
switch statusCode {
case 403:
err = AccessDeniedError{}
case 404:
err = NotFoundError{}
case 412:
err = PreconditionFailedError{}
case 421:
err = RateLimitReachedError{}
case 424:
err = InvalidParametersError{}
case 500:
err = InternalServerError{}
case 502:
err = BadGatewayError{}
case 503:
err = ServiceUnavailableError{}
default:
err = fmt.Errorf("unhandled status code: %d", statusCode)
}
return err
}
// AccessDeniedError represents an "Access Denied" error.
type AccessDeniedError struct{}
func (_ AccessDeniedError) Error() string {
return "access denied"
}
// NotFoundError represents a "Not Found" error.
type NotFoundError struct{}
func (_ NotFoundError) Error() string {
return "not found"
}
// PreconditionFailedError represents a "Precondition Failed" error.
type PreconditionFailedError struct{}
func (_ PreconditionFailedError) Error() string {
return "precondition failed"
}
// RateLimitReachedError represents a "Rate Limit Reached" error.
type RateLimitReachedError struct{}
func (_ RateLimitReachedError) Error() string {
return "rate limit reached"
}
// InvalidParametersError represents an "Invalid Parameters" error.
type InvalidParametersError struct{}
func (_ InvalidParametersError) Error() string {
return "invalid parameters"
}
// InternalServerError represents an "Internal Server Error" error.
type InternalServerError struct{}
func (_ InternalServerError) Error() string {
return "internal server error"
}
// BadGatewayError represents a "Bad Gateway" error.
type BadGatewayError struct{}
func (_ BadGatewayError) Error() string {
return "bad gateway"
}
// ServiceUnavailableError represents a "Service Unavailable" error.
type ServiceUnavailableError struct{}
func (_ ServiceUnavailableError) Error() string {
return "service unavailable"
}
// UnknownError represents an "Unknown" error.
type UnknownError struct{}
func (_ UnknownError) Error() string {
return "unknown error"
}
// OriginConnectionTimeOutError represents an "Origin Connection Time-Out" error.
type OriginConnectionTimeOutError struct{}
func (_ OriginConnectionTimeOutError) Error() string {
return "origin connection time-out"
}
// SSLHandshakeFailedError represents an "SSL Handshake Failed" error.
type SSLHandshakeFailedError struct{}
func (_ SSLHandshakeFailedError) Error() string {
return "ssl handshake failed"
}
package utils
import "fmt"
// StatusCodesToError maps HTTP status codes to corresponding error types.
//
// Parameters:
// - statusCode: The HTTP status code to be mapped to an error type.
//
// Returns:
// - error: An error representing the mapped HTTP status code.
func StatusCodesToError(statusCode int) error {
var err error
switch statusCode {
case 403:
err = AccessDeniedError{}
case 404:
err = NotFoundError{}
case 412:
err = PreconditionFailedError{}
case 421:
err = RateLimitReachedError{}
case 424:
err = InvalidParametersError{}
case 500:
err = InternalServerError{}
case 502:
err = BadGatewayError{}
case 503:
err = ServiceUnavailableError{}
default:
err = fmt.Errorf("unhandled status code: %d", statusCode)
}
return err
}
// AccessDeniedError represents an "Access Denied" error.
type AccessDeniedError struct{}
// Error returns the error message for AccessDeniedError.
func (_ AccessDeniedError) Error() string {
return "access denied"
}
// NotFoundError represents a "Not Found" error.
type NotFoundError struct{}
// Error returns the error message for NotFoundError.
func (_ NotFoundError) Error() string {
return "not found"
}
// PreconditionFailedError represents a "Precondition Failed" error.
type PreconditionFailedError struct{}
// Error returns the error message for PreconditionFailedError.
func (_ PreconditionFailedError) Error() string {
return "precondition failed"
}
// RateLimitReachedError represents a "Rate Limit Reached" error.
type RateLimitReachedError struct{}
// Error returns the error message for RateLimitReachedError.
func (_ RateLimitReachedError) Error() string {
return "rate limit reached"
}
// InvalidParametersError represents an "Invalid Parameters" error.
type InvalidParametersError struct{}
// Error returns the error message for InvalidParametersError.
func (_ InvalidParametersError) Error() string {
return "invalid parameters"
}
// InternalServerError represents an "Internal Server Error" error.
type InternalServerError struct{}
// Error returns the error message for InternalServerError.
func (_ InternalServerError) Error() string {
return "internal server error"
}
// BadGatewayError represents a "Bad Gateway" error.
type BadGatewayError struct{}
// Error returns the error message for BadGatewayError.
func (_ BadGatewayError) Error() string {
return "bad gateway"
}
// ServiceUnavailableError represents a "Service Unavailable" error.
type ServiceUnavailableError struct{}
// Error returns the error message for ServiceUnavailableError.
func (_ ServiceUnavailableError) Error() string {
return "service unavailable"
}
// UnknownError represents an "Unknown" error.
type UnknownError struct{}
// Error returns the error message for UnknownError.
func (_ UnknownError) Error() string {
return "unknown error"
}
// OriginConnectionTimeOutError represents an "Origin Connection Time-Out" error.
type OriginConnectionTimeOutError struct{}
// Error returns the error message for OriginConnectionTimeOutError.
func (_ OriginConnectionTimeOutError) Error() string {
return "origin connection time-out"
}
// SSLHandshakeFailedError represents an "SSL Handshake Failed" error.
type SSLHandshakeFailedError struct{}
// Error returns the error message for SSLHandshakeFailedError.
func (_ SSLHandshakeFailedError) Error() string {
return "ssl handshake failed"
}

53
pkg/e621/utils/helper.go Normal file
View File

@ -0,0 +1,53 @@
package utils
import (
"encoding/json"
"os"
)
// SliceFilter filters elements of a generic type from a slice based on a provided filter function.
//
// Parameters:
// - slice: The input slice containing elements of type T.
// - filter: A function that takes an element of type T and returns a boolean indicating whether to include the element in the result.
//
// Returns:
// - ret: A slice containing elements that satisfy the filtering condition.
func SliceFilter[T any](slice []T, filter func(T) bool) (ret []T) {
for _, s := range slice {
if filter(s) {
ret = append(ret, s)
}
}
return
}
// LoadJsonTestData decodes JSON data from a file and populates a variable of a generic type T.
//
// Parameters:
// - testDataPath: The file path to the JSON data.
//
// Returns:
// - T: A variable of type T populated with the decoded JSON data.
// - error: An error, if any, encountered during file opening, decoding, or closing.
func LoadJsonTestData[T any](testDataPath string) (T, error) {
// Create a variable to store the decoded JSON data
var jsonData T
// Open the JSON file
file, err := os.Open(testDataPath)
if err != nil {
return jsonData, err
}
defer file.Close()
// Create a decoder
decoder := json.NewDecoder(file)
// Decode the JSON data into the struct
if err := decoder.Decode(&jsonData); err != nil {
return jsonData, err
}
return jsonData, nil
}

View File

@ -1,28 +0,0 @@
package utils
import (
"encoding/json"
"os"
)
func LoadJsonTestData[T any](testDataPath string) (T, error) {
// Create a variable to store the decoded JSON data
var jsonData T
// Open the JSON file
file, err := os.Open(testDataPath)
if err != nil {
return jsonData, err
}
defer file.Close()
// Create a decoder
decoder := json.NewDecoder(file)
// Decode the JSON data into the struct
if err := decoder.Decode(&jsonData); err != nil {
return jsonData, err
}
return jsonData, nil
}

View File

@ -1,15 +1,15 @@
{
"id": 1337,
"created_at": "2009-05-19T13:30:28.360-04:00",
"updated_at": "2009-06-02T16:52:06.418-04:00",
"creator_id": 2942,
"x": 163,
"y": 718,
"width": 99,
"height": 47,
"version": 2,
"is_active": false,
"post_id": 31570,
"body": "BORANGE MORE LIKE IT",
"creator_name": "DahWuffie"
{
"id": 1337,
"created_at": "2009-05-19T13:30:28.360-04:00",
"updated_at": "2009-06-02T16:52:06.418-04:00",
"creator_id": 2942,
"x": 163,
"y": 718,
"width": 99,
"height": 47,
"version": 2,
"is_active": false,
"post_id": 31570,
"body": "BORANGE MORE LIKE IT",
"creator_name": "DahWuffie"
}

File diff suppressed because it is too large Load Diff

View File

@ -1,38 +1,38 @@
{
"id": 1,
"name": "Furry_Boys_by_Trump/Team_Shuffle",
"created_at": "2008-10-30T03:42:29.962-04:00",
"updated_at": "2023-10-24T06:58:59.488-04:00",
"creator_id": 7,
"description": "Furry Boys Comic",
"is_active": false,
"category": "series",
"post_ids": [
3294,
3295,
3296,
3297,
3298,
3299,
3300,
3303,
3306,
3304,
3305,
3307,
3309,
3308,
3313,
3312,
3316,
3314,
3315,
3321,
3317,
3319,
3318,
3320
],
"creator_name": "user_7",
"post_count": 24
{
"id": 1,
"name": "Furry_Boys_by_Trump/Team_Shuffle",
"created_at": "2008-10-30T03:42:29.962-04:00",
"updated_at": "2023-10-24T06:58:59.488-04:00",
"creator_id": 7,
"description": "Furry Boys Comic",
"is_active": false,
"category": "series",
"post_ids": [
3294,
3295,
3296,
3297,
3298,
3299,
3300,
3303,
3306,
3304,
3305,
3307,
3309,
3308,
3313,
3312,
3316,
3314,
3315,
3321,
3317,
3319,
3318,
3320
],
"creator_name": "user_7",
"post_count": 24
}

File diff suppressed because it is too large Load Diff

View File

@ -1,111 +1,111 @@
{
"post": {
"id": 1337,
"created_at": "2007-02-23T22:14:42.048-05:00",
"updated_at": "2023-10-20T01:59:09.423-04:00",
"file": {
"width": 790,
"height": 748,
"ext": "jpg",
"size": 156917,
"md5": "4e7586f0666a7c735b2f9e1ccd18bc68",
"url": "https://static1.e621.net/data/4e/75/4e7586f0666a7c735b2f9e1ccd18bc68.jpg"
},
"preview": {
"width": 150,
"height": 142,
"url": "https://static1.e621.net/data/preview/4e/75/4e7586f0666a7c735b2f9e1ccd18bc68.jpg"
},
"sample": {
"has": false,
"height": 748,
"width": 790,
"url": "https://static1.e621.net/data/4e/75/4e7586f0666a7c735b2f9e1ccd18bc68.jpg",
"alternates": {}
},
"score": {
"up": 46,
"down": -4,
"total": 42
},
"tags": {
"general": [
"\u003c3",
"anthro",
"blush",
"bottomwear",
"briefs",
"chibi",
"clothed",
"clothing",
"dialogue",
"ear_piercing",
"footwear",
"funny_post_number",
"fur",
"group",
"hair",
"humor",
"legwear",
"male",
"pants",
"piercing",
"pink_hair",
"reluctant",
"shirt",
"simple_background",
"socks",
"text",
"topless",
"topwear",
"underwear"
],
"artist": [
"sneakerfox"
],
"copyright": [],
"character": [],
"species": [
"canid",
"canine",
"fox",
"mammal",
"mephitid",
"skunk"
],
"invalid": [],
"meta": [
"2003",
"english_text"
],
"lore": []
},
"locked_tags": [],
"change_seq": 42512291,
"flags": {
"pending": false,
"flagged": false,
"note_locked": false,
"status_locked": false,
"rating_locked": false,
"deleted": false
},
"rating": "s",
"fav_count": 84,
"sources": [],
"pools": [],
"relationships": {
"parent_id": null,
"has_children": false,
"has_active_children": false,
"children": []
},
"approver_id": null,
"uploader_id": 17633,
"description": "",
"comment_count": 6,
"is_favorited": false,
"has_notes": false,
"duration": null
}
{
"post": {
"id": 1337,
"created_at": "2007-02-23T22:14:42.048-05:00",
"updated_at": "2023-10-20T01:59:09.423-04:00",
"file": {
"width": 790,
"height": 748,
"ext": "jpg",
"size": 156917,
"md5": "4e7586f0666a7c735b2f9e1ccd18bc68",
"url": "https://static1.e621.net/data/4e/75/4e7586f0666a7c735b2f9e1ccd18bc68.jpg"
},
"preview": {
"width": 150,
"height": 142,
"url": "https://static1.e621.net/data/preview/4e/75/4e7586f0666a7c735b2f9e1ccd18bc68.jpg"
},
"sample": {
"has": false,
"height": 748,
"width": 790,
"url": "https://static1.e621.net/data/4e/75/4e7586f0666a7c735b2f9e1ccd18bc68.jpg",
"alternates": {}
},
"score": {
"up": 46,
"down": -4,
"total": 42
},
"tags": {
"general": [
"\u003c3",
"anthro",
"blush",
"bottomwear",
"briefs",
"chibi",
"clothed",
"clothing",
"dialogue",
"ear_piercing",
"footwear",
"funny_post_number",
"fur",
"group",
"hair",
"humor",
"legwear",
"male",
"pants",
"piercing",
"pink_hair",
"reluctant",
"shirt",
"simple_background",
"socks",
"text",
"topless",
"topwear",
"underwear"
],
"artist": [
"sneakerfox"
],
"copyright": [],
"character": [],
"species": [
"canid",
"canine",
"fox",
"mammal",
"mephitid",
"skunk"
],
"invalid": [],
"meta": [
"2003",
"english_text"
],
"lore": []
},
"locked_tags": [],
"change_seq": 42512291,
"flags": {
"pending": false,
"flagged": false,
"note_locked": false,
"status_locked": false,
"rating_locked": false,
"deleted": false
},
"rating": "s",
"fav_count": 84,
"sources": [],
"pools": [],
"relationships": {
"parent_id": null,
"has_children": false,
"has_active_children": false,
"children": []
},
"approver_id": null,
"uploader_id": 17633,
"description": "",
"comment_count": 6,
"is_favorited": false,
"has_notes": false,
"duration": null
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,11 +1,11 @@
{
"id": 1337,
"name": "clothed",
"post_count": 945399,
"related_tags": "clothed 300 clothing 300 mammal 255 anthro 242 female 200 hi_res 197 solo 154 breasts 153 hair 152 male 140 fur 121 duo 102 genitals 101 digital_media_(artwork) 97 canid 88 topwear 88 bodily_fluids 87 text 86 canine 84 simple_background 82 big_breasts 79 smile 79 open_mouth 76 tail 76 felid 75",
"related_tags_updated_at": "2023-10-04T15:01:19.597-04:00",
"category": 0,
"is_locked": false,
"created_at": "2020-03-05T05:49:37.994-05:00",
"updated_at": "2023-10-04T15:01:19.598-04:00"
{
"id": 1337,
"name": "clothed",
"post_count": 945399,
"related_tags": "clothed 300 clothing 300 mammal 255 anthro 242 female 200 hi_res 197 solo 154 breasts 153 hair 152 male 140 fur 121 duo 102 genitals 101 digital_media_(artwork) 97 canid 88 topwear 88 bodily_fluids 87 text 86 canine 84 simple_background 82 big_breasts 79 smile 79 open_mouth 76 tail 76 felid 75",
"related_tags_updated_at": "2023-10-04T15:01:19.597-04:00",
"category": 0,
"is_locked": false,
"created_at": "2020-03-05T05:49:37.994-05:00",
"updated_at": "2023-10-04T15:01:19.598-04:00"
}

File diff suppressed because it is too large Load Diff

View File

@ -1,26 +1,26 @@
{
"wiki_page_version_count": 0,
"artist_version_count": 0,
"pool_version_count": 0,
"forum_post_count": 0,
"comment_count": 1,
"flag_count": 0,
"favorite_count": 1454,
"positive_feedback_count": 0,
"neutral_feedback_count": 0,
"negative_feedback_count": 0,
"upload_limit": 10,
"id": 136501,
"created_at": "2014-04-23T07:08:04.080-04:00",
"name": "Selloo",
"level": 20,
"base_upload_limit": 10,
"post_upload_count": 0,
"post_update_count": 5,
"note_update_count": 0,
"is_banned": false,
"can_approve_posts": false,
"can_upload_free": false,
"level_string": "Member",
"avatar_id": 922595
{
"wiki_page_version_count": 0,
"artist_version_count": 0,
"pool_version_count": 0,
"forum_post_count": 0,
"comment_count": 1,
"flag_count": 0,
"favorite_count": 1454,
"positive_feedback_count": 0,
"neutral_feedback_count": 0,
"negative_feedback_count": 0,
"upload_limit": 10,
"id": 136501,
"created_at": "2014-04-23T07:08:04.080-04:00",
"name": "Selloo",
"level": 20,
"base_upload_limit": 10,
"post_upload_count": 0,
"post_update_count": 5,
"note_update_count": 0,
"is_banned": false,
"can_approve_posts": false,
"can_upload_free": false,
"level_string": "Member",
"avatar_id": 922595
}

File diff suppressed because it is too large Load Diff