├── .buildpacks
├── .dockerignore
├── .example_env
├── .github
└── workflows
│ └── ci.yml
├── .gitignore
├── Cargo.lock
├── Cargo.toml
├── Dockerfile
├── LICENSE
├── Procfile
├── README.md
├── docs
├── average_auction_example.json
├── average_bin_example.json
├── average_example.json
├── docs.md
├── lowestbin_example.json
├── pets_example.json
├── query_example_1.json
├── query_example_2.json
├── query_items_example.json
└── underbin_example.json
└── src
├── api_handler.rs
├── config.rs
├── lib.rs
├── main.rs
├── server.rs
├── statics.rs
├── structs.rs
├── utils.rs
└── webhook.rs
/.buildpacks:
--------------------------------------------------------------------------------
1 | https://github.com/emk/heroku-buildpack-rust
2 |
--------------------------------------------------------------------------------
/.dockerignore:
--------------------------------------------------------------------------------
1 | *
2 | !src/
3 | !Cargo.lock
4 | !Cargo.toml
--------------------------------------------------------------------------------
/.example_env:
--------------------------------------------------------------------------------
1 | BASE_URL=
2 | PORT=
3 | API_KEY=
4 | ADMIN_API_KEY=
5 | POSTGRES_URL=
6 | WEBHOOK_URL=
7 | FEATURES=
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: Rust
2 |
3 | on:
4 | push:
5 | branches: [ main ]
6 | pull_request:
7 | branches: [ main ]
8 |
9 | env:
10 | CARGO_TERM_COLOR: always
11 |
12 | jobs:
13 | build:
14 | runs-on: ubuntu-latest
15 | steps:
16 | - uses: actions/checkout@v4
17 | - name: Build
18 | run: cargo build --verbose
19 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | /target
2 | *.log
3 | dev
4 | .DS_Store
5 | .env
6 | lowestbin.json
7 | underbin.json
8 | query_items.json
--------------------------------------------------------------------------------
/Cargo.toml:
--------------------------------------------------------------------------------
1 | [package]
2 | name = "query_api"
3 | version = "3.1.0"
4 | edition = "2021"
5 | repository = "https://github.com/kr45732/rust-query-api"
6 | readme = "README.md"
7 |
8 | [dependencies]
9 | # Runtime
10 | tokio = { version = "1.38.0", features = ["macros", "rt-multi-thread"] }
11 |
12 | # Serde
13 | serde = { version = "1.0.203", features = ["derive"] }
14 | serde_json = "1.0.117"
15 |
16 | # Database
17 | deadpool-postgres = "0.14.0"
18 | tokio-postgres = { version = "0.7.10", features = ["with-serde_json-1"] }
19 | postgres-types = { version = "0.2.6", features = ["derive", "array-impls"] }
20 |
21 | # HTTP
22 | reqwest = { version = "0.12.5", features = ["json", "gzip"] }
23 | hyper = { version = "1.3.1", features = ["full"] }
24 | hyper-util = { version = "0.1.5", features = ["full"] }
25 | http-body-util = "0.1.2"
26 |
27 | # Logging
28 | log = "0.4.21"
29 | simplelog = "0.12.2"
30 |
31 | # Misc
32 | dashmap = { version = "6.0.1", features = ["serde"] }
33 | lazy_static = "1.5.0"
34 | dotenv = "0.15.0"
35 | futures = "0.3.30"
36 | hematite-nbt = "0.5.2"
37 | base64 = "0.22.1"
38 | regex = "1.10.5"
39 |
40 | [profile.release]
41 | codegen-units = 1
42 | debug = true
43 | lto = true
44 |
--------------------------------------------------------------------------------
/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM rust:1.79.0
2 |
3 | WORKDIR /app
4 | COPY . .
5 |
6 | RUN cargo build --release
7 |
8 | CMD ./target/release/query_api
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published by
637 | the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | web: PORT=$PORT ./target/release/query_api
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Rust Query API
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 | A versatile API facade for the Hypixel Auction API written in Rust. The entire auction house is fetched every minute with NBT parsing and inserted into a PostgreSQL database in **less than a second** and with low memory usage (varies depending on enabled features, network speed, hardware, and latency of the Hypixel API)! You can query by auction UUID, auctioneer, end time, item name, item tier, item id, price, enchants, bin and bids. You can sort by the item's starting price or highest bid. You can track the average price of each unique pet-level-rarity combination. You can track the lowest prices of all bins. It also can track new bins that are at least one million lower than previous bins. It can track the average auction and average bin prices and sales for up to seven days with custom 'averaging methods'.
13 |
14 | ## Set Up
15 | ### Prerequisites
16 | - [Rust](https://www.rust-lang.org/tools/install)
17 | - [Cargo](https://doc.rust-lang.org/cargo/getting-started/installation.html)
18 | - [PostgreSQL database](https://www.postgresql.org/)
19 | - [Discord](https://discord.com/)
20 |
21 | ### Steps
22 | - Clone the repository
23 | - Rename the `.example_env` file to `.env` and fill out required fields **OR** set required fields using environment variables
24 | - Run `cargo run --release` (may take some time to build)
25 | - Use the API!
26 |
27 | ### Configuration Fields or Environment Variables
28 | - `BASE_URL`: Base address to bind to (e.g. 0.0.0.0)
29 | - `PORT`: Port to bind to (e.g. 8000)
30 | - Online hosts will automatically set this
31 | - `API_KEY`: Optional key needed to access this API (NOT a Hypixel API key)
32 | - `ADMIN_API_KEY`: Optional admin key required to use raw SQL parameters (defaults to the API_KEY)
33 | - `POSTGRES_URL`: Full URL of a PostgreSQL database (should look like `postgres://[user]:[password]@[host]:[port]/[dbname]`)
34 | - `WEBHOOK_URL`: Optional Discord webhook URL for logging
35 | - `FEATURES`: Features (QUERY, PETS, LOWESTBIN, UNDERBIN, AVERAGE_AUCTION, AVERAGE_BIN) you want enabled separated with a '+'
36 | - `DEBUG`: If the API should log to files and stdout (defaults to false)
37 |
38 | ## Usage
39 | ### Endpoints
40 | - `/query`
41 | - `/pets`
42 | - `/lowestbin`
43 | - `/underbin`
44 | - `/average_auction`
45 | - `/average_bin`
46 | - `/average`
47 | - `/query_items`
48 |
49 | ### Documentation & Examples
50 | - See documentation and examples [here](docs/docs.md)
51 |
52 | ## Free Hosting
53 | ### Deploy On Railway
54 | [](https://railway.app/new/template?template=https://github.com/kr45732/rust-query-api&plugins=postgresql&envs=BASE_URL,API_KEY,ADMIN_API_KEY,POSTGRES_URL,WEBHOOK_URL,FEATURES&optionalEnvs=WEBHOOK_URL,ADMIN_API_KEY&BASE_URLDesc=The+base+URL+of+the+domain.+Do+not+modify+this&API_KEYDesc=Key+needed+to+access+this+API+(NOT+a+Hypixel+API+key)&ADMIN_API_KEYDesc=Admin+key+required+to+use+raw+SQL+parameters.+Will+default+to+the+API_KEY+if+not+provided&POSTGRES_URLDesc=Full+URL+of+a+PostgreSQL+database.+No+need+to+modify+this+unless+you+are+using+your+own+database+since+Railway+already+provides+this+for+you.&WEBHOOK_URLDesc=Discord+webhook+URL+for+logging&FEATURESDesc=The+features+(QUERY,+PETS,+LOWESTBIN,+UNDERBIN,+AVERAGE_AUCTION,+AVERAGE_BIN)+you+want+enabled+separated+with+commas&BASE_URLDefault=0.0.0.0&POSTGRES_URLDefault=$%7B%7BDATABASE_URL%7D%7D&FEATURESDefault=QUERY,LOWESTBIN,AVERAGE_AUCTION,AVERAGE_BIN&referralCode=WrEybV)
55 |
56 | ### Deploy On Gigalixir
57 | Steps to deploy on [Gigalixir](https://gigalixir.com/):
58 | 1. Clone repository
59 | 2. Install gigalixir CLI: `pip3 install gigalixir`
60 | 3. Sign up: `gigalixir signup`
61 | 4. Create app: `gigalixir create -n NAME`
62 | 5. Set environment variables: `gigalixir config:set key=value`
63 | 6. Deploy app: `git push gigalixir`
64 | 7. Acess at [https://NAME.gigalixirapp.com/](https://NAME.gigalixirapp.com/)
65 |
66 | ### Free PostgreSQL Datbase
67 | The free tier of [Supabase](https://supabase.com/) is a great option with with plenty of storage and good performance.
68 |
69 | ## Todo
70 | - Improve underbin
71 | - Improve speed of database transactions
--------------------------------------------------------------------------------
/docs/docs.md:
--------------------------------------------------------------------------------
1 | # Documentation
2 | ## Query
3 | - `key` - key to access the API
4 | - `query` - raw SQL to be executed. Requires the admin key
5 | - `item_name` - filter by name
6 | - `tier` - filter by tier
7 | - `item_id` - filter by id
8 | - `internal_id` - filter by internal id
9 | - `enchants` - filter by comma separated list of enchants
10 | - `attributes` - filter by comma separated list of attributes. Each attribute is formatted as ATTRIBUTE_SHARD_{NAME};{LEVEL}
11 | - `end` - filter if end time is after this (epoch timestamp in milliseconds)
12 | - `bin` - filter by bin (true) or regular auction (false) or any (do not provide parameter)
13 | - `potato_books` - filter by potato books count (hot and fuming potato books are combined)
14 | - `stars` - filter by number of stars
15 | - `farming_for_dummies` - filter by farming for dummies count
16 | - `transmission_tuner` - filter by transmission tuner count
17 | - `mana_disintegrator` - filter by mana disintegrator count
18 | - `reforge` - filter by reforge name
19 | - `rune` - filter by rune
20 | - `skin` - filter by item skin
21 | - `power_scroll` - filter by power scroll
22 | - `drill_upgrade_module` - filter by drill upgrade module
23 | - `drill_fuel_tank` - filter by drill fuel tank
24 | - `drill_engine` - filter by drill engine
25 | - `dye` - filter by dye
26 | - `accessory_enrichment` - filter by accessory enrichment
27 | - `recombobulated` - filter by recombobulator applied
28 | - `wood_singularity` - filter by wood singularity applied
29 | - `art_of_war` = filter by art of war applied
30 | - `art_of_peace` = filter by art of peace applied
31 | - `etherwarp` - filter by etherwarp applied
32 | - `necron_scrolls` - filter by comma separated list of necron scrolls
33 | - `gemstones` - filter by comma separated list of gemstones. Each gemstone is formatted as SLOT_GEMSTONE (e.g. JADE_0_FINE_JADE_GEM)
34 | - `bids` - filter auctions by the UUID of their bidders
35 | - `sort_by` - sort by 'starting_bid' or 'highest_bid', or 'query'. Sorting by query will return a score indicating the number conditions an item matched
36 | - `sort_order` - sort 'ASC' or 'DESC'
37 | - `limit` - max number of auctions returned (defaults to 1). Limit of 0 will return return all auctions. Limits not between 0 and 500 require the admin key
38 |
39 | ## Pets
40 | - `key` - key to access the API
41 | - `query` - comma separated list of pet names. Each pet name is formatted as: [LVL_#]_NAME_TIER. For tier boosted pets, append _TB
42 |
43 | ## Lowest Bin
44 | - `key` - key to access the API
45 |
46 | ## Under Bin
47 | - `key` - key to access the API
48 |
49 | ## Average Auctions
50 | - `key` - key to access the API
51 | - `time` - unix timestamp, in seconds, for how far back the average auction prices should be calculated. The most is 5 days back
52 | - `step` - how the auction sales should be averaged. For example, 1 would average it by minute, 60 would average it by hour, 1440 would average it by day, and so on
53 | - `center` - measure of center used to determine item prices. Supported methods are 'mean', 'median', 'modified_median'
54 | - `percent` - percent of median (above and below) to average when using 'modified_median' center
55 |
56 | ## Average Bins
57 | - `key` - key to access the API
58 | - `time` - unix timestamp, in seconds, for how far back the average bin prices should be calculated. The most is 5 days back
59 | - `step` - how the bin sales should be averaged. For example, 1 would average it by minute, 60 would average it by hour, 1440 would average it by day, and so on
60 | - `center` - measure of center used to determine item prices. Supported methods are 'mean', 'median', 'modified_median'
61 | - `percent` - percent of median (above and below) to average when using 'modified_median' center
62 |
63 | ## Average Auctions & Bins
64 | - `key` - key to access the API
65 | - `time` - unix timestamp, in seconds, for how far back the average auction & bin prices should be calculated. The most is 5 days back
66 | - `step` - how the auction & bin sales should be averaged. For example, 1 would average it by minute, 60 would average it by hour, 1440 would average it by day, and so on
67 | - `center` - measure of center used to determine item prices. Supported methods are 'mean', 'median', 'modified_median'
68 | - `percent` - percent of median (above and below) to average when using 'modified_median' center
69 |
70 | ## Query Items
71 | - `key` - key to access the API
72 |
73 | # Examples
74 | ### [Query Example #1](query_example_1.json)
75 | - Request: /query?key=KEY&bin=true&item_id=POWER_WITHER_CHESTPLATE&recombobulated=true&stars=5&sort_by=starting_bid&sort_order=ASC&limit=50
76 | - Meaning: find the cheapest 50 bins where the item id is POWER_WITHER_CHESTPLATE, is recombobulated, and has 5 stars. Sort by ascending bin price
77 |
78 | ### [Query Example #2](query_example_2.json)
79 | - Request: /query?key=KEY&bin=true&item_id=POWER_WITHER_CHESTPLATE&recombobulated=true&enchants=GROWTH;6&gemstones=COMBAT_0_FINE_JASPER_GEM&stars=5&sort_by=query&limit=50
80 | - Meaning: find the closest matching bins where the item id is POWER_WITHER_CHESTPLATE, is recombobulated, enchanted with growth 6, have a fine jasper in the combat gemstone slot, and has 5 stars. Sort by ascending bin price and limit to 50 results. Returns a score indicating number of conditions matched
81 |
82 | ### [Pets Example](pets_example.json)
83 | - Request: /pets?key=KEY&query=[LVL_100]_WITHER_SKELETON_LEGENDARY,[LVL_80]_BAL_EPIC,[LVL_96]_ENDER_DRAGON_EPIC_TB
84 | - Meaning: get the average pet prices for a level 100 legendary wither skeleton, a level 80 epic bal, and a level 96 epic ender dragon (tier boosted from epic to legendary)
85 |
86 | ### [Lowestbin Example](lowestbin_example.json)
87 | - Request /lowestbin?key=KEY
88 | - Meaning: get all lowest bins
89 |
90 | ### [Underbin Example](underbin_example.json)
91 | - Request /underbin?key=KEY
92 | - Meaning: get all new bins that make at least one million in profit compared to the lowest bin of the previous API update. Experimental and still being improved
93 |
94 | ### [Average Auction Example](average_auction_example.json)
95 | - Request /average_auction?key=KEY&time=1647830293&step=60
96 | - Meaning: get average auction prices from the unix timestamp 1647830293 to the present. Average sales by hour
97 |
98 | ### [Average Bin Example](average_bin_example.json)
99 | - Request /average_bin?key=KEY&time=1647830293&step=60
100 | - Meaning: get average auction bin from the unix timestamp 1647830293 to the present. Average sales by hour
101 |
102 | ### [Average Example](average_example.json)
103 | - Request /average?key=KEY&time=1647830293&step=60
104 | - Meaning: get the combined average auctions and average bins from the unix timestamp 1647830293 to the present. Average sales by hour
105 |
106 | ### [Query Items Example](query_items_example.json)
107 | - Request /query_items?key=KEY
108 | - Meaning: get a list of all current unique auction names
--------------------------------------------------------------------------------
/docs/pets_example.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "name": "[LVL_96]_ENDER_DRAGON_EPIC_TB",
4 | "price": 318832070
5 | },
6 | {
7 | "name": "[LVL_80]_BAL_EPIC",
8 | "price": 8489854
9 | },
10 | {
11 | "name": "[LVL_100]_WITHER_SKELETON_LEGENDARY",
12 | "price": 9379439
13 | }
14 | ]
--------------------------------------------------------------------------------
/docs/query_example_1.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "uuid": "58d632e6beb2466299f14872fb38d2fe",
4 | "auctioneer": "432d87b5754b43848f338507a0b5ee28",
5 | "end_t": 1685229688482,
6 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
7 | "tier": "MYTHIC",
8 | "item_id": "POWER_WITHER_CHESTPLATE",
9 | "internal_id": "POWER_WITHER_CHESTPLATE",
10 | "starting_bid": 47000000,
11 | "highest_bid": 0,
12 | "bin": true,
13 | "count": 1,
14 | "enchants": [
15 | "PROTECTION;5",
16 | "GROWTH;5"
17 | ],
18 | "potato_books": 10,
19 | "stars": 5,
20 | "reforge": "ancient",
21 | "recombobulated": true
22 | },
23 | {
24 | "uuid": "53eb83b5b2cb456a9159313f956fbfee",
25 | "auctioneer": "a36216a88c664c54a83e2dd101e8c53d",
26 | "end_t": 1685225698151,
27 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
28 | "tier": "MYTHIC",
29 | "item_id": "POWER_WITHER_CHESTPLATE",
30 | "internal_id": "POWER_WITHER_CHESTPLATE",
31 | "starting_bid": 47200000,
32 | "highest_bid": 0,
33 | "bin": true,
34 | "count": 1,
35 | "enchants": [
36 | "PROTECTION;5",
37 | "GROWTH;5",
38 | "REJUVENATE;5"
39 | ],
40 | "potato_books": 10,
41 | "stars": 5,
42 | "reforge": "ancient",
43 | "recombobulated": true
44 | },
45 | {
46 | "uuid": "6b1d014d0e7547a6ba74eca6af47dec2",
47 | "auctioneer": "d68a1583fe4247199b4be0bc498335ae",
48 | "end_t": 1685227179914,
49 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
50 | "tier": "MYTHIC",
51 | "item_id": "POWER_WITHER_CHESTPLATE",
52 | "internal_id": "POWER_WITHER_CHESTPLATE",
53 | "starting_bid": 47474747,
54 | "highest_bid": 0,
55 | "bin": true,
56 | "count": 1,
57 | "enchants": [
58 | "PROTECTION;5",
59 | "THORNS;3",
60 | "GROWTH;5"
61 | ],
62 | "potato_books": 10,
63 | "stars": 5,
64 | "reforge": "ancient",
65 | "recombobulated": true
66 | },
67 | {
68 | "uuid": "f23eae954b7543bb8858609aa80ee406",
69 | "auctioneer": "5f5534eb367545afaac4fa3d029ad031",
70 | "end_t": 1685225176043,
71 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
72 | "tier": "MYTHIC",
73 | "item_id": "POWER_WITHER_CHESTPLATE",
74 | "internal_id": "POWER_WITHER_CHESTPLATE",
75 | "starting_bid": 47500000,
76 | "highest_bid": 0,
77 | "bin": true,
78 | "count": 1,
79 | "enchants": [
80 | "GROWTH;5",
81 | "MANA_VAMPIRE;2",
82 | "THORNS;3",
83 | "PROTECTION;5",
84 | "TRUE_PROTECTION;1",
85 | "RESPITE;2",
86 | "ULTIMATE_WISDOM;1"
87 | ],
88 | "potato_books": 10,
89 | "stars": 5,
90 | "reforge": "ancient",
91 | "recombobulated": true
92 | },
93 | {
94 | "uuid": "3c690c09c39a4bb3938e518e81805217",
95 | "auctioneer": "019269adf28b45a8ad8654880f6b11ed",
96 | "end_t": 1685216943431,
97 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
98 | "tier": "MYTHIC",
99 | "item_id": "POWER_WITHER_CHESTPLATE",
100 | "internal_id": "POWER_WITHER_CHESTPLATE",
101 | "starting_bid": 47900000,
102 | "highest_bid": 0,
103 | "bin": true,
104 | "count": 1,
105 | "enchants": [
106 | "PROTECTION;5",
107 | "STRONG_MANA;4",
108 | "GROWTH;5",
109 | "THORNS;3",
110 | "REJUVENATE;3"
111 | ],
112 | "potato_books": 10,
113 | "stars": 5,
114 | "reforge": "ancient",
115 | "recombobulated": true
116 | },
117 | {
118 | "uuid": "59843599b4e844dca6bbb5b9faa16d2f",
119 | "auctioneer": "098ea420cf384f59a9e0870f88017a38",
120 | "end_t": 1685222629389,
121 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
122 | "tier": "MYTHIC",
123 | "item_id": "POWER_WITHER_CHESTPLATE",
124 | "internal_id": "POWER_WITHER_CHESTPLATE",
125 | "starting_bid": 48000000,
126 | "highest_bid": 0,
127 | "bin": true,
128 | "count": 1,
129 | "enchants": [
130 | "PROTECTION;5",
131 | "GROWTH;5"
132 | ],
133 | "potato_books": 15,
134 | "stars": 5,
135 | "reforge": "ancient",
136 | "recombobulated": true
137 | },
138 | {
139 | "uuid": "36597bdf7a834a24bc338db94f4449ba",
140 | "auctioneer": "5f3000643d5c4d6a91ff4cfc9cd480b4",
141 | "end_t": 1685230096754,
142 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
143 | "tier": "MYTHIC",
144 | "item_id": "POWER_WITHER_CHESTPLATE",
145 | "internal_id": "POWER_WITHER_CHESTPLATE",
146 | "starting_bid": 48000000,
147 | "highest_bid": 0,
148 | "bin": true,
149 | "count": 1,
150 | "enchants": [
151 | "TRUE_PROTECTION;1",
152 | "PROTECTION;5",
153 | "REJUVENATE;5",
154 | "GROWTH;6"
155 | ],
156 | "potato_books": 10,
157 | "stars": 5,
158 | "reforge": "ancient",
159 | "recombobulated": true
160 | },
161 | {
162 | "uuid": "43cd47c08b034e4aaaf41686960082da",
163 | "auctioneer": "5f5534eb367545afaac4fa3d029ad031",
164 | "end_t": 1685216868190,
165 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
166 | "tier": "MYTHIC",
167 | "item_id": "POWER_WITHER_CHESTPLATE",
168 | "internal_id": "POWER_WITHER_CHESTPLATE",
169 | "starting_bid": 48990000,
170 | "highest_bid": 0,
171 | "bin": true,
172 | "count": 1,
173 | "enchants": [
174 | "PROTECTION;5",
175 | "GROWTH;5",
176 | "REJUVENATE;5"
177 | ],
178 | "potato_books": 10,
179 | "stars": 5,
180 | "reforge": "ancient",
181 | "recombobulated": true
182 | },
183 | {
184 | "uuid": "9dfb15e87744414ab332908eb6868a11",
185 | "auctioneer": "8614050af5714a89b39b7536b26be33a",
186 | "end_t": 1685138532398,
187 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
188 | "tier": "MYTHIC",
189 | "item_id": "POWER_WITHER_CHESTPLATE",
190 | "internal_id": "POWER_WITHER_CHESTPLATE",
191 | "starting_bid": 49000000,
192 | "highest_bid": 0,
193 | "bin": true,
194 | "count": 1,
195 | "enchants": [
196 | "ULTIMATE_LAST_STAND;5",
197 | "THORNS;3",
198 | "PROTECTION;5",
199 | "TRUE_PROTECTION;1",
200 | "REJUVENATE;5",
201 | "MANA_VAMPIRE;3",
202 | "GROWTH;5"
203 | ],
204 | "potato_books": 10,
205 | "stars": 5,
206 | "reforge": "ancient",
207 | "recombobulated": true
208 | },
209 | {
210 | "uuid": "29aa3564e2b4441c9abf0d175310089b",
211 | "auctioneer": "794ff453c255484c8c00ad65a116bb5f",
212 | "end_t": 1685134643454,
213 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
214 | "tier": "MYTHIC",
215 | "item_id": "POWER_WITHER_CHESTPLATE",
216 | "internal_id": "POWER_WITHER_CHESTPLATE",
217 | "starting_bid": 50000000,
218 | "highest_bid": 0,
219 | "bin": true,
220 | "count": 1,
221 | "enchants": [
222 | "ULTIMATE_WISDOM;5",
223 | "GROWTH;5",
224 | "PROTECTION;5",
225 | "THORNS;3",
226 | "REJUVENATE;5"
227 | ],
228 | "potato_books": 10,
229 | "stars": 5,
230 | "reforge": "ancient",
231 | "recombobulated": true
232 | },
233 | {
234 | "uuid": "fba55b7139944991ae68c5255c6859f0",
235 | "auctioneer": "3e28d581c74d431aa7a55bddc6a0d547",
236 | "end_t": 1686261985750,
237 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
238 | "tier": "MYTHIC",
239 | "item_id": "POWER_WITHER_CHESTPLATE",
240 | "internal_id": "POWER_WITHER_CHESTPLATE",
241 | "starting_bid": 50000000,
242 | "highest_bid": 0,
243 | "bin": true,
244 | "count": 1,
245 | "enchants": [
246 | "PROTECTION;5",
247 | "GROWTH;5",
248 | "ULTIMATE_LEGION;1",
249 | "REJUVENATE;5"
250 | ],
251 | "potato_books": 10,
252 | "stars": 5,
253 | "reforge": "ancient",
254 | "recombobulated": true
255 | },
256 | {
257 | "uuid": "3c4c3968f63c4de589e99b809c3784b3",
258 | "auctioneer": "8f4517e30352440e92685e2cbe10f51b",
259 | "end_t": 1685066888755,
260 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
261 | "tier": "MYTHIC",
262 | "item_id": "POWER_WITHER_CHESTPLATE",
263 | "internal_id": "POWER_WITHER_CHESTPLATE",
264 | "starting_bid": 50000000,
265 | "highest_bid": 0,
266 | "bin": true,
267 | "count": 1,
268 | "enchants": [
269 | "THORNS;3",
270 | "PROTECTION;5",
271 | "REJUVENATE;4",
272 | "GROWTH;5"
273 | ],
274 | "potato_books": 10,
275 | "stars": 5,
276 | "reforge": "ancient",
277 | "recombobulated": true
278 | },
279 | {
280 | "uuid": "f212575df35740c3957f521232f96cdf",
281 | "auctioneer": "f8aac9dccbde4cc7b3a4ecbfb44c2463",
282 | "end_t": 1685220554480,
283 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
284 | "tier": "MYTHIC",
285 | "item_id": "POWER_WITHER_CHESTPLATE",
286 | "internal_id": "POWER_WITHER_CHESTPLATE",
287 | "starting_bid": 50999000,
288 | "highest_bid": 0,
289 | "bin": true,
290 | "count": 1,
291 | "enchants": [
292 | "HARDENED_MANA;5",
293 | "REJUVENATE;5",
294 | "PROTECTION;5",
295 | "THORNS;3",
296 | "ULTIMATE_WISDOM;5",
297 | "GROWTH;5"
298 | ],
299 | "potato_books": 10,
300 | "stars": 5,
301 | "reforge": "ancient",
302 | "recombobulated": true
303 | },
304 | {
305 | "uuid": "2566c4fea060406b8be36d9a9df520c9",
306 | "auctioneer": "293dd0632ef9445aa48224ed0d304761",
307 | "end_t": 1685218956098,
308 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
309 | "tier": "MYTHIC",
310 | "item_id": "POWER_WITHER_CHESTPLATE",
311 | "internal_id": "POWER_WITHER_CHESTPLATE",
312 | "starting_bid": 50999000,
313 | "highest_bid": 0,
314 | "bin": true,
315 | "count": 1,
316 | "enchants": [
317 | "REJUVENATE;5",
318 | "PROTECTION;5",
319 | "ULTIMATE_WISDOM;5",
320 | "GROWTH;5"
321 | ],
322 | "potato_books": 10,
323 | "stars": 5,
324 | "reforge": "ancient",
325 | "recombobulated": true
326 | },
327 | {
328 | "uuid": "8afbe808039047bebe0978c13482c9bb",
329 | "auctioneer": "15d882d4710d43128087f07935edac5c",
330 | "end_t": 1685214736312,
331 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
332 | "tier": "MYTHIC",
333 | "item_id": "POWER_WITHER_CHESTPLATE",
334 | "internal_id": "POWER_WITHER_CHESTPLATE",
335 | "starting_bid": 50999000,
336 | "highest_bid": 0,
337 | "bin": true,
338 | "count": 1,
339 | "enchants": [
340 | "GROWTH;5",
341 | "ULTIMATE_LEGION;1",
342 | "REJUVENATE;5",
343 | "PROTECTION;5",
344 | "THORNS;3"
345 | ],
346 | "potato_books": 10,
347 | "stars": 5,
348 | "reforge": "ancient",
349 | "recombobulated": true
350 | },
351 | {
352 | "uuid": "0b2a48b4551f4137b3cfcb4137a534e6",
353 | "auctioneer": "19a4e487fd8645c792cb6f49847704ad",
354 | "end_t": 1685220823606,
355 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
356 | "tier": "MYTHIC",
357 | "item_id": "POWER_WITHER_CHESTPLATE",
358 | "internal_id": "POWER_WITHER_CHESTPLATE",
359 | "starting_bid": 51000000,
360 | "highest_bid": 0,
361 | "bin": true,
362 | "count": 1,
363 | "enchants": [
364 | "GROWTH;5",
365 | "FEROCIOUS_MANA;3",
366 | "REJUVENATE;5",
367 | "ULTIMATE_LAST_STAND;3",
368 | "PROTECTION;5"
369 | ],
370 | "potato_books": 10,
371 | "stars": 5,
372 | "reforge": "ancient",
373 | "recombobulated": true
374 | },
375 | {
376 | "uuid": "6eaffb85fb80424c922cdc97245556e3",
377 | "auctioneer": "df489c749f364f36a19b2de7819b6d1d",
378 | "end_t": 1685065391046,
379 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
380 | "tier": "MYTHIC",
381 | "item_id": "POWER_WITHER_CHESTPLATE",
382 | "internal_id": "POWER_WITHER_CHESTPLATE",
383 | "starting_bid": 51000000,
384 | "highest_bid": 0,
385 | "bin": true,
386 | "count": 1,
387 | "enchants": [
388 | "THORNS;3",
389 | "REJUVENATE;5",
390 | "GROWTH;5",
391 | "ULTIMATE_LAST_STAND;5",
392 | "PROTECTION;5"
393 | ],
394 | "potato_books": 10,
395 | "stars": 5,
396 | "reforge": "ancient",
397 | "recombobulated": true
398 | },
399 | {
400 | "uuid": "30d019b64a9344bfa6da8024299648b9",
401 | "auctioneer": "b15e77b8246b433dae69195130af415a",
402 | "end_t": 1685214444790,
403 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
404 | "tier": "MYTHIC",
405 | "item_id": "POWER_WITHER_CHESTPLATE",
406 | "internal_id": "POWER_WITHER_CHESTPLATE",
407 | "starting_bid": 51000000,
408 | "highest_bid": 0,
409 | "bin": true,
410 | "count": 1,
411 | "enchants": [
412 | "REJUVENATE;5",
413 | "PROTECTION;5",
414 | "GROWTH;5",
415 | "THORNS;3",
416 | "FEROCIOUS_MANA;4"
417 | ],
418 | "potato_books": 10,
419 | "stars": 5,
420 | "reforge": "ancient",
421 | "recombobulated": true
422 | },
423 | {
424 | "uuid": "b725c5664e1c4c6d92d4c83a3992cf16",
425 | "auctioneer": "4d471b6e6b6049d0b0bc6593bfea600d",
426 | "end_t": 1685211572634,
427 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
428 | "tier": "MYTHIC",
429 | "item_id": "POWER_WITHER_CHESTPLATE",
430 | "internal_id": "POWER_WITHER_CHESTPLATE",
431 | "starting_bid": 51900000,
432 | "highest_bid": 0,
433 | "bin": true,
434 | "count": 1,
435 | "enchants": [
436 | "ULTIMATE_LAST_STAND;3",
437 | "THORNS;3",
438 | "REJUVENATE;5",
439 | "PROTECTION;5",
440 | "GROWTH;5"
441 | ],
442 | "potato_books": 10,
443 | "stars": 5,
444 | "reforge": "ancient",
445 | "recombobulated": true
446 | },
447 | {
448 | "uuid": "571f8a2343724a4fb4f39f52d9deea0e",
449 | "auctioneer": "bc4ed2c192ae496eada1360d3e2573db",
450 | "end_t": 1685147452360,
451 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
452 | "tier": "MYTHIC",
453 | "item_id": "POWER_WITHER_CHESTPLATE",
454 | "internal_id": "POWER_WITHER_CHESTPLATE",
455 | "starting_bid": 52000000,
456 | "highest_bid": 0,
457 | "bin": true,
458 | "count": 1,
459 | "enchants": [
460 | "REJUVENATE;5",
461 | "THORNS;3",
462 | "GROWTH;5",
463 | "PROTECTION;5"
464 | ],
465 | "potato_books": 10,
466 | "stars": 5,
467 | "reforge": "ancient",
468 | "recombobulated": true
469 | },
470 | {
471 | "uuid": "c712d6f0116540abb23da4e5577dd03e",
472 | "auctioneer": "fc0bb97d8abb46eeade468c7607d755a",
473 | "end_t": 1686180097466,
474 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
475 | "tier": "MYTHIC",
476 | "item_id": "POWER_WITHER_CHESTPLATE",
477 | "internal_id": "POWER_WITHER_CHESTPLATE",
478 | "starting_bid": 53499000,
479 | "highest_bid": 0,
480 | "bin": true,
481 | "count": 1,
482 | "enchants": [
483 | "PROTECTION;5",
484 | "GROWTH;5",
485 | "ULTIMATE_WISDOM;3",
486 | "THORNS;3",
487 | "REJUVENATE;5",
488 | "TRUE_PROTECTION;1"
489 | ],
490 | "potato_books": 10,
491 | "stars": 5,
492 | "reforge": "ancient",
493 | "recombobulated": true
494 | },
495 | {
496 | "uuid": "ebbe8f52a90e42f79bcfd7666705eec9",
497 | "auctioneer": "23498b0f282448f29ebd7388f1ccbc1e",
498 | "end_t": 1685530310779,
499 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
500 | "tier": "MYTHIC",
501 | "item_id": "POWER_WITHER_CHESTPLATE",
502 | "internal_id": "POWER_WITHER_CHESTPLATE",
503 | "starting_bid": 53500000,
504 | "highest_bid": 0,
505 | "bin": true,
506 | "count": 1,
507 | "enchants": [
508 | "REJUVENATE;5",
509 | "ULTIMATE_WISDOM;5",
510 | "GROWTH;5",
511 | "PROTECTION;5"
512 | ],
513 | "potato_books": 10,
514 | "stars": 5,
515 | "reforge": "ancient",
516 | "recombobulated": true
517 | },
518 | {
519 | "uuid": "3d9715eb27d34e40acacbe67bc45885a",
520 | "auctioneer": "2d321b2ba0cb45bbb4277861569ed3cc",
521 | "end_t": 1685142803611,
522 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
523 | "tier": "MYTHIC",
524 | "item_id": "POWER_WITHER_CHESTPLATE",
525 | "internal_id": "POWER_WITHER_CHESTPLATE",
526 | "starting_bid": 53500000,
527 | "highest_bid": 0,
528 | "bin": true,
529 | "count": 1,
530 | "enchants": [
531 | "PROTECTION;5",
532 | "GROWTH;5",
533 | "REJUVENATE;5"
534 | ],
535 | "potato_books": 10,
536 | "stars": 5,
537 | "reforge": "ancient",
538 | "recombobulated": true
539 | },
540 | {
541 | "uuid": "424215e2d4eb4a7e90a09e4c6d3d5656",
542 | "auctioneer": "b9558a82e0ea43d4991b097087d36774",
543 | "end_t": 1685179211304,
544 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
545 | "tier": "MYTHIC",
546 | "item_id": "POWER_WITHER_CHESTPLATE",
547 | "internal_id": "POWER_WITHER_CHESTPLATE",
548 | "starting_bid": 53990000,
549 | "highest_bid": 0,
550 | "bin": true,
551 | "count": 1,
552 | "enchants": [
553 | "PROTECTION;5",
554 | "ULTIMATE_WISDOM;5",
555 | "GROWTH;5",
556 | "REJUVENATE;5"
557 | ],
558 | "potato_books": 10,
559 | "stars": 5,
560 | "reforge": "ancient",
561 | "recombobulated": true
562 | },
563 | {
564 | "uuid": "d515559a8ec44ce8a5f96b8cb4fab4a9",
565 | "auctioneer": "bf9ca0e665614931a672356311b73f42",
566 | "end_t": 1685196078300,
567 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
568 | "tier": "MYTHIC",
569 | "item_id": "POWER_WITHER_CHESTPLATE",
570 | "internal_id": "POWER_WITHER_CHESTPLATE",
571 | "starting_bid": 54400000,
572 | "highest_bid": 0,
573 | "bin": true,
574 | "count": 1,
575 | "enchants": [
576 | "PROTECTION;5",
577 | "ULTIMATE_LEGION;1",
578 | "REJUVENATE;5",
579 | "GROWTH;5"
580 | ],
581 | "potato_books": 10,
582 | "stars": 5,
583 | "reforge": "ancient",
584 | "recombobulated": true
585 | },
586 | {
587 | "uuid": "8032113aaab84c55ad165e8941e3b8ea",
588 | "auctioneer": "5aa7a188cd8c43098f875aae077d6ffa",
589 | "end_t": 1685210999615,
590 | "item_name": "Fierce Necron's Chestplate ✪✪✪✪✪",
591 | "tier": "MYTHIC",
592 | "item_id": "POWER_WITHER_CHESTPLATE",
593 | "internal_id": "POWER_WITHER_CHESTPLATE",
594 | "starting_bid": 54500000,
595 | "highest_bid": 0,
596 | "bin": true,
597 | "count": 1,
598 | "enchants": [
599 | "ULTIMATE_WISDOM;5",
600 | "PROTECTION;5",
601 | "GROWTH;5",
602 | "REJUVENATE;5",
603 | "THORNS;3"
604 | ],
605 | "potato_books": 10,
606 | "stars": 5,
607 | "reforge": "fierce",
608 | "recombobulated": true
609 | },
610 | {
611 | "uuid": "ea2a0a970b8c44ca9ac877b7098ab3f0",
612 | "auctioneer": "e09a30636a054c4886b2473eddf31ab5",
613 | "end_t": 1685133628095,
614 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
615 | "tier": "MYTHIC",
616 | "item_id": "POWER_WITHER_CHESTPLATE",
617 | "internal_id": "POWER_WITHER_CHESTPLATE",
618 | "starting_bid": 54600000,
619 | "highest_bid": 0,
620 | "bin": true,
621 | "count": 1,
622 | "enchants": [
623 | "REJUVENATE;5",
624 | "TRUE_PROTECTION;1",
625 | "PROTECTION;5",
626 | "GROWTH;5",
627 | "ULTIMATE_LAST_STAND;5",
628 | "FEROCIOUS_MANA;3"
629 | ],
630 | "potato_books": 10,
631 | "stars": 5,
632 | "reforge": "ancient",
633 | "recombobulated": true
634 | },
635 | {
636 | "uuid": "71ec573a20d04c3dbedf585d149f28d9",
637 | "auctioneer": "e24f60e491ba4d5187efd79974f79c04",
638 | "end_t": 1685221040213,
639 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
640 | "tier": "MYTHIC",
641 | "item_id": "POWER_WITHER_CHESTPLATE",
642 | "internal_id": "POWER_WITHER_CHESTPLATE",
643 | "starting_bid": 55000000,
644 | "highest_bid": 0,
645 | "bin": true,
646 | "count": 1,
647 | "enchants": [
648 | "GROWTH;5",
649 | "REJUVENATE;5",
650 | "ULTIMATE_LAST_STAND;3",
651 | "PROTECTION;5",
652 | "THORNS;3"
653 | ],
654 | "potato_books": 10,
655 | "stars": 5,
656 | "reforge": "ancient",
657 | "recombobulated": true
658 | },
659 | {
660 | "uuid": "2b951936a3994c48af8a0126abe93827",
661 | "auctioneer": "ef3cec57d4d64f2fbbd7962fd771d8ec",
662 | "end_t": 1685229615411,
663 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
664 | "tier": "MYTHIC",
665 | "item_id": "POWER_WITHER_CHESTPLATE",
666 | "internal_id": "POWER_WITHER_CHESTPLATE",
667 | "starting_bid": 55000000,
668 | "highest_bid": 0,
669 | "bin": true,
670 | "count": 1,
671 | "enchants": [
672 | "PROTECTION;5",
673 | "ULTIMATE_LEGION;3",
674 | "REJUVENATE;5",
675 | "FEROCIOUS_MANA;3",
676 | "GROWTH;5"
677 | ],
678 | "potato_books": 15,
679 | "stars": 5,
680 | "reforge": "ancient",
681 | "recombobulated": true
682 | },
683 | {
684 | "uuid": "70e7aa4053664866bdab41bf6a304f52",
685 | "auctioneer": "3ae6f4a643c6499da2fdd8161ca6f41f",
686 | "end_t": 1686249211240,
687 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
688 | "tier": "MYTHIC",
689 | "item_id": "POWER_WITHER_CHESTPLATE",
690 | "internal_id": "POWER_WITHER_CHESTPLATE",
691 | "starting_bid": 55000000,
692 | "highest_bid": 0,
693 | "bin": true,
694 | "count": 1,
695 | "enchants": [
696 | "REJUVENATE;5",
697 | "ULTIMATE_LEGION;3",
698 | "TRUE_PROTECTION;1",
699 | "PROTECTION;5",
700 | "THORNS;3",
701 | "GROWTH;5"
702 | ],
703 | "potato_books": 10,
704 | "stars": 5,
705 | "reforge": "ancient",
706 | "recombobulated": true
707 | },
708 | {
709 | "uuid": "86cf18142e5b4a4787f48d36b24242e2",
710 | "auctioneer": "072549cda91c4a499d3fbeda32fa529e",
711 | "end_t": 1685159930045,
712 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
713 | "tier": "MYTHIC",
714 | "item_id": "POWER_WITHER_CHESTPLATE",
715 | "internal_id": "POWER_WITHER_CHESTPLATE",
716 | "starting_bid": 55500000,
717 | "highest_bid": 0,
718 | "bin": true,
719 | "count": 1,
720 | "enchants": [
721 | "ULTIMATE_LAST_STAND;3",
722 | "REJUVENATE;5",
723 | "THORNS;3",
724 | "GROWTH;5",
725 | "PROTECTION;5"
726 | ],
727 | "potato_books": 10,
728 | "stars": 5,
729 | "reforge": "ancient",
730 | "recombobulated": true
731 | },
732 | {
733 | "uuid": "41b89a89102048ca9aca3e19b4e34ce2",
734 | "auctioneer": "3cf28071ede34b3a9df697368f3decf1",
735 | "end_t": 1686164336610,
736 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
737 | "tier": "MYTHIC",
738 | "item_id": "POWER_WITHER_CHESTPLATE",
739 | "internal_id": "POWER_WITHER_CHESTPLATE",
740 | "starting_bid": 55900000,
741 | "highest_bid": 0,
742 | "bin": true,
743 | "count": 1,
744 | "enchants": [
745 | "THORNS;3",
746 | "GROWTH;5",
747 | "PROTECTION;5"
748 | ],
749 | "potato_books": 10,
750 | "stars": 5,
751 | "reforge": "ancient",
752 | "recombobulated": true
753 | },
754 | {
755 | "uuid": "6a59cfaf8b1647c9b3bc7daeb1d6a073",
756 | "auctioneer": "097c7cdf69d8488690709bfee107a458",
757 | "end_t": 1686174545890,
758 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
759 | "tier": "MYTHIC",
760 | "item_id": "POWER_WITHER_CHESTPLATE",
761 | "internal_id": "POWER_WITHER_CHESTPLATE",
762 | "starting_bid": 57999000,
763 | "highest_bid": 0,
764 | "bin": true,
765 | "count": 1,
766 | "enchants": [
767 | "ULTIMATE_WISDOM;5",
768 | "THORNS;3",
769 | "PROTECTION;5",
770 | "GROWTH;5",
771 | "REJUVENATE;5"
772 | ],
773 | "potato_books": 10,
774 | "stars": 5,
775 | "reforge": "ancient",
776 | "recombobulated": true
777 | },
778 | {
779 | "uuid": "dcd758a40b3642deab43c7a93b716fdd",
780 | "auctioneer": "c79ff712eecf40cf957213fdc05cc015",
781 | "end_t": 1685208581796,
782 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
783 | "tier": "MYTHIC",
784 | "item_id": "POWER_WITHER_CHESTPLATE",
785 | "internal_id": "POWER_WITHER_CHESTPLATE",
786 | "starting_bid": 57999000,
787 | "highest_bid": 0,
788 | "bin": true,
789 | "count": 1,
790 | "enchants": [
791 | "PROTECTION;5",
792 | "REJUVENATE;5",
793 | "ULTIMATE_LEGION;2",
794 | "GROWTH;5"
795 | ],
796 | "potato_books": 10,
797 | "stars": 5,
798 | "reforge": "ancient",
799 | "recombobulated": true
800 | },
801 | {
802 | "uuid": "13d0879dd5e047f1b5e498abc6ca71bc",
803 | "auctioneer": "dd79212e2c364bda958814af0b95d4ba",
804 | "end_t": 1685890910779,
805 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
806 | "tier": "MYTHIC",
807 | "item_id": "POWER_WITHER_CHESTPLATE",
808 | "internal_id": "POWER_WITHER_CHESTPLATE",
809 | "starting_bid": 58000000,
810 | "highest_bid": 0,
811 | "bin": true,
812 | "count": 1,
813 | "enchants": [
814 | "GROWTH;5",
815 | "PROTECTION;5"
816 | ],
817 | "stars": 5,
818 | "reforge": "ancient",
819 | "recombobulated": true
820 | },
821 | {
822 | "uuid": "1cab44b31c584fa1a59e86396b5fd9e7",
823 | "auctioneer": "e9a2de45d4bc4ee495c96c18603d57fa",
824 | "end_t": 1685184653423,
825 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
826 | "tier": "MYTHIC",
827 | "item_id": "POWER_WITHER_CHESTPLATE",
828 | "internal_id": "POWER_WITHER_CHESTPLATE",
829 | "starting_bid": 59000000,
830 | "highest_bid": 0,
831 | "bin": true,
832 | "count": 1,
833 | "enchants": [
834 | "TRUE_PROTECTION;1",
835 | "ULTIMATE_LEGION;1",
836 | "GROWTH;5",
837 | "REJUVENATE;5",
838 | "THORNS;3",
839 | "PROTECTION;5"
840 | ],
841 | "potato_books": 15,
842 | "stars": 5,
843 | "reforge": "ancient",
844 | "recombobulated": true
845 | },
846 | {
847 | "uuid": "e0cc5e75958a4f679b0feb02da888d9f",
848 | "auctioneer": "d69420382a2c41d98318007c9440705c",
849 | "end_t": 1685222525155,
850 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
851 | "tier": "MYTHIC",
852 | "item_id": "POWER_WITHER_CHESTPLATE",
853 | "internal_id": "POWER_WITHER_CHESTPLATE",
854 | "starting_bid": 59500000,
855 | "highest_bid": 0,
856 | "bin": true,
857 | "count": 1,
858 | "enchants": [
859 | "GROWTH;5",
860 | "FEROCIOUS_MANA;3",
861 | "ULTIMATE_LEGION;3",
862 | "PROTECTION;5",
863 | "REJUVENATE;5"
864 | ],
865 | "potato_books": 10,
866 | "stars": 5,
867 | "reforge": "ancient",
868 | "recombobulated": true
869 | },
870 | {
871 | "uuid": "967613fee9444225b2738630bd648d55",
872 | "auctioneer": "3519b335f1444b639fc73b2cafb3667a",
873 | "end_t": 1685203313546,
874 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
875 | "tier": "MYTHIC",
876 | "item_id": "POWER_WITHER_CHESTPLATE",
877 | "internal_id": "POWER_WITHER_CHESTPLATE",
878 | "starting_bid": 59999999,
879 | "highest_bid": 0,
880 | "bin": true,
881 | "count": 1,
882 | "enchants": [
883 | "ULTIMATE_LAST_STAND;3",
884 | "REJUVENATE;3",
885 | "HARDENED_MANA;5",
886 | "GROWTH;5",
887 | "PROTECTION;5",
888 | "THORNS;3"
889 | ],
890 | "potato_books": 15,
891 | "stars": 5,
892 | "reforge": "ancient",
893 | "recombobulated": true
894 | },
895 | {
896 | "uuid": "1d7c630d2e6e47f3bbc49535398778ac",
897 | "auctioneer": "d3554334b1c14caebc4f70b5565297ae",
898 | "end_t": 1685209246826,
899 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
900 | "tier": "MYTHIC",
901 | "item_id": "POWER_WITHER_CHESTPLATE",
902 | "internal_id": "POWER_WITHER_CHESTPLATE",
903 | "starting_bid": 60000000,
904 | "highest_bid": 0,
905 | "bin": true,
906 | "count": 1,
907 | "enchants": [
908 | "ULTIMATE_LEGION;3",
909 | "PROTECTION;5",
910 | "REJUVENATE;5",
911 | "GROWTH;5"
912 | ],
913 | "potato_books": 15,
914 | "stars": 5,
915 | "reforge": "ancient",
916 | "recombobulated": true,
917 | "gemstones": [
918 | "COMBAT_0_FINE_JASPER_GEM"
919 | ]
920 | },
921 | {
922 | "uuid": "582d1ddc5d124833969520dff12181fb",
923 | "auctioneer": "7274b1be9fbf47bba3bae40a20d2142c",
924 | "end_t": 1685889871642,
925 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
926 | "tier": "MYTHIC",
927 | "item_id": "POWER_WITHER_CHESTPLATE",
928 | "internal_id": "POWER_WITHER_CHESTPLATE",
929 | "starting_bid": 60000000,
930 | "highest_bid": 0,
931 | "bin": true,
932 | "count": 1,
933 | "enchants": [
934 | "REJUVENATE;5",
935 | "GROWTH;5",
936 | "PROTECTION;5",
937 | "ULTIMATE_LEGION;1",
938 | "THORNS;3"
939 | ],
940 | "potato_books": 10,
941 | "stars": 5,
942 | "reforge": "ancient",
943 | "recombobulated": true
944 | },
945 | {
946 | "uuid": "98aa630734ff42699754e69e3510d519",
947 | "auctioneer": "a2424870380f4a55ae6f09079c63416f",
948 | "end_t": 1685201392266,
949 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
950 | "tier": "MYTHIC",
951 | "item_id": "POWER_WITHER_CHESTPLATE",
952 | "internal_id": "POWER_WITHER_CHESTPLATE",
953 | "starting_bid": 60000000,
954 | "highest_bid": 0,
955 | "bin": true,
956 | "count": 1,
957 | "enchants": [
958 | "REJUVENATE;5",
959 | "PROTECTION;5",
960 | "ULTIMATE_LEGION;3",
961 | "GROWTH;5",
962 | "THORNS;3"
963 | ],
964 | "potato_books": 15,
965 | "stars": 5,
966 | "reforge": "ancient",
967 | "recombobulated": true
968 | },
969 | {
970 | "uuid": "c63e941de88a4eb3b9964757a243e7ae",
971 | "auctioneer": "814111b095ac4cbf9f96a9fd271f885e",
972 | "end_t": 1685219775359,
973 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
974 | "tier": "MYTHIC",
975 | "item_id": "POWER_WITHER_CHESTPLATE",
976 | "internal_id": "POWER_WITHER_CHESTPLATE",
977 | "starting_bid": 60000000,
978 | "highest_bid": 0,
979 | "bin": true,
980 | "count": 1,
981 | "enchants": [
982 | "THORNS;3",
983 | "ULTIMATE_LAST_STAND;5",
984 | "PROTECTION;5",
985 | "HARDENED_MANA;6",
986 | "REJUVENATE;5",
987 | "GROWTH;5",
988 | "TRUE_PROTECTION;1"
989 | ],
990 | "potato_books": 15,
991 | "stars": 5,
992 | "reforge": "ancient",
993 | "recombobulated": true
994 | },
995 | {
996 | "uuid": "927d3eb926f94c8d8732bdf37e2f0bef",
997 | "auctioneer": "43341fd8e9684104b784c11724db493e",
998 | "end_t": 1685200550394,
999 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
1000 | "tier": "MYTHIC",
1001 | "item_id": "POWER_WITHER_CHESTPLATE",
1002 | "internal_id": "POWER_WITHER_CHESTPLATE",
1003 | "starting_bid": 60000000,
1004 | "highest_bid": 0,
1005 | "bin": true,
1006 | "count": 1,
1007 | "enchants": [
1008 | "ULTIMATE_LEGION;3",
1009 | "GROWTH;5",
1010 | "FEROCIOUS_MANA;5",
1011 | "THORNS;3",
1012 | "PROTECTION;5",
1013 | "REJUVENATE;5"
1014 | ],
1015 | "potato_books": 10,
1016 | "stars": 5,
1017 | "reforge": "ancient",
1018 | "recombobulated": true
1019 | },
1020 | {
1021 | "uuid": "f14a8154650a49eba453f08d302c58fd",
1022 | "auctioneer": "2b68e42727e1401ea06c75a7a6acba51",
1023 | "end_t": 1685209350264,
1024 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
1025 | "tier": "MYTHIC",
1026 | "item_id": "POWER_WITHER_CHESTPLATE",
1027 | "internal_id": "POWER_WITHER_CHESTPLATE",
1028 | "starting_bid": 62000000,
1029 | "highest_bid": 0,
1030 | "bin": true,
1031 | "count": 1,
1032 | "enchants": [
1033 | "ULTIMATE_LEGION;1",
1034 | "PROTECTION;5",
1035 | "GROWTH;5",
1036 | "FEROCIOUS_MANA;2",
1037 | "REJUVENATE;5"
1038 | ],
1039 | "potato_books": 10,
1040 | "stars": 5,
1041 | "reforge": "ancient",
1042 | "recombobulated": true
1043 | },
1044 | {
1045 | "uuid": "fbd57598ffa744f183d06dfb0efb3fb9",
1046 | "auctioneer": "32a727a1ead84321a4df91f10fd24d77",
1047 | "end_t": 1685226002192,
1048 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
1049 | "tier": "MYTHIC",
1050 | "item_id": "POWER_WITHER_CHESTPLATE",
1051 | "internal_id": "POWER_WITHER_CHESTPLATE",
1052 | "starting_bid": 62500000,
1053 | "highest_bid": 0,
1054 | "bin": true,
1055 | "count": 1,
1056 | "enchants": [
1057 | "REJUVENATE;5",
1058 | "ULTIMATE_WISDOM;5",
1059 | "TRUE_PROTECTION;1",
1060 | "PROTECTION;6",
1061 | "GROWTH;6",
1062 | "FEROCIOUS_MANA;5"
1063 | ],
1064 | "potato_books": 10,
1065 | "stars": 5,
1066 | "reforge": "ancient",
1067 | "recombobulated": true
1068 | },
1069 | {
1070 | "uuid": "c97df8ba85cd4db0bdf209f04d3e835f",
1071 | "auctioneer": "c5c5bd78d6714d22a177f4cbc303acab",
1072 | "end_t": 1685343817544,
1073 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
1074 | "tier": "MYTHIC",
1075 | "item_id": "POWER_WITHER_CHESTPLATE",
1076 | "internal_id": "POWER_WITHER_CHESTPLATE",
1077 | "starting_bid": 62900000,
1078 | "highest_bid": 0,
1079 | "bin": true,
1080 | "count": 1,
1081 | "enchants": [
1082 | "ULTIMATE_LEGION;3",
1083 | "THORNS;3",
1084 | "PROTECTION;5",
1085 | "GROWTH;5"
1086 | ],
1087 | "stars": 5,
1088 | "reforge": "ancient",
1089 | "recombobulated": true
1090 | },
1091 | {
1092 | "uuid": "fdcf46949f714522b9c8de69b293bc0d",
1093 | "auctioneer": "3395a42705784db0abbb668fb97971c2",
1094 | "end_t": 1685215807683,
1095 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
1096 | "tier": "MYTHIC",
1097 | "item_id": "POWER_WITHER_CHESTPLATE",
1098 | "internal_id": "POWER_WITHER_CHESTPLATE",
1099 | "starting_bid": 63000000,
1100 | "highest_bid": 0,
1101 | "bin": true,
1102 | "count": 1,
1103 | "enchants": [
1104 | "TRUE_PROTECTION;1",
1105 | "FEROCIOUS_MANA;5",
1106 | "REJUVENATE;5",
1107 | "PROTECTION;6",
1108 | "GROWTH;6",
1109 | "THORNS;3",
1110 | "ULTIMATE_WISDOM;5"
1111 | ],
1112 | "potato_books": 15,
1113 | "stars": 5,
1114 | "reforge": "ancient",
1115 | "recombobulated": true
1116 | },
1117 | {
1118 | "uuid": "43c8c2a6689c462c86d4bfe7192c0f35",
1119 | "auctioneer": "c5c5bd78d6714d22a177f4cbc303acab",
1120 | "end_t": 1685343805826,
1121 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
1122 | "tier": "MYTHIC",
1123 | "item_id": "POWER_WITHER_CHESTPLATE",
1124 | "internal_id": "POWER_WITHER_CHESTPLATE",
1125 | "starting_bid": 63600000,
1126 | "highest_bid": 0,
1127 | "bin": true,
1128 | "count": 1,
1129 | "enchants": [
1130 | "GROWTH;5",
1131 | "REJUVENATE;5",
1132 | "PROTECTION;6",
1133 | "ULTIMATE_LEGION;3"
1134 | ],
1135 | "potato_books": 10,
1136 | "stars": 5,
1137 | "reforge": "ancient",
1138 | "recombobulated": true
1139 | },
1140 | {
1141 | "uuid": "fbc5c3a9cac544f08985b077e4df56e9",
1142 | "auctioneer": "df2b974944b7416899a1ec1fe396519a",
1143 | "end_t": 1685150186236,
1144 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
1145 | "tier": "MYTHIC",
1146 | "item_id": "POWER_WITHER_CHESTPLATE",
1147 | "internal_id": "POWER_WITHER_CHESTPLATE",
1148 | "starting_bid": 63988000,
1149 | "highest_bid": 0,
1150 | "bin": true,
1151 | "count": 1,
1152 | "enchants": [
1153 | "PROTECTION;6",
1154 | "GROWTH;6",
1155 | "MANA_VAMPIRE;5",
1156 | "ULTIMATE_WISDOM;5"
1157 | ],
1158 | "potato_books": 10,
1159 | "stars": 5,
1160 | "reforge": "ancient",
1161 | "recombobulated": true
1162 | },
1163 | {
1164 | "uuid": "8c813d5cd6f24b4298764e11241be5a1",
1165 | "auctioneer": "c5c5bd78d6714d22a177f4cbc303acab",
1166 | "end_t": 1685343796321,
1167 | "item_name": "Ancient Necron's Chestplate ✪✪✪✪✪",
1168 | "tier": "MYTHIC",
1169 | "item_id": "POWER_WITHER_CHESTPLATE",
1170 | "internal_id": "POWER_WITHER_CHESTPLATE",
1171 | "starting_bid": 64000000,
1172 | "highest_bid": 0,
1173 | "bin": true,
1174 | "count": 1,
1175 | "enchants": [
1176 | "PROTECTION;5",
1177 | "ULTIMATE_LEGION;3",
1178 | "REJUVENATE;5",
1179 | "TRUE_PROTECTION;1",
1180 | "THORNS;3",
1181 | "GROWTH;5",
1182 | "FEROCIOUS_MANA;5"
1183 | ],
1184 | "stars": 5,
1185 | "reforge": "ancient",
1186 | "recombobulated": true
1187 | }
1188 | ]
--------------------------------------------------------------------------------
/docs/underbin_example.json:
--------------------------------------------------------------------------------
1 | {
2 | "f189ee8f89fe4003a23022bd94f053a2": {
3 | "auctioneer": "41ea357f1d924aeba40abe13762b506f",
4 | "id": "MAGMA_LORD_LEGGINGS",
5 | "name": "Magma Lord Leggings",
6 | "past_bin_price": 13500000,
7 | "profit": 1030000,
8 | "starting_bid": 12200000,
9 | "uuid": "f189ee8f89fe4003a23022bd94f053a2"
10 | },
11 | "be1242943bee4655b64d58b37a890749": {
12 | "auctioneer": "cc8afebd5c044637bcb474dd6208a7c3",
13 | "id": "ATOMSPLIT_KATANA",
14 | "name": "Atomsplit Katana",
15 | "past_bin_price": 56000000,
16 | "profit": 1380000,
17 | "starting_bid": 53500000,
18 | "uuid": "be1242943bee4655b64d58b37a890749"
19 | }
20 | }
--------------------------------------------------------------------------------
/src/api_handler.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Rust Query API - A versatile API facade for the Hypixel Auction API
3 | * Copyright (c) 2022 kr45732
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU Affero General Public License as
7 | * published by the Free Software Foundation, either version 3 of the
8 | * License, or (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU Affero General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU Affero General Public License
16 | * along with this program. If not, see .
17 | */
18 |
19 | use crate::{
20 | config::{Config, Feature},
21 | statics::*,
22 | structs::*,
23 | utils::*,
24 | };
25 | use dashmap::{DashMap, DashSet};
26 | use futures::{stream::FuturesUnordered, FutureExt, StreamExt};
27 | use log::{debug, info};
28 | use serde_json::{json, Value};
29 | use std::{
30 | fs,
31 | sync::{Arc, Mutex},
32 | thread,
33 | time::{Duration, Instant},
34 | };
35 |
36 | /// Update the enabled APIs
37 | pub async fn update_auctions(config: Arc) -> bool {
38 | info!("Fetching auctions...");
39 |
40 | *IS_UPDATING.lock().await = true;
41 | let started = Instant::now();
42 | let mut started_epoch = get_timestamp_millis() as i64;
43 | let previous_started_epoch = *LAST_UPDATED.lock().await;
44 | // Periodically fetch entire ah to correct excess/missing auctions (please fix your API Hypixel)
45 | let last_updated = if *TOTAL_UPDATES.lock().await % 5 == 0 {
46 | 0
47 | } else {
48 | previous_started_epoch
49 | };
50 | let is_full_update = last_updated == 0;
51 |
52 | // Stores all auction uuids in auctions vector to prevent duplicates
53 | let inserted_uuids: DashSet = DashSet::new();
54 | let query_prices: Mutex> = Mutex::new(Vec::new());
55 | let pet_prices: DashMap = DashMap::new();
56 | let bin_prices: DashMap = DashMap::new();
57 | let under_bin_prices: DashMap = DashMap::new();
58 | let avg_ah_prices: DashMap = DashMap::new();
59 | let avg_bin_prices: DashMap = DashMap::new();
60 | let past_bin_prices: DashMap = serde_json::from_str(
61 | &fs::read_to_string("lowestbin.json").unwrap_or_else(|_| String::from("{}")),
62 | )
63 | .unwrap();
64 | let ended_auction_uuids: DashSet = DashSet::new();
65 |
66 | // Get which APIs to update
67 | let update_query = config.is_enabled(Feature::Query);
68 | let update_pets = config.is_enabled(Feature::Pets);
69 | let update_lowestbin = config.is_enabled(Feature::Lowestbin);
70 | let update_underbin = config.is_enabled(Feature::Underbin);
71 | let update_average_auction = config.is_enabled(Feature::AverageAuction);
72 | let update_average_bin = config.is_enabled(Feature::AverageBin);
73 |
74 | // Stores the futures for all auction pages in order to utilize multithreading
75 | let futures = FuturesUnordered::new();
76 |
77 | // Only fetch auctions if any of APIs that need the auctions are enabled
78 | if update_query || update_lowestbin || update_underbin {
79 | // First page to get the total number of pages
80 | let json_opt = get_auction_page(0).await;
81 | if json_opt.is_none() {
82 | error(String::from(
83 | "Failed to fetch the first auction page. Canceling this run.",
84 | ));
85 | return true;
86 | }
87 |
88 | let json = json_opt.unwrap();
89 | started_epoch = json.last_updated;
90 |
91 | // May run too early sometimes
92 | if started_epoch == previous_started_epoch {
93 | thread::sleep(Duration::from_secs(1));
94 | return false;
95 | }
96 |
97 | // Parse the first page's auctions and append them to the prices
98 | let finished = parse_auctions(
99 | json.auctions,
100 | &inserted_uuids,
101 | &query_prices,
102 | &bin_prices,
103 | &under_bin_prices,
104 | &past_bin_prices,
105 | update_query,
106 | update_lowestbin,
107 | update_underbin,
108 | last_updated,
109 | );
110 |
111 | if is_full_update {
112 | debug!("Sending {} async requests", json.total_pages);
113 | // Skip page zero since it's already been parsed
114 | for page_number in 1..json.total_pages {
115 | futures.push(
116 | process_auction_page(
117 | page_number,
118 | &inserted_uuids,
119 | &query_prices,
120 | &bin_prices,
121 | &under_bin_prices,
122 | &past_bin_prices,
123 | update_query,
124 | update_lowestbin,
125 | update_underbin,
126 | last_updated,
127 | )
128 | .boxed(),
129 | );
130 | }
131 | } else if !finished {
132 | for page_number in 1..json.total_pages {
133 | if process_auction_page(
134 | page_number,
135 | &inserted_uuids,
136 | &query_prices,
137 | &bin_prices,
138 | &under_bin_prices,
139 | &past_bin_prices,
140 | update_query,
141 | update_lowestbin,
142 | update_underbin,
143 | last_updated,
144 | )
145 | .await
146 | {
147 | break;
148 | }
149 | }
150 | }
151 | }
152 |
153 | // Update average auctions if the feature is enabled
154 | if update_average_auction || update_average_bin || update_pets || !is_full_update {
155 | futures.push(
156 | parse_ended_auctions(
157 | &avg_ah_prices,
158 | &avg_bin_prices,
159 | &pet_prices,
160 | update_average_auction,
161 | update_average_bin,
162 | update_pets,
163 | &ended_auction_uuids,
164 | !is_full_update,
165 | &mut started_epoch,
166 | )
167 | .boxed(),
168 | );
169 | }
170 |
171 | let _: Vec<_> = futures.collect().await;
172 |
173 | let fetch_sec = started.elapsed().as_secs_f32();
174 | info!("Total fetch time: {:.2}s", fetch_sec);
175 |
176 | debug!("Inserting into database");
177 | let insert_started = Instant::now();
178 | let mut ok_logs = String::new();
179 | let mut err_logs = String::new();
180 | // Write async to database and files
181 | let insert_futures = FuturesUnordered::new();
182 |
183 | // Also updates bin and underbin (if enabled)
184 | if update_query {
185 | insert_futures.push(
186 | update_query_bin_underbin_fn(
187 | query_prices,
188 | ended_auction_uuids,
189 | is_full_update,
190 | &bin_prices,
191 | update_lowestbin,
192 | last_updated,
193 | update_underbin,
194 | &under_bin_prices,
195 | )
196 | .boxed(),
197 | );
198 | }
199 |
200 | if update_pets && !pet_prices.is_empty() {
201 | insert_futures.push(update_pets_fn(pet_prices).boxed());
202 | }
203 |
204 | if update_average_auction && !avg_ah_prices.is_empty() {
205 | insert_futures.push(
206 | update_average_fn(
207 | "average auctions",
208 | "average_auction",
209 | avg_ah_prices,
210 | started_epoch,
211 | )
212 | .boxed(),
213 | );
214 | }
215 |
216 | if update_average_bin && !avg_bin_prices.is_empty() {
217 | insert_futures.push(
218 | update_average_fn("average bins", "average_bin", avg_bin_prices, started_epoch).boxed(),
219 | );
220 | }
221 |
222 | let logs: Vec<(String, String)> = insert_futures.collect().await;
223 | for ele in logs {
224 | if !ele.0.is_empty() {
225 | ok_logs.push_str(&ele.0);
226 | }
227 | if !ele.1.is_empty() {
228 | err_logs.push_str(&ele.1);
229 | }
230 | }
231 |
232 | if !ok_logs.is_empty() {
233 | info_mention(
234 | ok_logs.trim().to_string(),
235 | config.super_secret_config_option,
236 | );
237 | }
238 |
239 | if !err_logs.is_empty() {
240 | error(err_logs.trim().to_string());
241 | }
242 |
243 | info(format!(
244 | "Fetch time: {:.2}s | Insert time: {:.2}s | Total time: {:.2}s",
245 | fetch_sec,
246 | insert_started.elapsed().as_secs_f32(),
247 | started.elapsed().as_secs_f32()
248 | ));
249 |
250 | *TOTAL_UPDATES.lock().await += 1;
251 | *LAST_UPDATED.lock().await = started_epoch;
252 | *IS_UPDATING.lock().await = false;
253 |
254 | true
255 | }
256 |
257 | async fn process_auction_page(
258 | page_number: i32,
259 | inserted_uuids: &DashSet,
260 | query_prices: &Mutex>,
261 | bin_prices: &DashMap,
262 | under_bin_prices: &DashMap,
263 | past_bin_prices: &DashMap,
264 | update_query: bool,
265 | update_lowestbin: bool,
266 | update_underbin: bool,
267 | last_updated: i64,
268 | ) -> bool {
269 | let before_page_request = Instant::now();
270 | // Get the page from the Hypixel API
271 | if let Some(page_request) = get_auction_page(page_number).await {
272 | debug!("---------------- Fetching page {}", page_request.page);
273 | debug!(
274 | "Request time: {}ms",
275 | before_page_request.elapsed().as_millis()
276 | );
277 |
278 | // Parse the auctions and append them to the prices
279 | let before_page_parse = Instant::now();
280 | let is_finished = parse_auctions(
281 | page_request.auctions,
282 | inserted_uuids,
283 | query_prices,
284 | bin_prices,
285 | under_bin_prices,
286 | past_bin_prices,
287 | update_query,
288 | update_lowestbin,
289 | update_underbin,
290 | last_updated,
291 | );
292 | debug!(
293 | "Parsing time: {}ms",
294 | before_page_parse.elapsed().as_millis()
295 | );
296 |
297 | debug!(
298 | "Total time: {}ms",
299 | before_page_request.elapsed().as_millis()
300 | );
301 |
302 | return is_finished;
303 | }
304 |
305 | false
306 | }
307 |
308 | /* Parses a page of auctions and updates query, lowestbin, and underbin */
309 | fn parse_auctions(
310 | auctions: Vec,
311 | inserted_uuids: &DashSet,
312 | query_prices: &Mutex>,
313 | bin_prices: &DashMap,
314 | under_bin_prices: &DashMap,
315 | past_bin_prices: &DashMap,
316 | update_query: bool,
317 | update_lowestbin: bool,
318 | update_underbin: bool,
319 | last_updated: i64,
320 | ) -> bool {
321 | let is_full_update = last_updated == 0;
322 |
323 | for auction in auctions {
324 | if !is_full_update && last_updated >= auction.last_updated {
325 | return true;
326 | }
327 |
328 | // Prevent duplicate auctions (returns false if already exists)
329 | if inserted_uuids.insert(auction.uuid.to_string()) {
330 | let mut tier = auction.tier;
331 |
332 | let nbt = &parse_nbt(&auction.item_bytes).unwrap().i[0];
333 | let extra_attrs = &nbt.tag.extra_attributes;
334 | let id = extra_attrs.id.to_owned();
335 | let mut lowestbin_id = id.to_owned();
336 | let mut lowestbin_price = auction.starting_bid as f32 / nbt.count as f32;
337 |
338 | let mut enchants = Vec::new();
339 | let mut attributes = Vec::new();
340 | if update_query {
341 | if let Some(enchantments) = &extra_attrs.enchantments {
342 | for entry in enchantments {
343 | enchants.push(format!("{};{}", entry.key().to_uppercase(), entry.value()));
344 | }
345 | }
346 | if let Some(attributes_unwrap) = &extra_attrs.attributes {
347 | for entry in attributes_unwrap {
348 | attributes.push(format!(
349 | "ATTRIBUTE_SHARD_{};{}",
350 | entry.0.to_uppercase(),
351 | entry.1
352 | ));
353 | }
354 | }
355 | }
356 |
357 | if id == "PET" {
358 | // If the pet is tier boosted, the tier field in the auction shows the rarity after boosting
359 | tier = serde_json::from_str::(extra_attrs.pet.as_ref().unwrap())
360 | .unwrap()
361 | .tier;
362 |
363 | if auction.bin && update_lowestbin {
364 | let mut split = auction.item_name.split("] ");
365 | split.next();
366 |
367 | if let Some(pet_name) = split.next() {
368 | lowestbin_id = format!(
369 | "{};{}",
370 | pet_name.replace(' ', "_").replace("_✦", "").to_uppercase(),
371 | match tier.as_str() {
372 | "COMMON" => 0,
373 | "UNCOMMON" => 1,
374 | "RARE" => 2,
375 | "EPIC" => 3,
376 | "LEGENDARY" => 4,
377 | "MYTHIC" => 5,
378 | _ => -1,
379 | }
380 | );
381 | }
382 | }
383 | }
384 |
385 | if auction.bin && update_lowestbin {
386 | if let Some(attributes) = &extra_attrs.attributes {
387 | if id == "ATTRIBUTE_SHARD" {
388 | if attributes.len() == 1 {
389 | for entry in attributes {
390 | lowestbin_id = format!("{}_{}", id, entry.0.to_uppercase());
391 | lowestbin_price /= 2_i64.pow((entry.1 - 1) as u32) as f32;
392 | }
393 | }
394 | } else {
395 | for entry in attributes {
396 | lowestbin_id.push_str("+ATTRIBUTE_SHARD_");
397 | lowestbin_id.push_str(&entry.0.to_uppercase());
398 | }
399 | }
400 | }
401 | if id == "PARTY_HAT_CRAB" || id == "PARTY_HAT_CRAB_ANIMATED" {
402 | if let Some(party_hat_color) = &extra_attrs.party_hat_color {
403 | lowestbin_id = format!(
404 | "PARTY_HAT_CRAB_{}{}",
405 | party_hat_color.to_uppercase(),
406 | if id.ends_with("_ANIMATED") {
407 | "_ANIMATED"
408 | } else {
409 | ""
410 | }
411 | );
412 | }
413 | } else if id == "PARTY_HAT_SLOTH" {
414 | if let Some(party_hat_emoji) = &extra_attrs.party_hat_emoji {
415 | lowestbin_id = format!("{}_{}", id, party_hat_emoji.to_uppercase());
416 | }
417 | } else if id == "NEW_YEAR_CAKE" {
418 | if let Some(new_years_cake) = &extra_attrs.new_years_cake {
419 | lowestbin_id = format!("{}_{}", id, new_years_cake);
420 | }
421 | } else if id == "MIDAS_SWORD" || id == "MIDAS_STAFF" {
422 | if let Some(winning_bid) = &extra_attrs.winning_bid {
423 | let best_bid = if id == "MIDAS_SWORD" {
424 | 50000000
425 | } else {
426 | 100000000
427 | };
428 | if winning_bid > &best_bid {
429 | lowestbin_id = format!("{}_{}", id, best_bid);
430 | }
431 | }
432 | } else if id == "RUNE" {
433 | if let Some(runes) = &extra_attrs.runes {
434 | if runes.len() == 1 {
435 | for entry in runes {
436 | lowestbin_id = format!(
437 | "{}_RUNE;{}",
438 | entry.key().to_uppercase(),
439 | entry.value()
440 | );
441 | }
442 | }
443 | }
444 | }
445 | if extra_attrs.is_shiny() {
446 | lowestbin_id.push_str("_SHINY");
447 | }
448 |
449 | if is_full_update {
450 | update_lower_else_insert(&lowestbin_id, lowestbin_price, bin_prices);
451 | }
452 |
453 | if update_underbin
454 | && id != "PET" // TODO: Improve under bins
455 | && !auction.item_lore.contains("Furniture")
456 | && auction.item_name != "null"
457 | && !auction.item_name.contains("Minion Skin")
458 | {
459 | if let Some(past_bin_price) = past_bin_prices.get(&lowestbin_id) {
460 | let profit = calculate_with_taxes(*past_bin_price.value())
461 | - auction.starting_bid as f32;
462 | if profit > 1000000.0 {
463 | under_bin_prices.insert(
464 | auction.uuid.clone(),
465 | json!({
466 | "uuid": auction.uuid,
467 | "name": auction.item_name,
468 | "id" : lowestbin_id,
469 | "auctioneer": auction.auctioneer,
470 | "starting_bid" : auction.starting_bid,
471 | "past_bin_price": *past_bin_price.value(),
472 | "profit": profit
473 | }),
474 | );
475 | }
476 | }
477 | }
478 | }
479 |
480 | // Push this auction to the array
481 | if update_query {
482 | let mut bids = Vec::new();
483 | for ele in auction.bids {
484 | bids.push(Bid {
485 | bidder: ele.bidder,
486 | amount: ele.amount,
487 | });
488 | }
489 |
490 | query_prices.lock().unwrap().push(QueryDatabaseItem {
491 | uuid: auction.uuid,
492 | score: None,
493 | auctioneer: auction.auctioneer,
494 | end_t: auction.end,
495 | item_name: auction.item_name,
496 | lore: format!("{}\n{}", nbt.tag.display.name, auction.item_lore),
497 | tier: tier.to_string(),
498 | starting_bid: auction.starting_bid,
499 | highest_bid: auction.highest_bid_amount,
500 | lowestbin_price,
501 | item_id: id,
502 | internal_id: lowestbin_id,
503 | enchants,
504 | attributes,
505 | bin: auction.bin,
506 | bids,
507 | count: nbt.count,
508 | potato_books: extra_attrs.hot_potato_count,
509 | stars: extra_attrs.get_stars(),
510 | farming_for_dummies: extra_attrs.farming_for_dummies_count,
511 | transmission_tuner: extra_attrs.tuned_transmission,
512 | mana_disintegrator: extra_attrs.mana_disintegrator_count,
513 | reforge: extra_attrs.modifier.to_owned(),
514 | rune: extra_attrs.get_rune(),
515 | skin: extra_attrs.skin.to_owned(),
516 | power_scroll: extra_attrs.power_ability_scroll.to_owned(),
517 | drill_upgrade_module: extra_attrs.drill_part_upgrade_module.to_owned(),
518 | drill_fuel_tank: extra_attrs.drill_part_fuel_tank.to_owned(),
519 | drill_engine: extra_attrs.drill_part_engine.to_owned(),
520 | dye: extra_attrs.dye_item.to_owned(),
521 | accessory_enrichment: extra_attrs.get_talisman_enrichment(),
522 | recombobulated: extra_attrs.is_recombobulated(),
523 | wood_singularity: extra_attrs.is_wood_singularity_applied(),
524 | art_of_war: extra_attrs.is_art_of_war_applied(),
525 | art_of_peace: extra_attrs.is_art_of_peace_applied(),
526 | etherwarp: extra_attrs.is_etherwarp_applied(),
527 | necron_scrolls: extra_attrs.ability_scroll.to_owned(),
528 | gemstones: extra_attrs.get_gemstones(),
529 | });
530 | }
531 | }
532 | }
533 |
534 | false
535 | }
536 |
537 | /* Parse ended auctions into Vec */
538 | async fn parse_ended_auctions(
539 | avg_ah_prices: &DashMap,
540 | avg_bin_prices: &DashMap,
541 | pet_prices: &DashMap,
542 | update_average_auction: bool,
543 | update_average_bin: bool,
544 | update_pets: bool,
545 | ended_auction_uuids: &DashSet,
546 | update_ended_auction_uuids: bool,
547 | started_epoch: &mut i64,
548 | ) -> bool {
549 | match get_ended_auctions().await {
550 | Some(page_request) => {
551 | *started_epoch = page_request.last_updated;
552 |
553 | for mut auction in page_request.auctions {
554 | if update_ended_auction_uuids {
555 | ended_auction_uuids.insert(auction.auction_id);
556 | }
557 |
558 | // Always update if pets is enabled, otherwise check if only auction or bin are enabled
559 | if !update_pets && !(update_average_auction && update_average_bin) {
560 | // Only update avg ah is enabled but is bin or only update avg bin is enabled but isn't bin
561 | if (update_average_auction && auction.bin)
562 | || (update_average_bin && !auction.bin)
563 | {
564 | continue;
565 | }
566 | }
567 |
568 | let nbt = &parse_nbt(&auction.item_bytes).unwrap().i[0];
569 | let extra_attrs = &nbt.tag.extra_attributes;
570 | let mut id = extra_attrs.id.to_owned();
571 |
572 | if id == "PET" {
573 | let pet_info =
574 | serde_json::from_str::(extra_attrs.pet.as_ref().unwrap()).unwrap();
575 |
576 | let item_name = MC_CODE_REGEX
577 | .replace_all(&nbt.tag.display.name, "")
578 | .to_string();
579 |
580 | if update_pets {
581 | let pet_id = format!(
582 | "{}_{}{}",
583 | item_name.replace(' ', "_").replace("_✦", ""),
584 | pet_info.tier,
585 | if let Some(held_item) = pet_info.held_item {
586 | if held_item == "PET_ITEM_TIER_BOOST" {
587 | "_TB"
588 | } else {
589 | ""
590 | }
591 | } else {
592 | ""
593 | }
594 | )
595 | .to_uppercase();
596 |
597 | if let Some(mut value) = pet_prices.get_mut(&pet_id) {
598 | value.update(auction.price, 1);
599 | } else {
600 | pet_prices.insert(
601 | pet_id,
602 | AvgSum {
603 | sum: auction.price,
604 | count: 1,
605 | },
606 | );
607 | }
608 | }
609 |
610 | let mut split = item_name.split("] ");
611 | split.next();
612 |
613 | id = format!(
614 | "{};{}",
615 | split
616 | .next()
617 | .unwrap()
618 | .replace(' ', "_")
619 | .replace("_✦", "")
620 | .to_uppercase(),
621 | match pet_info.tier.as_str() {
622 | "COMMON" => 0,
623 | "UNCOMMON" => 1,
624 | "RARE" => 2,
625 | "EPIC" => 3,
626 | "LEGENDARY" => 4,
627 | "MYTHIC" => 5,
628 | _ => -1,
629 | }
630 | );
631 | }
632 |
633 | if !update_average_bin && !update_average_auction {
634 | continue;
635 | }
636 |
637 | if let Some(attributes) = &extra_attrs.attributes {
638 | if id == "ATTRIBUTE_SHARD" {
639 | if attributes.len() == 1 {
640 | for entry in attributes {
641 | id = format!("ATTRIBUTE_SHARD_{}", entry.0.to_uppercase());
642 | auction.price /= 2_i64.pow((entry.1 - 1) as u32);
643 | }
644 | }
645 | } else if !attributes.is_empty() {
646 | // Track average of item (regardless of attributes)
647 | if update_average_bin && auction.bin {
648 | update_average_map(avg_bin_prices, &id, auction.price, nbt.count);
649 | } else if update_average_auction && !auction.bin {
650 | update_average_map(avg_ah_prices, &id, auction.price, nbt.count);
651 | }
652 |
653 | for entry in attributes {
654 | id.push_str("+ATTRIBUTE_SHARD_");
655 | id.push_str(&entry.0.to_uppercase());
656 | }
657 | }
658 | }
659 | if id == "PARTY_HAT_CRAB" || id == "PARTY_HAT_CRAB_ANIMATED" {
660 | if let Some(party_hat_color) = &extra_attrs.party_hat_color {
661 | id = format!(
662 | "PARTY_HAT_CRAB_{}{}",
663 | party_hat_color.to_uppercase(),
664 | if id.ends_with("_ANIMATED") {
665 | "_ANIMATED"
666 | } else {
667 | ""
668 | }
669 | );
670 | }
671 | } else if id == "PARTY_HAT_SLOTH" {
672 | if let Some(party_hat_emoji) = &extra_attrs.party_hat_emoji {
673 | id = format!("{}_{}", id, party_hat_emoji.to_uppercase());
674 | }
675 | } else if id == "NEW_YEAR_CAKE" {
676 | if let Some(new_years_cake) = &extra_attrs.new_years_cake {
677 | id = format!("{}_{}", id, new_years_cake);
678 | }
679 | } else if id == "MIDAS_SWORD" || id == "MIDAS_STAFF" {
680 | if let Some(winning_bid) = &extra_attrs.winning_bid {
681 | let best_bid = if id == "MIDAS_SWORD" {
682 | 50000000
683 | } else {
684 | 100000000
685 | };
686 | if winning_bid > &best_bid {
687 | id = format!("{}_{}", id, best_bid);
688 | }
689 | }
690 | } else if id == "RUNE" {
691 | if let Some(runes) = &extra_attrs.runes {
692 | if runes.len() == 1 {
693 | for entry in runes {
694 | id = format!(
695 | "{}_RUNE;{}",
696 | entry.key().to_uppercase(),
697 | entry.value()
698 | );
699 | }
700 | }
701 | }
702 | }
703 | if extra_attrs.is_shiny() {
704 | id.push_str("_SHINY");
705 | }
706 |
707 | if update_average_bin && auction.bin {
708 | update_average_map(avg_bin_prices, &id, auction.price, nbt.count);
709 | } else if update_average_auction && !auction.bin {
710 | update_average_map(avg_ah_prices, &id, auction.price, nbt.count);
711 | }
712 | }
713 | }
714 | None => {
715 | error(String::from("Failed to fetch ended auctions"));
716 | }
717 | }
718 |
719 | true
720 | }
721 |
722 | /* Gets an auction page from the Hypixel API */
723 | async fn get_auction_page(page_number: i32) -> Option {
724 | let res = HTTP_CLIENT
725 | .get(format!(
726 | "https://api.hypixel.net/skyblock/auctions?page={page_number}"
727 | ))
728 | .send()
729 | .await;
730 | if res.is_ok() {
731 | res.unwrap().json().await.ok()
732 | } else {
733 | None
734 | }
735 | }
736 |
737 | /* Gets ended auctions from the Hypixel API */
738 | async fn get_ended_auctions() -> Option {
739 | let res = HTTP_CLIENT
740 | .get("https://api.hypixel.net/skyblock/auctions_ended")
741 | .send()
742 | .await;
743 | if res.is_ok() {
744 | res.unwrap().json().await.ok()
745 | } else {
746 | None
747 | }
748 | }
749 |
--------------------------------------------------------------------------------
/src/config.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Rust Query API - A versatile API facade for the Hypixel Auction API
3 | * Copyright (c) 2022 kr45732
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU Affero General Public License as
7 | * published by the Free Software Foundation, either version 3 of the
8 | * License, or (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU Affero General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU Affero General Public License
16 | * along with this program. If not, see .
17 | */
18 |
19 | use std::{collections::HashSet, env, str::FromStr};
20 |
21 | #[derive(Debug, PartialEq, Eq, Hash)]
22 | pub enum Feature {
23 | Query,
24 | Pets,
25 | Lowestbin,
26 | Underbin,
27 | AverageAuction,
28 | AverageBin,
29 | }
30 |
31 | impl FromStr for Feature {
32 | type Err = String;
33 |
34 | fn from_str(s: &str) -> Result {
35 | Ok(match s {
36 | "QUERY" => Self::Query,
37 | "PETS" => Self::Pets,
38 | "LOWESTBIN" => Self::Lowestbin,
39 | "UNDERBIN" => Self::Underbin,
40 | "AVERAGE_AUCTION" => Self::AverageAuction,
41 | "AVERAGE_BIN" => Self::AverageBin,
42 | _ => return Err(format!("Unknown feature flag {}", s)),
43 | })
44 | }
45 | }
46 |
47 | pub struct Config {
48 | pub enabled_features: HashSet,
49 | pub webhook_url: String,
50 | pub base_url: String,
51 | pub port: u32,
52 | pub full_url: String,
53 | pub postgres_url: String,
54 | pub api_key: String,
55 | pub admin_api_key: String,
56 | pub debug: bool,
57 | pub disable_updating: bool,
58 | // Shh, don't tell anyone!
59 | pub super_secret_config_option: bool,
60 | }
61 |
62 | fn get_env(name: &str) -> String {
63 | env::var(name).unwrap_or_else(|_| panic!("Unable to find {} environment variable", name))
64 | }
65 |
66 | impl Config {
67 | pub fn load_or_panic() -> Self {
68 | let base_url = get_env("BASE_URL");
69 | let port = get_env("PORT").parse::().expect("PORT not valid");
70 | let api_key = env::var("API_KEY").unwrap_or_default();
71 | let webhook_url = env::var("WEBHOOK_URL").unwrap_or_default();
72 | let admin_api_key = env::var("ADMIN_API_KEY").unwrap_or_else(|_| api_key.clone());
73 | let debug = env::var("DEBUG")
74 | .unwrap_or_else(|_| String::from("false"))
75 | .parse()
76 | .unwrap_or(false);
77 | let disable_updating = env::var("DISABLE_UPDATING")
78 | .unwrap_or_else(|_| String::from("false"))
79 | .parse()
80 | .unwrap_or(false);
81 | let super_secret_config_option = env::var("SUPER_SECRET_CONFIG_OPTION")
82 | .unwrap_or_else(|_| String::from("false"))
83 | .parse()
84 | .unwrap_or(false);
85 | let postgres_url = get_env("POSTGRES_URL");
86 | let features = get_env("FEATURES")
87 | .replace(',', "+")
88 | .split('+')
89 | .map(|s| Feature::from_str(s).unwrap())
90 | .collect::>();
91 | if features.contains(&Feature::Lowestbin) && !features.contains(&Feature::Query) {
92 | panic!("The QUERY feature must be enabled to enable the LOWESTBIN feature");
93 | }
94 | if features.contains(&Feature::Underbin) && !features.contains(&Feature::Lowestbin) {
95 | panic!("The LOWESTBIN feature must be enabled to enable the UNDERBIN feature");
96 | }
97 | Config {
98 | enabled_features: features,
99 | full_url: format!("{}:{}", base_url, port),
100 | postgres_url,
101 | base_url,
102 | webhook_url,
103 | api_key,
104 | admin_api_key,
105 | port,
106 | debug,
107 | disable_updating,
108 | super_secret_config_option,
109 | }
110 | }
111 |
112 | pub fn is_enabled(&self, feature: Feature) -> bool {
113 | self.enabled_features.contains(&feature)
114 | }
115 | }
116 |
--------------------------------------------------------------------------------
/src/lib.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Rust Query API - A versatile API facade for the Hypixel Auction API
3 | * Copyright (c) 2022 kr45732
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU Affero General Public License as
7 | * published by the Free Software Foundation, either version 3 of the
8 | * License, or (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU Affero General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU Affero General Public License
16 | * along with this program. If not, see .
17 | */
18 |
19 | #![allow(clippy::too_many_arguments)]
20 |
21 | pub mod api_handler;
22 | pub mod config;
23 | pub mod server;
24 | pub mod statics;
25 | pub mod structs;
26 | pub mod utils;
27 | pub mod webhook;
28 |
--------------------------------------------------------------------------------
/src/main.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Rust Query API - A versatile API facade for the Hypixel Auction API
3 | * Copyright (c) 2022 kr45732
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU Affero General Public License as
7 | * published by the Free Software Foundation, either version 3 of the
8 | * License, or (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU Affero General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU Affero General Public License
16 | * along with this program. If not, see .
17 | */
18 |
19 | use deadpool_postgres::{Manager, ManagerConfig, Pool, RecyclingMethod, Runtime};
20 | use dotenv::dotenv;
21 | use query_api::{
22 | api_handler::update_auctions,
23 | config::{Config, Feature},
24 | server::start_server,
25 | statics::{BID_ARRAY, DATABASE, WEBHOOK},
26 | utils::{info, start_auction_loop},
27 | webhook::Webhook,
28 | };
29 | use simplelog::{CombinedLogger, LevelFilter, SimpleLogger, WriteLogger};
30 | use std::{
31 | error::Error,
32 | fs::{self, File},
33 | sync::Arc,
34 | };
35 | use tokio_postgres::NoTls;
36 |
37 | /* Entry point to the program. Creates loggers, reads config, creates tables, starts auction loop and server */
38 | #[tokio::main]
39 | async fn main() -> Result<(), Box> {
40 | // Read config
41 | println!("Reading config");
42 | if dotenv().is_err() {
43 | println!("Cannot find a .env file, will attempt to use environment variables");
44 | }
45 | let config = Arc::new(Config::load_or_panic());
46 |
47 | if config.debug {
48 | // Create log files
49 | CombinedLogger::init(vec![
50 | SimpleLogger::new(LevelFilter::Info, simplelog::Config::default()),
51 | WriteLogger::new(
52 | LevelFilter::Info,
53 | simplelog::Config::default(),
54 | File::create("info.log")?,
55 | ),
56 | WriteLogger::new(
57 | LevelFilter::Debug,
58 | simplelog::Config::default(),
59 | File::create("debug.log")?,
60 | ),
61 | ])
62 | .expect("Error when creating loggers");
63 | println!("Loggers Created");
64 | }
65 |
66 | if !config.webhook_url.is_empty() {
67 | let _ = WEBHOOK
68 | .lock()
69 | .await
70 | .insert(Webhook::from_url(config.webhook_url.as_str()));
71 | }
72 |
73 | if config.is_enabled(Feature::Query)
74 | || config.is_enabled(Feature::AverageAuction)
75 | || config.is_enabled(Feature::AverageBin)
76 | || config.is_enabled(Feature::Pets)
77 | {
78 | // Connect to database
79 | let database = DATABASE
80 | .lock()
81 | .await
82 | .insert(
83 | Pool::builder(Manager::from_config(
84 | config.postgres_url.parse::()?,
85 | NoTls,
86 | ManagerConfig {
87 | recycling_method: RecyclingMethod::Fast,
88 | },
89 | ))
90 | .max_size(16)
91 | .runtime(Runtime::Tokio1)
92 | .build()?,
93 | )
94 | .get()
95 | .await?;
96 |
97 | if config.is_enabled(Feature::Query) {
98 | // Create bid custom type
99 | let _ = database
100 | .simple_query(
101 | "CREATE TYPE bid AS (
102 | bidder TEXT,
103 | amount BIGINT
104 | )",
105 | )
106 | .await;
107 |
108 | // Get the bid array type and store for future use
109 | let _ = BID_ARRAY
110 | .lock()
111 | .await
112 | .insert(database.prepare("SELECT $1::_bid").await?.params()[0].clone());
113 |
114 | // Create query table if doesn't exist
115 | let _ = database
116 | .simple_query(
117 | "CREATE UNLOGGED TABLE IF NOT EXISTS query (
118 | uuid TEXT NOT NULL PRIMARY KEY,
119 | auctioneer TEXT,
120 | end_t BIGINT,
121 | item_name TEXT,
122 | lore TEXT,
123 | tier TEXT,
124 | item_id TEXT,
125 | internal_id TEXT,
126 | starting_bid BIGINT,
127 | highest_bid BIGINT,
128 | lowestbin_price REAL,
129 | enchants TEXT[],
130 | attributes TEXT[],
131 | bin BOOLEAN,
132 | bids bid[],
133 | count SMALLINT,
134 | potato_books SMALLINT,
135 | stars SMALLINT,
136 | farming_for_dummies SMALLINT,
137 | transmission_tuner SMALLINT,
138 | mana_disintegrator SMALLINT,
139 | reforge TEXT,
140 | rune TEXT,
141 | skin TEXT,
142 | power_scroll TEXT,
143 | drill_upgrade_module TEXT,
144 | drill_fuel_tank TEXT,
145 | drill_engine TEXT,
146 | dye TEXT,
147 | accessory_enrichment TEXT,
148 | recombobulated BOOLEAN,
149 | wood_singularity BOOLEAN,
150 | art_of_war BOOLEAN,
151 | art_of_peace BOOLEAN,
152 | etherwarp BOOLEAN,
153 | necron_scrolls TEXT[],
154 | gemstones TEXT[]
155 | )",
156 | )
157 | .await?;
158 | }
159 |
160 | if config.is_enabled(Feature::AverageAuction) || config.is_enabled(Feature::AverageBin) {
161 | // Create avg_ah custom type
162 | let _ = database
163 | .simple_query(
164 | "CREATE TYPE avg_ah AS (
165 | price REAL,
166 | sales REAL
167 | )",
168 | )
169 | .await;
170 |
171 | if config.is_enabled(Feature::AverageAuction) {
172 | // Create average auction table if doesn't exist
173 | let _ = database
174 | .simple_query(
175 | "CREATE TABLE IF NOT EXISTS average_auction (
176 | time_t INT,
177 | item_id TEXT,
178 | price REAL,
179 | sales REAL,
180 | PRIMARY KEY (time_t, item_id)
181 | )",
182 | )
183 | .await?;
184 |
185 | let _ = database
186 | .simple_query(
187 | "CREATE INDEX IF NOT EXISTS average_auction_time_t_idx ON average_auction (time_t)",
188 | )
189 | .await?;
190 | let _ = database
191 | .simple_query(
192 | "CREATE INDEX IF NOT EXISTS average_auction_item_id_idx ON average_auction (item_id)",
193 | )
194 | .await?;
195 | }
196 |
197 | if config.is_enabled(Feature::AverageBin) {
198 | // Create average bins table if doesn't exist
199 | let _ = database
200 | .simple_query(
201 | "CREATE TABLE IF NOT EXISTS average_bin (
202 | time_t INT,
203 | item_id TEXT,
204 | price REAL,
205 | sales REAL,
206 | PRIMARY KEY (time_t, item_id)
207 | )",
208 | )
209 | .await?;
210 |
211 | let _ = database
212 | .simple_query(
213 | "CREATE INDEX IF NOT EXISTS average_bin_time_t_idx ON average_bin (time_t)",
214 | )
215 | .await?;
216 | let _ = database
217 | .simple_query(
218 | "CREATE INDEX IF NOT EXISTS average_bin_item_id_idx ON average_bin (item_id)",
219 | )
220 | .await?;
221 | }
222 | }
223 |
224 | if config.is_enabled(Feature::Pets) {
225 | // Create pets table if doesn't exist
226 | let _ = database
227 | .simple_query(
228 | "CREATE TABLE IF NOT EXISTS pets (
229 | name TEXT NOT NULL PRIMARY KEY,
230 | price BIGINT,
231 | count INTEGER
232 | )",
233 | )
234 | .await?;
235 | }
236 | }
237 |
238 | if !config.disable_updating {
239 | // Remove any files from previous runs
240 | let _ = fs::remove_file("lowestbin.json");
241 | let _ = fs::remove_file("underbin.json");
242 | let _ = fs::remove_file("query_items.json");
243 |
244 | info(String::from("Starting auction loop..."));
245 | let auction_config = config.clone();
246 | start_auction_loop(move || {
247 | let auction_config = auction_config.clone();
248 | async move {
249 | loop {
250 | let auction_config = auction_config.clone();
251 | if update_auctions(auction_config).await {
252 | break;
253 | }
254 | }
255 | }
256 | })
257 | .await;
258 | }
259 |
260 | info(String::from("Starting server..."));
261 | start_server(config.clone()).await?;
262 |
263 | Ok(())
264 | }
265 |
--------------------------------------------------------------------------------
/src/server.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Rust Query API - A versatile API facade for the Hypixel Auction API
3 | * Copyright (c) 2022 kr45732
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU Affero General Public License as
7 | * published by the Free Software Foundation, either version 3 of the
8 | * License, or (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU Affero General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU Affero General Public License
16 | * along with this program. If not, see .
17 | */
18 |
19 | use crate::{
20 | config::{Config, Feature},
21 | statics::*,
22 | structs::*,
23 | utils::*,
24 | };
25 | use dashmap::DashMap;
26 | use futures::TryStreamExt;
27 | use http_body_util::{combinators::BoxBody, BodyExt, Full};
28 | use hyper::{
29 | body::{Body, Bytes},
30 | header,
31 | service::service_fn,
32 | Error, Method, Request, Response, StatusCode,
33 | };
34 | use hyper_util::{
35 | rt::{TokioExecutor, TokioIo},
36 | server::conn::auto,
37 | };
38 | use log::info;
39 | use postgres_types::ToSql;
40 | use reqwest::Url;
41 | use serde::Serialize;
42 | use serde_json::json;
43 | use std::{fs, net::SocketAddr, sync::Arc};
44 | use tokio::net::TcpListener;
45 | use tokio_postgres::Row;
46 |
47 | /// Starts the server listening on URL
48 | pub async fn start_server(
49 | config: Arc,
50 | ) -> Result<(), Box> {
51 | let address: SocketAddr = config.full_url.parse().unwrap();
52 | let listener = TcpListener::bind(address).await?;
53 |
54 | info(format!("Listening on http://{}", address));
55 |
56 | loop {
57 | let (tcp, _) = listener.accept().await?;
58 | let io = TokioIo::new(tcp);
59 | let captured_config = config.clone();
60 |
61 | tokio::task::spawn(async move {
62 | if let Err(err) = auto::Builder::new(TokioExecutor::new())
63 | .serve_connection(
64 | io,
65 | service_fn(move |req| handle_response(captured_config.clone(), req)),
66 | )
67 | .await
68 | {
69 | println!("Error serving connection: {:?}", err);
70 | }
71 | });
72 | }
73 | }
74 |
75 | /* Handles http requests to the server */
76 | async fn handle_response(
77 | config: Arc,
78 | req: Request,
79 | ) -> Result>, Error> {
80 | info!("{} {}", req.method(), req.uri().path());
81 |
82 | if req.method() != Method::GET {
83 | return not_implemented();
84 | }
85 |
86 | match req.uri().path() {
87 | "/" => base(config).await,
88 | "/query" => {
89 | if config.is_enabled(Feature::Query) {
90 | query(config, req).await
91 | } else {
92 | bad_request("Query feature is not enabled")
93 | }
94 | }
95 | "/query_items" => {
96 | if config.is_enabled(Feature::Query) {
97 | query_items(config, req).await
98 | } else {
99 | bad_request("Query feature is not enabled")
100 | }
101 | }
102 | "/pets" => {
103 | if config.is_enabled(Feature::Pets) {
104 | pets(config, req).await
105 | } else {
106 | bad_request("Pets feature is not enabled")
107 | }
108 | }
109 | "/lowestbin" => {
110 | if config.is_enabled(Feature::Lowestbin) {
111 | lowestbin(config, req).await
112 | } else {
113 | bad_request("Lowest bins feature is not enabled")
114 | }
115 | }
116 | "/underbin" => {
117 | if config.is_enabled(Feature::Underbin) {
118 | underbin(config, req).await
119 | } else {
120 | bad_request("Under bins feature is not enabled")
121 | }
122 | }
123 | "/average_auction" => {
124 | if config.is_enabled(Feature::AverageAuction) {
125 | averages(config, req, vec!["average_auction"]).await
126 | } else {
127 | bad_request("Average auction feature is not enabled")
128 | }
129 | }
130 | "/average_bin" => {
131 | if config.is_enabled(Feature::AverageBin) {
132 | averages(config, req, vec!["average_bin"]).await
133 | } else {
134 | bad_request("Average bin feature is not enabled")
135 | }
136 | }
137 | "/average" => {
138 | if config.is_enabled(Feature::AverageAuction) && config.is_enabled(Feature::AverageBin)
139 | {
140 | averages(config, req, vec!["average_bin", "average_auction"]).await
141 | } else {
142 | bad_request("Both average auction and average bin feature are not enabled")
143 | }
144 | }
145 | "/debug" => {
146 | if config.debug {
147 | debug_log(config, req).await
148 | } else {
149 | bad_request("Debug is not enabled")
150 | }
151 | }
152 | "/info" => {
153 | if config.debug {
154 | info_log(config, req).await
155 | } else {
156 | bad_request("Debug is not enabled")
157 | }
158 | }
159 | _ => not_found(),
160 | }
161 | }
162 |
163 | async fn debug_log(
164 | config: Arc,
165 | req: Request,
166 | ) -> Result>, Error> {
167 | let mut key = String::new();
168 |
169 | // Reads the query parameters from the request and stores them in the corresponding variable
170 | for query_pair in Url::parse(&format!(
171 | "http://{}{}",
172 | config.full_url,
173 | &req.uri().to_string()
174 | ))
175 | .unwrap()
176 | .query_pairs()
177 | {
178 | if query_pair.0 == "key" {
179 | key = query_pair.1.to_string();
180 | }
181 | }
182 |
183 | if !valid_api_key(config, key, true) {
184 | return unauthorized();
185 | }
186 |
187 | let file_result = fs::read("debug.log");
188 | if file_result.is_err() {
189 | return internal_error("Unable to open or read debug.log");
190 | }
191 |
192 | Ok(Response::builder()
193 | .status(StatusCode::OK)
194 | .body(file_body(file_result))
195 | .unwrap())
196 | }
197 |
198 | async fn info_log(
199 | config: Arc,
200 | req: Request,
201 | ) -> Result>, Error> {
202 | let mut key = String::new();
203 |
204 | // Reads the query parameters from the request and stores them in the corresponding variable
205 | for query_pair in Url::parse(&format!(
206 | "http://{}{}",
207 | config.full_url,
208 | &req.uri().to_string()
209 | ))
210 | .unwrap()
211 | .query_pairs()
212 | {
213 | if query_pair.0 == "key" {
214 | key = query_pair.1.to_string();
215 | }
216 | }
217 |
218 | if !valid_api_key(config, key, true) {
219 | return unauthorized();
220 | }
221 |
222 | let file_result = fs::read("info.log");
223 | if file_result.is_err() {
224 | return internal_error("Unable to open or read info.log");
225 | }
226 |
227 | Ok(Response::builder()
228 | .status(StatusCode::OK)
229 | .body(file_body(file_result))
230 | .unwrap())
231 | }
232 |
233 | async fn pets(
234 | config: Arc,
235 | req: Request,
236 | ) -> Result>, Error> {
237 | let mut query = String::new();
238 | let mut key = String::new();
239 |
240 | // Reads the query parameters from the request and stores them in the corresponding variable
241 | for query_pair in Url::parse(&format!(
242 | "http://{}{}",
243 | config.full_url,
244 | &req.uri().to_string()
245 | ))
246 | .unwrap()
247 | .query_pairs()
248 | {
249 | if query_pair.0 == "query" {
250 | query = query_pair.1.to_string();
251 | } else if query_pair.0 == "key" {
252 | key = query_pair.1.to_string();
253 | }
254 | }
255 |
256 | // The API key in request doesn't match
257 | if !valid_api_key(config, key, false) {
258 | return unauthorized();
259 | }
260 |
261 | if query.is_empty() {
262 | return bad_request("The query parameter cannot be empty");
263 | }
264 |
265 | let mut sql: String = String::from("SELECT * FROM pets WHERE name IN (");
266 | let mut param_vec: Vec> = Vec::new();
267 | let mut param_count = 1;
268 |
269 | let mut split = query.split(',');
270 | for pet_name in split.by_ref() {
271 | if param_count != 1 {
272 | sql.push(',');
273 | }
274 | sql.push_str(&format!("${}", param_count));
275 | param_vec.push(Box::new(pet_name.to_string()));
276 | param_count += 1;
277 | }
278 | sql.push(')');
279 |
280 | let out: &Vec<&String> = ¶m_vec
281 | .iter()
282 | .map(std::ops::Deref::deref)
283 | .collect::>();
284 |
285 | // Find and sort using query JSON
286 | let results_cursor = get_client().await.query_raw(&sql, out).await;
287 |
288 | if let Err(e) = results_cursor {
289 | return internal_error(&format!("Error when querying database: {}", e));
290 | }
291 |
292 | // Convert the cursor iterator to a vector
293 | let results_vec: Vec = results_cursor
294 | .unwrap()
295 | .try_collect::>()
296 | .await
297 | .unwrap()
298 | .into_iter()
299 | .map(PetsDatabaseItem::from)
300 | .collect();
301 |
302 | // Return the vector of auctions serialized into JSON
303 | Ok(Response::builder()
304 | .status(StatusCode::OK)
305 | .header(header::CONTENT_TYPE, "application/json")
306 | .body(json_body(&results_vec))
307 | .unwrap())
308 | }
309 |
310 | async fn averages(
311 | config: Arc,
312 | req: Request,
313 | tables: Vec<&str>,
314 | ) -> Result>, Error> {
315 | let mut key = String::new();
316 | let mut time = 0;
317 | let mut step = 60;
318 | let mut center = String::from("mean");
319 | let mut percent = 0.25;
320 |
321 | // Reads the query parameters from the request and stores them in the corresponding variable
322 | for query_pair in Url::parse(&format!(
323 | "http://{}{}",
324 | config.full_url,
325 | &req.uri().to_string()
326 | ))
327 | .unwrap()
328 | .query_pairs()
329 | {
330 | match query_pair.0.to_string().as_str() {
331 | "time" => match query_pair.1.to_string().parse::() {
332 | Ok(time_int) => time = time_int,
333 | Err(e) => return bad_request(&format!("Error parsing time parameter: {}", e)),
334 | },
335 | "step" => match query_pair.1.to_string().parse::() {
336 | Ok(step_int) => step = step_int,
337 | Err(e) => return bad_request(&format!("Error parsing step parameter: {}", e)),
338 | },
339 | "key" => key = query_pair.1.to_string(),
340 | "center" => center = query_pair.1.to_string(),
341 | "percent" => match query_pair.1.to_string().parse::() {
342 | Ok(percent_float) => percent = percent_float,
343 | Err(e) => return bad_request(&format!("Error parsing percent parameter: {}", e)),
344 | },
345 | _ => {}
346 | }
347 | }
348 |
349 | // The API key in request doesn't match
350 | if !valid_api_key(config, key, false) {
351 | return unauthorized();
352 | }
353 |
354 | if time < 0 {
355 | return bad_request("The time parameter cannot be negative");
356 | }
357 |
358 | if step <= 0 {
359 | return bad_request("The step parameter must be positive");
360 | }
361 |
362 | if percent <= 0.0 || percent >= 1.0 {
363 | return bad_request("The percent parameter must be between 0 and 1");
364 | }
365 |
366 | // Map each item id to its prices and sales
367 | let avg_map: DashMap = DashMap::new();
368 |
369 | for table in tables {
370 | // Find and sort using query JSON
371 | let results_cursor = get_client()
372 | .await
373 | .query(
374 | &format!("SELECT item_id, ARRAY_AGG((price, sales)::avg_ah) prices FROM {table} WHERE time_t > $1 GROUP BY item_id"),
375 | &[&time],
376 | )
377 | .await;
378 |
379 | if let Err(e) = results_cursor {
380 | return internal_error(&format!("Error when querying database: {}", e));
381 | }
382 |
383 | for row in results_cursor.unwrap() {
384 | let mut row_parsed = AverageDatabaseItem::from(row);
385 | if let Some(mut value) = avg_map.get_mut(&row_parsed.item_id) {
386 | value.prices.append(&mut row_parsed.prices);
387 | } else {
388 | avg_map.insert(row_parsed.item_id.to_string(), row_parsed);
389 | }
390 | }
391 | }
392 |
393 | let start = time.max(get_timestamp_secs() - 604800);
394 | let end = get_timestamp_secs();
395 | let count = (((end - start) / 60 + 1) / step) as f32;
396 |
397 | let avg_map_final: DashMap = DashMap::new();
398 | for ele in avg_map {
399 | avg_map_final.insert(
400 | ele.0,
401 | PartialAvgAh {
402 | price: match center.as_str() {
403 | "median" => ele.1.get_median(),
404 | "modified_median" => ele.1.get_modified_median(percent),
405 | _ => ele.1.get_average(),
406 | },
407 | sales: ele.1.get_sales(count),
408 | },
409 | );
410 | }
411 |
412 | // Return the vector of auctions or bins serialized into JSON
413 | Ok(Response::builder()
414 | .status(StatusCode::OK)
415 | .header(header::CONTENT_TYPE, "application/json")
416 | .body(json_body(&avg_map_final))
417 | .unwrap())
418 | }
419 |
420 | async fn query(
421 | config: Arc,
422 | req: Request,
423 | ) -> Result>, Error> {
424 | let mut query = String::new();
425 | let mut sort_by = String::new();
426 | let mut sort_order = String::new();
427 | let mut limit = 1;
428 | let mut key = String::new();
429 | let mut item_name = String::new();
430 | let mut tier = String::new();
431 | let mut item_id = String::new();
432 | let mut internal_id = String::new();
433 | let mut enchants = String::new();
434 | let mut attributes = String::new();
435 | let mut end = -1;
436 | let mut bids = String::new();
437 | let mut bin = Option::None;
438 | let mut potato_books = -1;
439 | let mut stars = -1;
440 | let mut farming_for_dummies = -1;
441 | let mut transmission_tuner = -1;
442 | let mut mana_disintegrator = -1;
443 | let mut reforge = String::new();
444 | let mut rune = String::new();
445 | let mut skin = String::new();
446 | let mut power_scroll = String::new();
447 | let mut drill_upgrade_module = String::new();
448 | let mut drill_fuel_tank = String::new();
449 | let mut drill_engine = String::new();
450 | let mut dye = String::new();
451 | let mut accessory_enrichment = String::new();
452 | let mut recombobulated = Option::None;
453 | let mut wood_singularity = Option::None;
454 | let mut art_of_war = Option::None;
455 | let mut art_of_peace = Option::None;
456 | let mut etherwarp = Option::None;
457 | let mut necron_scrolls = String::new();
458 | let mut gemstones = String::new();
459 |
460 | // Reads the query parameters from the request and stores them in the corresponding variable
461 | for query_pair in Url::parse(&format!(
462 | "http://{}{}",
463 | config.full_url,
464 | &req.uri().to_string()
465 | ))
466 | .unwrap()
467 | .query_pairs()
468 | {
469 | match query_pair.0.to_string().as_str() {
470 | "query" => query = query_pair.1.to_string(),
471 | "sort_by" => sort_by = query_pair.1.to_string(),
472 | "sort_order" => sort_order = query_pair.1.to_string(),
473 | "limit" => match query_pair.1.to_string().parse::() {
474 | Ok(limit_int) => limit = limit_int,
475 | Err(e) => return bad_request(&format!("Error parsing limit parameter: {}", e)),
476 | },
477 | "key" => key = query_pair.1.to_string(),
478 | "item_name" => item_name = query_pair.1.to_string(),
479 | "tier" => tier = query_pair.1.to_string(),
480 | "item_id" => item_id = query_pair.1.to_string(),
481 | "internal_id" => internal_id = query_pair.1.to_string(),
482 | "enchants" => enchants = query_pair.1.to_string(),
483 | "attributes" => attributes = query_pair.1.to_string(),
484 | "end" => match query_pair.1.to_string().parse::() {
485 | Ok(end_int) => end = end_int,
486 | Err(e) => return bad_request(&format!("Error parsing end parameter: {}", e)),
487 | },
488 | "bids" => bids = query_pair.1.to_string(),
489 | "bin" => match query_pair.1.to_string().parse::() {
490 | Ok(bin_bool) => bin = Some(bin_bool),
491 | Err(e) => return bad_request(&format!("Error parsing bin parameter: {}", e)),
492 | },
493 | "potato_books" => match query_pair.1.to_string().parse::() {
494 | Ok(potato_books_int) => potato_books = potato_books_int,
495 | Err(e) => {
496 | return bad_request(&format!("Error parsing potato_books parameter: {}", e))
497 | }
498 | },
499 | "stars" => match query_pair.1.to_string().parse::() {
500 | Ok(stars_int) => stars = stars_int,
501 | Err(e) => return bad_request(&format!("Error parsing stars parameter: {}", e)),
502 | },
503 | "farming_for_dummies" => match query_pair.1.to_string().parse::() {
504 | Ok(farming_for_dummies_int) => farming_for_dummies = farming_for_dummies_int,
505 | Err(e) => {
506 | return bad_request(&format!(
507 | "Error parsing farming_for_dummies parameter: {}",
508 | e
509 | ))
510 | }
511 | },
512 | "transmission_tuner" => match query_pair.1.to_string().parse::() {
513 | Ok(transmission_tuner_int) => transmission_tuner = transmission_tuner_int,
514 | Err(e) => {
515 | return bad_request(&format!(
516 | "Error parsing transmission_tuner parameter: {}",
517 | e
518 | ))
519 | }
520 | },
521 | "mana_disintegrator" => match query_pair.1.to_string().parse::() {
522 | Ok(mana_disintegrator_int) => mana_disintegrator = mana_disintegrator_int,
523 | Err(e) => {
524 | return bad_request(&format!(
525 | "Error parsing mana_disintegrator parameter: {}",
526 | e
527 | ))
528 | }
529 | },
530 | "reforge" => reforge = query_pair.1.to_string(),
531 | "rune" => rune = query_pair.1.to_string(),
532 | "skin" => skin = query_pair.1.to_string(),
533 | "power_scroll" => power_scroll = query_pair.1.to_string(),
534 | "drill_upgrade_module" => drill_upgrade_module = query_pair.1.to_string(),
535 | "drill_fuel_tank" => drill_fuel_tank = query_pair.1.to_string(),
536 | "drill_engine" => drill_engine = query_pair.1.to_string(),
537 | "dye" => dye = query_pair.1.to_string(),
538 | "accessory_enrichment" => accessory_enrichment = query_pair.1.to_string(),
539 | "recombobulated" => match query_pair.1.to_string().parse::() {
540 | Ok(recombobulated_bool) => recombobulated = Some(recombobulated_bool),
541 | Err(e) => {
542 | return bad_request(&format!("Error parsing recombobulated parameter: {}", e))
543 | }
544 | },
545 | "wood_singularity" => match query_pair.1.to_string().parse::() {
546 | Ok(wood_singularity_bool) => wood_singularity = Some(wood_singularity_bool),
547 | Err(e) => {
548 | return bad_request(&format!("Error parsing wood_singularity parameter: {}", e))
549 | }
550 | },
551 | "art_of_war" => match query_pair.1.to_string().parse::() {
552 | Ok(art_of_war_bool) => art_of_war = Some(art_of_war_bool),
553 | Err(e) => {
554 | return bad_request(&format!("Error parsing art_of_war parameter: {}", e))
555 | }
556 | },
557 | "art_of_peace" => match query_pair.1.to_string().parse::() {
558 | Ok(art_of_peace_bool) => art_of_peace = Some(art_of_peace_bool),
559 | Err(e) => {
560 | return bad_request(&format!("Error parsing art_of_peace parameter: {}", e))
561 | }
562 | },
563 | "etherwarp" => match query_pair.1.to_string().parse::() {
564 | Ok(etherwarp_bool) => etherwarp = Some(etherwarp_bool),
565 | Err(e) => return bad_request(&format!("Error parsing etherwarp parameter: {}", e)),
566 | },
567 | "necron_scrolls" => necron_scrolls = query_pair.1.to_string(),
568 | "gemstones" => gemstones = query_pair.1.to_string(),
569 | _ => {}
570 | }
571 | }
572 |
573 | if !valid_api_key(config.clone(), key.to_owned(), false) {
574 | return unauthorized();
575 | }
576 | // Prevent fetching too many rows
577 | if (limit <= 0 || limit >= 500) && !valid_api_key(config.clone(), key.to_owned(), true) {
578 | return unauthorized();
579 | }
580 |
581 | let database_ref = get_client().await;
582 | let results_cursor;
583 |
584 | // Find and sort using query
585 | if query.is_empty() {
586 | let mut sql = String::new();
587 | let mut param_vec: Vec<&(dyn ToSql + Sync)> = Vec::new();
588 | let mut param_count = 1;
589 |
590 | let sort_by_query = sort_by == "query";
591 | let mut sort_by_query_end_sql = String::new();
592 |
593 | if !sort_by_query {
594 | if !bids.is_empty() {
595 | // TODO: support bids in sort_by query
596 | sql =
597 | String::from("SELECT * FROM query, unnest(bids) AS bid WHERE bid.bidder = $1");
598 | param_vec.push(&bids);
599 | param_count += 1;
600 | } else {
601 | sql = String::from("SELECT * FROM query WHERE");
602 | }
603 | }
604 |
605 | param_count = int_eq(
606 | &mut sql,
607 | &mut param_vec,
608 | "stars",
609 | &stars,
610 | param_count,
611 | sort_by_query,
612 | );
613 | param_count = int_eq(
614 | &mut sql,
615 | &mut param_vec,
616 | "potato_books",
617 | &potato_books,
618 | param_count,
619 | sort_by_query,
620 | );
621 | param_count = int_eq(
622 | &mut sql,
623 | &mut param_vec,
624 | "farming_for_dummies",
625 | &farming_for_dummies,
626 | param_count,
627 | sort_by_query,
628 | );
629 | param_count = int_eq(
630 | &mut sql,
631 | &mut param_vec,
632 | "transmission_tuner",
633 | &transmission_tuner,
634 | param_count,
635 | sort_by_query,
636 | );
637 | param_count = int_eq(
638 | &mut sql,
639 | &mut param_vec,
640 | "mana_disintegrator",
641 | &mana_disintegrator,
642 | param_count,
643 | sort_by_query,
644 | );
645 |
646 | param_count = str_eq(
647 | &mut sql,
648 | &mut param_vec,
649 | "reforge",
650 | &reforge,
651 | param_count,
652 | sort_by_query,
653 | );
654 | param_count = str_eq(
655 | &mut sql,
656 | &mut param_vec,
657 | "rune",
658 | &rune,
659 | param_count,
660 | sort_by_query,
661 | );
662 | param_count = str_eq(
663 | &mut sql,
664 | &mut param_vec,
665 | "skin",
666 | &skin,
667 | param_count,
668 | sort_by_query,
669 | );
670 | param_count = str_eq(
671 | &mut sql,
672 | &mut param_vec,
673 | "tier",
674 | &tier,
675 | param_count,
676 | sort_by_query,
677 | );
678 | param_count = str_eq(
679 | &mut sql,
680 | &mut param_vec,
681 | "dye",
682 | &dye,
683 | param_count,
684 | sort_by_query,
685 | );
686 | param_count = str_eq(
687 | &mut sql,
688 | &mut param_vec,
689 | "internal_id",
690 | &internal_id,
691 | param_count,
692 | sort_by_query,
693 | );
694 | param_count = str_eq(
695 | &mut sql,
696 | &mut param_vec,
697 | "power_scroll",
698 | &power_scroll,
699 | param_count,
700 | sort_by_query,
701 | );
702 | param_count = str_eq(
703 | &mut sql,
704 | &mut param_vec,
705 | "drill_upgrade_module",
706 | &drill_upgrade_module,
707 | param_count,
708 | sort_by_query,
709 | );
710 | param_count = str_eq(
711 | &mut sql,
712 | &mut param_vec,
713 | "drill_fuel_tank",
714 | &drill_fuel_tank,
715 | param_count,
716 | sort_by_query,
717 | );
718 | param_count = str_eq(
719 | &mut sql,
720 | &mut param_vec,
721 | "drill_engine",
722 | &drill_engine,
723 | param_count,
724 | sort_by_query,
725 | );
726 | param_count = str_eq(
727 | &mut sql,
728 | &mut param_vec,
729 | "accessory_enrichment",
730 | &accessory_enrichment,
731 | param_count,
732 | sort_by_query,
733 | );
734 |
735 | param_count = bool_eq(
736 | &mut sql,
737 | &mut param_vec,
738 | "bin",
739 | &bin,
740 | param_count,
741 | sort_by_query,
742 | );
743 | param_count = bool_eq(
744 | &mut sql,
745 | &mut param_vec,
746 | "recombobulated",
747 | &recombobulated,
748 | param_count,
749 | sort_by_query,
750 | );
751 | param_count = bool_eq(
752 | &mut sql,
753 | &mut param_vec,
754 | "wood_singularity",
755 | &wood_singularity,
756 | param_count,
757 | sort_by_query,
758 | );
759 | param_count = bool_eq(
760 | &mut sql,
761 | &mut param_vec,
762 | "art_of_war",
763 | &art_of_war,
764 | param_count,
765 | sort_by_query,
766 | );
767 | param_count = bool_eq(
768 | &mut sql,
769 | &mut param_vec,
770 | "art_of_peace",
771 | &art_of_peace,
772 | param_count,
773 | sort_by_query,
774 | );
775 | param_count = bool_eq(
776 | &mut sql,
777 | &mut param_vec,
778 | "etherwarp",
779 | ðerwarp,
780 | param_count,
781 | sort_by_query,
782 | );
783 |
784 | let enchants_split: Vec;
785 | if !enchants.is_empty() {
786 | enchants_split = enchants.split(',').map(|s| s.trim().to_string()).collect();
787 | param_count = array_contains(
788 | &mut sql,
789 | &mut param_vec,
790 | "enchants",
791 | &enchants_split,
792 | param_count,
793 | sort_by_query,
794 | );
795 | }
796 | let attributes_split: Vec;
797 | if !attributes.is_empty() {
798 | attributes_split = attributes
799 | .split(',')
800 | .map(|s| s.trim().to_string())
801 | .collect();
802 | param_count = array_contains(
803 | &mut sql,
804 | &mut param_vec,
805 | "attributes",
806 | &attributes_split,
807 | param_count,
808 | sort_by_query,
809 | );
810 | }
811 | let necron_scrolls_split: Vec;
812 | if !necron_scrolls.is_empty() {
813 | necron_scrolls_split = necron_scrolls
814 | .split(',')
815 | .map(|s| s.trim().to_string())
816 | .collect();
817 | param_count = array_contains(
818 | &mut sql,
819 | &mut param_vec,
820 | "necron_scrolls",
821 | &necron_scrolls_split,
822 | param_count,
823 | sort_by_query,
824 | );
825 | }
826 | let gemstones_split: Vec;
827 | if !gemstones.is_empty() {
828 | gemstones_split = gemstones.split(',').map(|s| s.trim().to_string()).collect();
829 | param_count = array_contains(
830 | &mut sql,
831 | &mut param_vec,
832 | "gemstones",
833 | &gemstones_split,
834 | param_count,
835 | sort_by_query,
836 | );
837 | }
838 |
839 | if !item_id.is_empty() {
840 | if sort_by_query {
841 | if !sort_by_query_end_sql.is_empty() {
842 | sort_by_query_end_sql.push_str(" AND");
843 | }
844 | sort_by_query_end_sql.push_str(&format!(" item_id = ${}", param_count));
845 | } else {
846 | if param_count != 1 {
847 | sql.push_str(" AND");
848 | }
849 | sql.push_str(&format!(" item_id = ${}", param_count));
850 | }
851 | param_vec.push(&item_id);
852 | param_count += 1;
853 | }
854 | if end >= 0 {
855 | if sort_by_query {
856 | if !sort_by_query_end_sql.is_empty() {
857 | sort_by_query_end_sql.push_str(" AND");
858 | }
859 | sort_by_query_end_sql.push_str(&format!(" end_t > ${}", param_count));
860 | } else {
861 | if param_count != 1 {
862 | sql.push_str(" AND");
863 | }
864 | sql.push_str(&format!(" end_t > ${}", param_count));
865 | }
866 | param_vec.push(&end);
867 | param_count += 1;
868 | }
869 | if !item_name.is_empty() {
870 | if sort_by_query {
871 | if !sort_by_query_end_sql.is_empty() {
872 | sort_by_query_end_sql.push_str(" AND");
873 | }
874 | sort_by_query_end_sql.push_str(&format!(" item_name ILIKE ${}", param_count));
875 | } else {
876 | if param_count != 1 {
877 | sql.push_str(" AND");
878 | }
879 | sql.push_str(&format!(" item_name ILIKE ${}", param_count));
880 | }
881 | param_vec.push(&item_name);
882 | param_count += 1;
883 | }
884 |
885 | // Handle unfinished WHERE
886 | if sort_by_query && sort_by_query_end_sql.is_empty() {
887 | sort_by_query_end_sql.push_str(" 1=1");
888 | } else if param_count == 1 {
889 | sql.push_str(" 1=1");
890 | }
891 |
892 | if sort_by_query {
893 | sort_by_query_end_sql.push_str(" ORDER BY score DESC, cur_bid");
894 | } else if (sort_by == "starting_bid" || sort_by == "highest_bid")
895 | && (sort_order == "ASC" || sort_order == "DESC")
896 | {
897 | sql.push_str(&format!(" ORDER BY {} {}", sort_by, sort_order));
898 | };
899 |
900 | if limit > 0 {
901 | if sort_by_query {
902 | sort_by_query_end_sql.push_str(&format!(" LIMIT ${}", param_count));
903 | } else {
904 | sql.push_str(&format!(" LIMIT ${}", param_count));
905 | }
906 | param_vec.push(&limit);
907 | }
908 |
909 | if sort_by_query {
910 | sql = format!(
911 | "SELECT *,{} AS score, GREATEST(starting_bid, highest_bid) AS cur_bid FROM query WHERE{}",
912 | if sql.is_empty() { "0" } else { &sql },
913 | sort_by_query_end_sql
914 | );
915 | }
916 |
917 | results_cursor = database_ref.query(&sql, ¶m_vec).await;
918 | } else {
919 | if !valid_api_key(config, key, true) {
920 | return unauthorized();
921 | }
922 |
923 | results_cursor = database_ref
924 | .query(&format!("SELECT * FROM query WHERE {}", query), &[])
925 | .await;
926 | }
927 |
928 | if let Err(e) = results_cursor {
929 | return internal_error(&format!("Error when querying database: {}", e));
930 | }
931 |
932 | // Convert the cursor iterator to a vector
933 | let results_vec = results_cursor
934 | .unwrap()
935 | .into_iter()
936 | .map(QueryDatabaseItem::from)
937 | .collect::>();
938 |
939 | // Return the vector of auctions serialized into JSON
940 | Ok(Response::builder()
941 | .status(StatusCode::OK)
942 | .header(header::CONTENT_TYPE, "application/json")
943 | .body(json_body(&results_vec))
944 | .unwrap())
945 | }
946 |
947 | async fn query_items(
948 | config: Arc,
949 | req: Request,
950 | ) -> Result>, Error> {
951 | let mut key = String::new();
952 |
953 | // Reads the query parameters from the request and stores them in the corresponding variable
954 | for query_pair in Url::parse(&format!(
955 | "http://{}{}",
956 | config.full_url,
957 | &req.uri().to_string()
958 | ))
959 | .unwrap()
960 | .query_pairs()
961 | {
962 | if query_pair.0 == "key" {
963 | key = query_pair.1.to_string();
964 | }
965 | }
966 |
967 | if !valid_api_key(config, key, false) {
968 | return unauthorized();
969 | }
970 |
971 | let file_result = fs::read("query_items.json");
972 | if file_result.is_err() {
973 | return internal_error("Unable to open or read query_items.json");
974 | }
975 |
976 | Ok(Response::builder()
977 | .status(StatusCode::OK)
978 | .header(header::CONTENT_TYPE, "application/json")
979 | .body(file_body(file_result))
980 | .unwrap())
981 | }
982 |
983 | async fn lowestbin(
984 | config: Arc,
985 | req: Request,
986 | ) -> Result>, Error> {
987 | let mut key = String::new();
988 |
989 | // Reads the query parameters from the request and stores them in the corresponding variable
990 | for query_pair in Url::parse(&format!("http://{}{}", config.full_url, &req.uri()))
991 | .unwrap()
992 | .query_pairs()
993 | {
994 | if query_pair.0 == "key" {
995 | key = query_pair.1.to_string();
996 | }
997 | }
998 |
999 | if !valid_api_key(config, key, false) {
1000 | return unauthorized();
1001 | }
1002 |
1003 | let file_result = fs::read("lowestbin.json");
1004 | if file_result.is_err() {
1005 | return internal_error("Unable to open or read lowestbin.json");
1006 | }
1007 |
1008 | Ok(Response::builder()
1009 | .status(StatusCode::OK)
1010 | .header(header::CONTENT_TYPE, "application/json")
1011 | .body(file_body(file_result))
1012 | .unwrap())
1013 | }
1014 |
1015 | async fn underbin(
1016 | config: Arc,
1017 | req: Request,
1018 | ) -> Result>, Error> {
1019 | let mut key = String::new();
1020 |
1021 | // Reads the query parameters from the request and stores them in the corresponding variable
1022 | for query_pair in Url::parse(&format!("http://{}{}", config.full_url, &req.uri()))
1023 | .unwrap()
1024 | .query_pairs()
1025 | {
1026 | if query_pair.0 == "key" {
1027 | key = query_pair.1.to_string();
1028 | }
1029 | }
1030 |
1031 | if !valid_api_key(config, key, false) {
1032 | return unauthorized();
1033 | }
1034 |
1035 | let file_result = fs::read("underbin.json");
1036 | if file_result.is_err() {
1037 | return internal_error("Unable to open or read underbin.json");
1038 | }
1039 |
1040 | Ok(Response::builder()
1041 | .status(StatusCode::OK)
1042 | .header(header::CONTENT_TYPE, "application/json")
1043 | .body(file_body(file_result))
1044 | .unwrap())
1045 | }
1046 |
1047 | async fn base(config: Arc) -> Result>, Error> {
1048 | Ok(Response::builder()
1049 | .status(StatusCode::OK)
1050 | .header(header::CONTENT_TYPE, "application/json")
1051 | .body(json_body(&json!({
1052 | "success":true,
1053 | "enabled_features": {
1054 | "query":config.is_enabled(Feature::Query),
1055 | "pets":config.is_enabled(Feature::Pets),
1056 | "lowestbin":config.is_enabled(Feature::Lowestbin),
1057 | "underbin": config.is_enabled(Feature::Underbin),
1058 | "average_auction":config.is_enabled(Feature::AverageAuction),
1059 | "average_bin":config.is_enabled(Feature::AverageBin),
1060 | },
1061 | "statistics": {
1062 | "is_updating":*IS_UPDATING.lock().await,
1063 | "total_updates":*TOTAL_UPDATES.lock().await,
1064 | "last_updated":*LAST_UPDATED.lock().await
1065 | }
1066 | })))
1067 | .unwrap())
1068 | }
1069 |
1070 | fn bool_eq<'a>(
1071 | sql: &mut String,
1072 | param_vec: &mut Vec<&'a (dyn ToSql + Sync)>,
1073 | param_name: &str,
1074 | param_value: &'a Option,
1075 | param_count: i32,
1076 | sort_by_query: bool,
1077 | ) -> i32 {
1078 | if let Some(param_value) = param_value {
1079 | return param_eq(
1080 | sql,
1081 | param_vec,
1082 | param_name,
1083 | param_value,
1084 | param_count,
1085 | sort_by_query,
1086 | );
1087 | }
1088 |
1089 | param_count
1090 | }
1091 |
1092 | fn int_eq<'a>(
1093 | sql: &mut String,
1094 | param_vec: &mut Vec<&'a (dyn ToSql + Sync)>,
1095 | param_name: &str,
1096 | param_value: &'a i16,
1097 | param_count: i32,
1098 | sort_by_query: bool,
1099 | ) -> i32 {
1100 | if param_value >= &0 {
1101 | return param_eq(
1102 | sql,
1103 | param_vec,
1104 | param_name,
1105 | param_value,
1106 | param_count,
1107 | sort_by_query,
1108 | );
1109 | }
1110 |
1111 | param_count
1112 | }
1113 |
1114 | fn str_eq<'a>(
1115 | sql: &mut String,
1116 | param_vec: &mut Vec<&'a (dyn ToSql + Sync)>,
1117 | param_name: &str,
1118 | param_value: &'a String,
1119 | param_count: i32,
1120 | sort_by_query: bool,
1121 | ) -> i32 {
1122 | if !param_value.is_empty() {
1123 | return param_eq(
1124 | sql,
1125 | param_vec,
1126 | param_name,
1127 | param_value,
1128 | param_count,
1129 | sort_by_query,
1130 | );
1131 | }
1132 |
1133 | param_count
1134 | }
1135 |
1136 | fn param_eq<'a>(
1137 | sql: &mut String,
1138 | param_vec: &mut Vec<&'a (dyn ToSql + Sync)>,
1139 | param_name: &str,
1140 | param_value: &'a (dyn ToSql + Sync),
1141 | param_count: i32,
1142 | sort_by_query: bool,
1143 | ) -> i32 {
1144 | if param_count != 1 {
1145 | sql.push_str(if sort_by_query { " +" } else { " AND" });
1146 | }
1147 | if sort_by_query {
1148 | sql.push_str(" CASE WHEN")
1149 | }
1150 |
1151 | sql.push_str(&format!(" {} = ${}", param_name, param_count));
1152 | param_vec.push(param_value);
1153 |
1154 | if sort_by_query {
1155 | sql.push_str(" THEN 1 ELSE 0 END")
1156 | }
1157 |
1158 | param_count + 1
1159 | }
1160 |
1161 | fn array_contains<'a>(
1162 | sql: &mut String,
1163 | param_vec: &mut Vec<&'a (dyn ToSql + Sync)>,
1164 | param_name: &str,
1165 | param_value: &'a [String],
1166 | param_count: i32,
1167 | sort_by_query: bool,
1168 | ) -> i32 {
1169 | if param_count != 1 {
1170 | sql.push_str(if sort_by_query { " +" } else { " AND" });
1171 | }
1172 |
1173 | let mut param_count_mut = param_count;
1174 |
1175 | if sort_by_query {
1176 | sql.push_str(" cardinality(ARRAY(SELECT unnest(ARRAY[");
1177 | } else {
1178 | sql.push(' ');
1179 | sql.push_str(param_name);
1180 | sql.push_str(" @> ARRAY[");
1181 | }
1182 |
1183 | let start_param_count = param_count;
1184 | for enchant in param_value.iter() {
1185 | if param_count_mut != start_param_count {
1186 | sql.push(',');
1187 | }
1188 |
1189 | sql.push_str(&format!("${}", param_count_mut));
1190 | param_vec.push(enchant);
1191 | param_count_mut += 1;
1192 | }
1193 |
1194 | sql.push(']');
1195 | if sort_by_query {
1196 | sql.push_str(") intersect SELECT unnest(");
1197 | sql.push_str(param_name);
1198 | sql.push_str(")))");
1199 | }
1200 |
1201 | param_count_mut
1202 | }
1203 |
1204 | fn http_err(status: StatusCode, reason: &str) -> Result>, Error> {
1205 | Ok(Response::builder()
1206 | .status(status)
1207 | .header(header::CONTENT_TYPE, "application/json")
1208 | .body(json_body(&json!({"success": false, "reason": reason})))
1209 | .unwrap())
1210 | }
1211 |
1212 | fn bad_request(reason: &str) -> Result>, Error> {
1213 | http_err(StatusCode::BAD_REQUEST, reason)
1214 | }
1215 |
1216 | fn internal_error(reason: &str) -> Result>, Error> {
1217 | http_err(StatusCode::INTERNAL_SERVER_ERROR, reason)
1218 | }
1219 |
1220 | fn unauthorized() -> Result>, Error> {
1221 | http_err(StatusCode::UNAUTHORIZED, "Unauthorized")
1222 | }
1223 |
1224 | fn not_found() -> Result>, Error> {
1225 | http_err(StatusCode::NOT_FOUND, "Not found")
1226 | }
1227 |
1228 | fn not_implemented() -> Result>, Error> {
1229 | http_err(StatusCode::NOT_IMPLEMENTED, "Unsupported method")
1230 | }
1231 |
1232 | fn json_body(json: &T) -> BoxBody
1233 | where
1234 | T: ?Sized + Serialize,
1235 | {
1236 | Full::new(serde_json::to_vec(json).unwrap().into())
1237 | .map_err(|never| match never {})
1238 | .boxed()
1239 | }
1240 |
1241 | fn file_body(file: Result, std::io::Error>) -> BoxBody {
1242 | Full::from(file.unwrap())
1243 | .map_err(|never| match never {})
1244 | .boxed()
1245 | }
1246 |
--------------------------------------------------------------------------------
/src/statics.rs:
--------------------------------------------------------------------------------
1 | /*
2 | * Rust Query API - A versatile API facade for the Hypixel Auction API
3 | * Copyright (c) 2022 kr45732
4 | *
5 | * This program is free software: you can redistribute it and/or modify
6 | * it under the terms of the GNU Affero General Public License as
7 | * published by the Free Software Foundation, either version 3 of the
8 | * License, or (at your option) any later version.
9 | *
10 | * This program is distributed in the hope that it will be useful,
11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | * GNU Affero General Public License for more details.
14 | *
15 | * You should have received a copy of the GNU Affero General Public License
16 | * along with this program. If not, see .
17 | */
18 |
19 | use crate::webhook::Webhook;
20 | use deadpool_postgres::Pool;
21 | use lazy_static::lazy_static;
22 | use postgres_types::Type;
23 | use regex::Regex;
24 | use std::time::Duration;
25 | use tokio::sync::Mutex;
26 |
27 | lazy_static! {
28 | pub static ref HTTP_CLIENT: reqwest::Client = reqwest::ClientBuilder::new()
29 | .connect_timeout(Duration::from_secs(15))
30 | .gzip(true)
31 | .build()
32 | .unwrap();
33 | pub static ref MC_CODE_REGEX: Regex = Regex::new("(?i)\u{00A7}[0-9A-FK-OR]").unwrap();
34 | pub static ref IS_UPDATING: Mutex = Mutex::new(false);
35 | pub static ref TOTAL_UPDATES: Mutex = Mutex::new(0);
36 | pub static ref LAST_UPDATED: Mutex = Mutex::new(0);
37 | pub static ref WEBHOOK: Mutex