import from unified repo

This commit is contained in:
Giovanni Harting 2021-10-03 16:24:20 +02:00
commit 79d1df4cf3
50 changed files with 21269 additions and 0 deletions

168
.gitignore vendored Normal file
View File

@ -0,0 +1,168 @@
### Go ###
# Binaries for programs and plugins
*.exe
*.exe~
*.dll
*.so
*.dylib
# Test binary, built with `go test -c`
*.test
# Output of the go coverage tool, specifically when used with LiteIDE
*.out
# Dependency directories (remove the comment below to include it)
# vendor/
### Go Patch ###
/vendor/
/Godeps/
### Intellij+all ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser
### Intellij+all Patch ###
# Ignores the whole .idea folder and all .iml files
# See https://github.com/joeblau/gitignore.io/issues/186 and https://github.com/joeblau/gitignore.io/issues/360
.idea/
# Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-249601023
*.iml
modules.xml
.idea/misc.xml
*.ipr
# Sonarlint plugin
.idea/sonarlint
### Linux ###
*~
# temporary files which can be created if a process still has a handle open of a deleted file
.fuse_hidden*
# KDE directory preferences
.directory
# Linux trash folder which might appear on any partition or disk
.Trash-*
# .nfs files are created when an open file is removed but is still being accessed
.nfs*
### Vuejs ###
# Recommended template: Node.gitignore
node_modules/
dist/
npm-debug.log
yarn-error.log
### Windows ###
# Windows thumbnail cache files
Thumbs.db
Thumbs.db:encryptable
ehthumbs.db
ehthumbs_vista.db
# Dump file
*.stackdump
# Folder config file
[Dd]esktop.ini
# Recycle Bin used on file shares
$RECYCLE.BIN/
# Windows Installer files
*.cab
*.msi
*.msix
*.msm
*.msp
# Windows shortcuts
*.lnk
# OPENCSGO
.login_key
.sentry
.server.json
opencsgo.db

232
LICENSE Normal file
View File

@ -0,0 +1,232 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for software and other kinds of works.
The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
TERMS AND CONDITIONS
0. Definitions.
“This License” refers to version 3 of the GNU General Public License.
“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks.
“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations.
To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.
A “covered work” means either the unmodified Program or a work based on the Program.
To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well.
To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion.
1. Source Code.
The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work.
A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language.
The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it.
The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified it, and giving a relevant date.
b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”.
c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways:
a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b.
d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work.
A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product.
“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying.
7. Additional Terms.
“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or authors of the material; or
e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors.
All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License.
An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it.
11. Patents.
A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”.
A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version.
In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it.
A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the “copyright” line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”.
You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>.

2
README.md Normal file
View File

@ -0,0 +1,2 @@
# opencsgo

7
config.yaml Normal file
View File

@ -0,0 +1,7 @@
logging:
level: DEBUG
steam:
username: steamusername
api_key: apikey
rate_per_sec: 1

262
csgo/demo_loader.go Normal file
View File

@ -0,0 +1,262 @@
package csgo
import (
"bufio"
"encoding/json"
"fmt"
"github.com/an0nfunc/go-steam/v3"
"github.com/an0nfunc/go-steam/v3/csgo/protocol/protobuf"
"github.com/an0nfunc/go-steam/v3/netutil"
"github.com/an0nfunc/go-steam/v3/protocol/gamecoordinator"
"github.com/an0nfunc/go-steam/v3/protocol/steamlang"
log "github.com/sirupsen/logrus"
"google.golang.org/protobuf/proto"
"io/ioutil"
"math/rand"
"os"
"time"
)
//goland:noinspection SpellCheckingInspection
const (
SENTRYFILE = ".sentry"
LOGINKEYFILE = ".login_key"
SERVERLIST = ".server.json"
APPID = 730
)
type DemoMatchLoader struct {
client *steam.Client
GCReady bool
steamLogin *steam.LogOnDetails
matchRecv chan *protobuf.CMsgGCCStrike15V2_MatchList
cmList []*netutil.PortAddr
}
func AccountId2SteamId(accId uint32) uint64 {
return uint64(accId) + 76561197960265728
}
func SteamId2AccountId(steamId uint64) uint32 {
return uint32(steamId - 76561197960265728)
}
func (d *DemoMatchLoader) HandleGCPacket(pkg *gamecoordinator.GCPacket) {
switch pkg.MsgType {
case uint32(protobuf.EGCBaseClientMsg_k_EMsgGCClientWelcome):
msg := &protobuf.CMsgClientWelcome{}
err := proto.Unmarshal(pkg.Body, msg)
if err != nil {
log.Errorf("[DL] Unable to unmarshal event %v: %v", pkg.MsgType, err)
}
log.Debugf("[GC] Welcome: %+v", msg)
d.GCReady = true
case uint32(protobuf.EGCBaseClientMsg_k_EMsgGCClientConnectionStatus):
msg := &protobuf.CMsgConnectionStatus{}
err := proto.Unmarshal(pkg.Body, msg)
if err != nil {
log.Errorf("[DL] Unable to unmarshal event %v: %v", pkg.MsgType, err)
}
log.Debugf("[GC] Status: %+v", msg)
if msg.GetStatus() != protobuf.GCConnectionStatus_GCConnectionStatus_HAVE_SESSION {
d.GCReady = false
go d.greetGC()
}
case uint32(protobuf.ECsgoGCMsg_k_EMsgGCCStrike15_v2_GC2ClientGlobalStats):
msg := &protobuf.GlobalStatistics{}
err := proto.Unmarshal(pkg.Body, msg)
if err != nil {
log.Errorf("[DL] Unable to unmarshal event %v: %v", pkg.MsgType, err)
}
log.Debugf("[GC] Stats: %+v", msg)
d.GCReady = true
case uint32(protobuf.ECsgoGCMsg_k_EMsgGCCStrike15_v2_MatchList):
msg := &protobuf.CMsgGCCStrike15V2_MatchList{}
err := proto.Unmarshal(pkg.Body, msg)
if err != nil {
log.Errorf("[DL] Unable to unmarshal event %v: %v", pkg.MsgType, err)
}
d.matchRecv <- msg
default:
log.Debugf("[GC] Unhandled GC message: %+v", pkg)
}
}
func (d *DemoMatchLoader) GetMatchDetails(sharecode string) (*protobuf.CMsgGCCStrike15V2_MatchList, error) {
if !d.GCReady {
return nil, fmt.Errorf("gc not ready")
}
matchId, outcomeId, tokenId, err := DecodeSharecode(sharecode)
if err != nil {
return nil, err
}
err = d.RequestDemoInfo(matchId, outcomeId, tokenId)
if err != nil {
return nil, err
}
for {
select {
case match := <-d.matchRecv:
if *match.Matches[0].Matchid == matchId {
return match, nil
} else {
d.matchRecv <- match
}
}
}
}
func (d *DemoMatchLoader) getRandomCM() *netutil.PortAddr {
return d.cmList[rand.Intn(len(d.cmList))]
}
func (d *DemoMatchLoader) connectToSteam() error {
if d.cmList != nil {
err := d.client.ConnectTo(d.getRandomCM())
if err != nil {
return err
}
} else {
_, err := d.client.Connect()
if err != nil {
return err
}
}
return nil
}
func (d *DemoMatchLoader) Setup(username string) error {
d.steamLogin = new(steam.LogOnDetails)
d.steamLogin.Username = username
d.steamLogin.Password = os.Getenv("STEAM_PASSWORD")
d.steamLogin.ShouldRememberPassword = true
if _, err := os.Stat(SENTRYFILE); err == nil {
hash, err := ioutil.ReadFile(SENTRYFILE)
if err != nil {
return err
}
d.steamLogin.SentryFileHash = hash
}
if _, err := os.Stat(LOGINKEYFILE); err == nil {
hash, err := ioutil.ReadFile(LOGINKEYFILE)
if err != nil {
return err
}
d.steamLogin.LoginKey = string(hash)
}
if _, err := os.Stat(SERVERLIST); err == nil {
rawJson, err := ioutil.ReadFile(SERVERLIST)
if err != nil {
return err
}
err = json.Unmarshal(rawJson, &d.cmList)
if err != nil {
return err
}
}
d.client = steam.NewClient()
d.matchRecv = make(chan *protobuf.CMsgGCCStrike15V2_MatchList, 500)
go d.connectLoop()
go d.steamEventHandler()
return nil
}
func (d DemoMatchLoader) connectLoop() {
for d.connectToSteam() != nil {
log.Infof("Retrying connecting to steam")
time.Sleep(time.Second)
}
}
func (d *DemoMatchLoader) steamEventHandler() {
for event := range d.client.Events() {
switch e := event.(type) {
case *steam.ConnectedEvent:
log.Debug("[DL] Connected!")
d.client.Auth.LogOn(d.steamLogin)
case *steam.ClientCMListEvent:
log.Debug("[DL] CM list")
serverJson, err := json.Marshal(e.Addresses)
if err != nil {
log.Errorf("[DL] Unable to marshal JSON: %v", err)
}
err = ioutil.WriteFile(SERVERLIST, serverJson, os.ModePerm)
if err != nil {
log.Errorf("[DL] Unable to write server list: %v", err)
}
case *steam.MachineAuthUpdateEvent:
log.Debug("[DL] Got sentry!")
err := ioutil.WriteFile(SENTRYFILE, e.Hash, os.ModePerm)
if err != nil {
log.Errorf("[DL] Unable write sentry file: %v", err)
}
case *steam.LoggedOnEvent:
log.Debug("[DL] Login successfully!")
d.client.Social.SetPersonaState(steamlang.EPersonaState_Online)
go d.SetPlaying()
case *steam.LogOnFailedEvent:
log.Warningf("[DL] Steam login denied: %+v", e)
log.Warningf("[DL] Asking for auth code now, please provide on stdin.")
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan()
d.steamLogin.AuthCode = scanner.Text()
case *steam.DisconnectedEvent:
log.Warningf("Steam disconnected, trying to reconnect...")
_, err := d.client.Connect()
if err != nil {
log.Errorf("[DL] Unable to reconnect to steam: %v", err)
}
case *steam.LoginKeyEvent:
log.Debug("Got login_key!")
err := ioutil.WriteFile(LOGINKEYFILE, []byte(e.LoginKey), os.ModePerm)
if err != nil {
log.Errorf("[DL] Unable write login_key: %v", err)
}
case steam.FatalErrorEvent:
log.Debugf("[DL] Got FatalError %+v", e)
case error:
log.Fatalf("[DL] Got error %+v", e)
default:
log.Debugf("[DL] %T: %v", e, e)
}
}
}
func (d *DemoMatchLoader) SetPlaying() {
d.client.GC.SetGamesPlayed(APPID)
d.client.GC.RegisterPacketHandler(d)
go d.greetGC()
}
func (d *DemoMatchLoader) greetGC() {
for !d.GCReady {
log.Debugf("[DL] Sending GC greeting")
msg := protobuf.CMsgClientHello{}
d.client.GC.Write(gamecoordinator.NewGCMsgProtobuf(APPID, uint32(protobuf.EGCBaseClientMsg_k_EMsgGCClientHello), &msg))
time.Sleep(500 * time.Millisecond)
}
}
func (d *DemoMatchLoader) RequestDemoInfo(matchId uint64, conclusionId uint64, tokenId uint32) error {
if !d.GCReady {
return fmt.Errorf("gc not ready")
}
msg := protobuf.CMsgGCCStrike15V2_MatchListRequestFullGameInfo{Matchid: &matchId,
Outcomeid: &conclusionId,
Token: &tokenId}
d.client.GC.Write(gamecoordinator.NewGCMsgProtobuf(APPID, uint32(protobuf.ECsgoGCMsg_k_EMsgGCCStrike15_v2_MatchListRequestFullGameInfo), &msg))
return nil
}

321
csgo/demo_parser.go Normal file
View File

@ -0,0 +1,321 @@
package csgo
import (
"compress/bzip2"
"context"
"csgowtfd/ent"
"csgowtfd/ent/match"
"csgowtfd/ent/player"
"fmt"
"github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs"
"github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs/common"
"github.com/markus-wa/demoinfocs-golang/v2/pkg/demoinfocs/events"
log "github.com/sirupsen/logrus"
"io"
"net/http"
"sync"
"time"
)
type Demo struct {
ShareCode string
MatchId uint64
Url string
Rank int
Tickrate int
File string
}
type DemoParser struct {
demoQueue chan *Demo
tempDir string
}
type DemoNotFoundError struct {
error
}
func (p *DemoParser) Setup(db *ent.Client, lock *sync.RWMutex) error {
p.demoQueue = make(chan *Demo, 1000)
go p.parseWorker(db, lock)
return nil
}
func (p *DemoParser) ParseDemo(demo *Demo) error {
select {
case p.demoQueue <- demo:
return nil
default:
return fmt.Errorf("queue full")
}
}
func (p *DemoParser) downloadReplay(demo *Demo) (io.Reader, error) {
log.Debugf("[DP] Downloading replay for %d", demo.MatchId)
r, err := http.Get(demo.Url)
if err != nil {
return nil, err
}
if r.StatusCode != http.StatusOK {
return nil, DemoNotFoundError{fmt.Errorf("demo not found")}
}
return bzip2.NewReader(r.Body), nil
}
func (p *DemoParser) getDBPlayer(db *ent.Client, lock *sync.RWMutex, demo *Demo, demoPlayer *common.Player) (*ent.Stats, error) {
lock.RLock()
tMatchPlayer, err := db.Stats.Query().WithMatches(func(q *ent.MatchQuery) {
q.Where(match.MatchID(demo.MatchId))
}).WithPlayers(func(q *ent.PlayerQuery) {
q.Where(player.Steamid(demoPlayer.SteamID64))
}).Only(context.Background())
lock.RUnlock()
if err != nil {
return nil, err
}
return tMatchPlayer, nil
}
func (p *DemoParser) getMatchPlayerBySteamID(stats []*ent.Stats, steamId uint64) *ent.Stats {
for _, tStats := range stats {
tPLayer, err := tStats.Edges.PlayersOrErr()
if err != nil {
log.Errorf("Unbale to get Stats from statList: %v", err)
return nil
}
if tPLayer.Steamid == steamId {
return tStats
}
}
return nil
}
func (p *DemoParser) parseWorker(db *ent.Client, lock *sync.RWMutex) {
for {
select {
case demo := <-p.demoQueue:
if demo.MatchId == 0 {
log.Warningf("[DP] can't parse match %s: no matchid found", demo.ShareCode)
continue
}
lock.RLock()
tMatch, err := db.Match.Query().Where(match.MatchID(demo.MatchId)).Only(context.Background())
lock.RUnlock()
if err != nil {
log.Errorf("[DP] Unable to get match %d: %v", demo.MatchId, err)
continue
}
if tMatch.DemoParsed {
log.Infof("[DP] skipped already parsed %d", demo.MatchId)
continue
}
startTime := time.Now()
fDemo, err := p.downloadReplay(demo)
if err != nil {
switch e := err.(type) {
case DemoNotFoundError:
err := tMatch.Update().SetDemoExpired(true).Exec(context.Background())
if err != nil {
log.Errorf("[DP] Unable to set demo expire for match %d: %v", demo.MatchId, e)
continue
}
log.Warningf("[DP] Demo already expired for %d", demo.MatchId)
continue
default:
log.Warningf("[DP] Unable to download demo for %d: %v", demo.MatchId, e)
continue
}
}
downloadTime := time.Now().Sub(startTime)
lock.RLock()
tStats, err := tMatch.QueryStats().WithPlayers().All(context.Background())
lock.RUnlock()
if err != nil {
log.Errorf("[DP] Failed to find players for match %d: %v", demo.MatchId, err)
continue
}
killMap := make(map[uint64]int, 10)
gameStarted := false
demoParser := demoinfocs.NewParser(fDemo)
// onPlayerHurt
demoParser.RegisterEventHandler(func(e events.PlayerHurt) {
if e.Attacker == nil || e.Player == nil || !gameStarted {
return
}
tAttacker := p.getMatchPlayerBySteamID(tStats, e.Attacker.SteamID64)
if e.Attacker.Team == e.Player.Team {
tAttacker.Extended.Dmg.Team += e.HealthDamageTaken
return
} else {
tAttacker.Extended.Dmg.Enemy += e.HealthDamageTaken
}
switch e.Weapon.Type {
case common.EqDecoy:
tAttacker.Extended.Dmg.UD.Decoy += e.HealthDamageTaken
case common.EqSmoke:
tAttacker.Extended.Dmg.UD.Smoke += e.HealthDamageTaken
case common.EqHE:
tAttacker.Extended.Dmg.UD.HE += e.HealthDamageTaken
case common.EqMolotov, common.EqIncendiary:
tAttacker.Extended.Dmg.UD.Flames += e.HealthDamageTaken
case common.EqFlash:
tAttacker.Extended.Dmg.UD.Flash += e.HealthDamageTaken
}
switch e.HitGroup {
case events.HitGroupHead:
tAttacker.Extended.Dmg.HitGroup.Head += e.HealthDamageTaken
case events.HitGroupChest:
tAttacker.Extended.Dmg.HitGroup.Chest += e.HealthDamageTaken
case events.HitGroupStomach:
tAttacker.Extended.Dmg.HitGroup.Stomach += e.HealthDamageTaken
case events.HitGroupLeftArm:
tAttacker.Extended.Dmg.HitGroup.LeftArm += e.HealthDamageTaken
case events.HitGroupRightArm:
tAttacker.Extended.Dmg.HitGroup.RightArm += e.HealthDamageTaken
case events.HitGroupLeftLeg:
tAttacker.Extended.Dmg.HitGroup.LeftLeg += e.HealthDamageTaken
case events.HitGroupRightLeg:
tAttacker.Extended.Dmg.HitGroup.RightLeg += e.HealthDamageTaken
case events.HitGroupGear:
tAttacker.Extended.Dmg.HitGroup.Gear += e.HealthDamageTaken
}
})
// onKill
demoParser.RegisterEventHandler(func(e events.Kill) {
})
// onFreezeTimeEnd
demoParser.RegisterEventHandler(func(e events.RoundFreezetimeEnd) {
})
// onRoundEnd
demoParser.RegisterEventHandler(func(e events.RoundEnd) {
if gameStarted {
for _, IGP := range demoParser.GameState().Participants().Playing() {
if IGP != nil && IGP.SteamID64 != 0 {
killDiff := IGP.Kills() - killMap[IGP.SteamID64]
tPlayer := p.getMatchPlayerBySteamID(tStats, IGP.SteamID64)
switch killDiff {
case 2:
tPlayer.Extended.MultiKills.Duo++
case 3:
tPlayer.Extended.MultiKills.Triple++
case 4:
tPlayer.Extended.MultiKills.Quad++
case 5:
tPlayer.Extended.MultiKills.Pent++
}
killMap[IGP.SteamID64] = IGP.Kills()
}
}
}
})
// onPlayerFlashed
demoParser.RegisterEventHandler(func(e events.PlayerFlashed) {
if e.Attacker == nil || e.Player == nil || !gameStarted {
return
}
tAttacker := p.getMatchPlayerBySteamID(tStats, e.Attacker.SteamID64)
// team flash
if e.Attacker.Team == e.Player.Team && e.Attacker.SteamID64 != e.Player.SteamID64 {
tAttacker.Extended.Flash.Total.Team++
tAttacker.Extended.Flash.Duration.Team += e.Player.FlashDuration
}
// own flash
if e.Attacker.SteamID64 == e.Player.SteamID64 {
tAttacker.Extended.Flash.Total.Self++
tAttacker.Extended.Flash.Duration.Self += e.Player.FlashDuration
}
// enemy flash
if e.Attacker.Team != e.Player.Team {
tAttacker.Extended.Flash.Total.Enemy++
tAttacker.Extended.Flash.Duration.Enemy += e.Player.FlashDuration
}
})
// onMatchStart
demoParser.RegisterEventHandler(func(e events.MatchStart) {
gs := demoParser.GameState()
gameStarted = true
for _, demoPlayer := range gs.Participants().Playing() {
if demoPlayer != nil && demoPlayer.SteamID64 != 0 {
tMatchPlayer := p.getMatchPlayerBySteamID(tStats, demoPlayer.SteamID64)
tMatchPlayer.Extended.Crosshair = demoPlayer.CrosshairCode()
tMatchPlayer.Extended.Color = int(demoPlayer.Color())
}
}
})
// onMatchEnd?
demoParser.RegisterEventHandler(func(e events.AnnouncementWinPanelMatch) {
})
// onRankUpdate
demoParser.RegisterEventHandler(func(e events.RankUpdate) {
if e.Player != nil && e.SteamID64() != 0 {
tMatchPlayer := p.getMatchPlayerBySteamID(tStats, e.SteamID64())
tMatchPlayer.Extended.Rank.Old = e.RankOld
tMatchPlayer.Extended.Rank.New = e.RankNew
}
})
err = demoParser.ParseToEnd()
if err != nil {
log.Errorf("[DP] Error parsing replay: %v", err)
continue
}
lock.Lock()
err = tMatch.Update().SetMap(demoParser.Header().MapName).SetDemoParsed(true).Exec(context.Background())
lock.Unlock()
if err != nil {
log.Errorf("[DP] Unable to update match %d in database: %v", demo.MatchId, err)
continue
}
for _, tMatchPlayer := range tStats {
lock.Lock()
err := tMatchPlayer.Update().SetExtended(tMatchPlayer.Extended).Exec(context.Background())
lock.Unlock()
if err != nil {
log.Errorf("[DP] Unable to update player %d in database: %v", tMatchPlayer.Edges.Players.Steamid, err)
continue
}
}
log.Infof("[DP] Parsed %d (took %s/%s)", demo.MatchId, downloadTime, time.Now().Sub(startTime))
err = demoParser.Close()
if err != nil {
log.Errorf("[DP] Unable close demo file for match %d: %v", demo.MatchId, err)
}
}
}
}

57
csgo/sharecode.go Normal file
View File

@ -0,0 +1,57 @@
package csgo
import (
"encoding/hex"
"fmt"
"math/big"
"regexp"
"strings"
)
//goland:noinspection SpellCheckingInspection
var DICT = "ABCDEFGHJKLMNOPQRSTUVWXYZabcdefhijkmnopqrstuvwxyz23456789"
var sharecodeRexEx = regexp.MustCompile("^CSGO(?:-?[\\w]{5}){5}$")
func DecodeSharecode(code string) (uint64, uint64, uint32, error) {
if !sharecodeRexEx.MatchString(code) {
return 0, 0, 0, fmt.Errorf("not a CSGO sharecode: %s", code)
}
cleanCode := strings.ReplaceAll(code, "CSGO", "")
cleanCode = strings.ReplaceAll(cleanCode, "-", "")
chars := ReverseString(strings.Split(cleanCode, ""))
bigInt := new(big.Int)
dictLenBig := big.NewInt(int64(len(DICT)))
for _, c := range chars {
bigInt.Mul(bigInt, dictLenBig)
bigInt.Add(bigInt, big.NewInt(int64(strings.Index(DICT, c))))
}
bytes := make([]byte, 18)
bigInt.FillBytes(bytes)
matchId := new(big.Int)
matchId.SetString(hex.EncodeToString(Reverse(bytes[0:8])), 16)
outcomeId := new(big.Int)
outcomeId.SetString(hex.EncodeToString(Reverse(bytes[8:16])), 16)
tokenId := new(big.Int)
tokenId.SetString(hex.EncodeToString(Reverse(bytes[16:18])), 16)
return matchId.Uint64(), outcomeId.Uint64(), uint32(tokenId.Uint64()), nil
}
func Reverse(numbers []byte) []byte {
for i, j := 0, len(numbers)-1; i < j; i, j = i+1, j-1 {
numbers[i], numbers[j] = numbers[j], numbers[i]
}
return numbers
}
func ReverseString(numbers []string) []string {
for i, j := 0, len(numbers)-1; i < j; i, j = i+1, j-1 {
numbers[i], numbers[j] = numbers[j], numbers[i]
}
return numbers
}

29
csgo/sharecode_test.go Normal file
View File

@ -0,0 +1,29 @@
package csgo
import "testing"
//goland:noinspection SpellCheckingInspection
func TestSharecode(t *testing.T) {
eMatchId := uint64(3505575050994516382)
eOutcomeId := uint64(3505581094013501947)
eTokenId := uint32(12909)
matchId, outcomeId, tokenId, err := DecodeSharecode("CSGO-P9k3F-eVL9n-LZLXN-DrBGF-VKD7K")
if err != nil {
t.Log("error should be nil", err)
t.Fail()
}
if matchId != eMatchId {
t.Logf("matchID should be %d, is %d", eMatchId, matchId)
t.Fail()
}
if outcomeId != eOutcomeId {
t.Logf("outcomeID should be %d, is %d", eOutcomeId, outcomeId)
t.Fail()
}
if tokenId != eTokenId {
t.Logf("tokenID should be %d, is %d", eTokenId, tokenId)
t.Fail()
}
}

503
ent/client.go Normal file
View File

@ -0,0 +1,503 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"log"
"csgowtfd/ent/migrate"
"csgowtfd/ent/match"
"csgowtfd/ent/player"
"csgowtfd/ent/stats"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// Client is the client that holds all ent builders.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Match is the client for interacting with the Match builders.
Match *MatchClient
// Player is the client for interacting with the Player builders.
Player *PlayerClient
// Stats is the client for interacting with the Stats builders.
Stats *StatsClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
cfg := config{log: log.Println, hooks: &hooks{}}
cfg.options(opts...)
client := &Client{config: cfg}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Match = NewMatchClient(c.config)
c.Player = NewPlayerClient(c.config)
c.Stats = NewStatsClient(c.config)
}
// Open opens a database/sql.DB specified by the driver name and
// the data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// Tx returns a new transactional client. The provided context
// is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction")
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Match: NewMatchClient(cfg),
Player: NewPlayerClient(cfg),
Stats: NewStatsClient(cfg),
}, nil
}
// BeginTx returns a transactional client with specified options.
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, fmt.Errorf("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
}).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
config: cfg,
Match: NewMatchClient(cfg),
Player: NewPlayerClient(cfg),
Stats: NewStatsClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Match.
// Query().
// Count(ctx)
//
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := c.config
cfg.driver = dialect.Debug(c.driver, c.log)
client := &Client{config: cfg}
client.init()
return client
}
// Close closes the database connection and prevents new queries from starting.
func (c *Client) Close() error {
return c.driver.Close()
}
// Use adds the mutation hooks to all the entity clients.
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Match.Use(hooks...)
c.Player.Use(hooks...)
c.Stats.Use(hooks...)
}
// MatchClient is a client for the Match schema.
type MatchClient struct {
config
}
// NewMatchClient returns a client for the Match from the given config.
func NewMatchClient(c config) *MatchClient {
return &MatchClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `match.Hooks(f(g(h())))`.
func (c *MatchClient) Use(hooks ...Hook) {
c.hooks.Match = append(c.hooks.Match, hooks...)
}
// Create returns a create builder for Match.
func (c *MatchClient) Create() *MatchCreate {
mutation := newMatchMutation(c.config, OpCreate)
return &MatchCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Match entities.
func (c *MatchClient) CreateBulk(builders ...*MatchCreate) *MatchCreateBulk {
return &MatchCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Match.
func (c *MatchClient) Update() *MatchUpdate {
mutation := newMatchMutation(c.config, OpUpdate)
return &MatchUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *MatchClient) UpdateOne(m *Match) *MatchUpdateOne {
mutation := newMatchMutation(c.config, OpUpdateOne, withMatch(m))
return &MatchUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *MatchClient) UpdateOneID(id int) *MatchUpdateOne {
mutation := newMatchMutation(c.config, OpUpdateOne, withMatchID(id))
return &MatchUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Match.
func (c *MatchClient) Delete() *MatchDelete {
mutation := newMatchMutation(c.config, OpDelete)
return &MatchDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a delete builder for the given entity.
func (c *MatchClient) DeleteOne(m *Match) *MatchDeleteOne {
return c.DeleteOneID(m.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *MatchClient) DeleteOneID(id int) *MatchDeleteOne {
builder := c.Delete().Where(match.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &MatchDeleteOne{builder}
}
// Query returns a query builder for Match.
func (c *MatchClient) Query() *MatchQuery {
return &MatchQuery{
config: c.config,
}
}
// Get returns a Match entity by its id.
func (c *MatchClient) Get(ctx context.Context, id int) (*Match, error) {
return c.Query().Where(match.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *MatchClient) GetX(ctx context.Context, id int) *Match {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryStats queries the stats edge of a Match.
func (c *MatchClient) QueryStats(m *Match) *StatsQuery {
query := &StatsQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := m.ID
step := sqlgraph.NewStep(
sqlgraph.From(match.Table, match.FieldID, id),
sqlgraph.To(stats.Table, stats.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, match.StatsTable, match.StatsColumn),
)
fromV = sqlgraph.Neighbors(m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryPlayers queries the players edge of a Match.
func (c *MatchClient) QueryPlayers(m *Match) *PlayerQuery {
query := &PlayerQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := m.ID
step := sqlgraph.NewStep(
sqlgraph.From(match.Table, match.FieldID, id),
sqlgraph.To(player.Table, player.FieldID),
sqlgraph.Edge(sqlgraph.M2M, true, match.PlayersTable, match.PlayersPrimaryKey...),
)
fromV = sqlgraph.Neighbors(m.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *MatchClient) Hooks() []Hook {
return c.hooks.Match
}
// PlayerClient is a client for the Player schema.
type PlayerClient struct {
config
}
// NewPlayerClient returns a client for the Player from the given config.
func NewPlayerClient(c config) *PlayerClient {
return &PlayerClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `player.Hooks(f(g(h())))`.
func (c *PlayerClient) Use(hooks ...Hook) {
c.hooks.Player = append(c.hooks.Player, hooks...)
}
// Create returns a create builder for Player.
func (c *PlayerClient) Create() *PlayerCreate {
mutation := newPlayerMutation(c.config, OpCreate)
return &PlayerCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Player entities.
func (c *PlayerClient) CreateBulk(builders ...*PlayerCreate) *PlayerCreateBulk {
return &PlayerCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Player.
func (c *PlayerClient) Update() *PlayerUpdate {
mutation := newPlayerMutation(c.config, OpUpdate)
return &PlayerUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *PlayerClient) UpdateOne(pl *Player) *PlayerUpdateOne {
mutation := newPlayerMutation(c.config, OpUpdateOne, withPlayer(pl))
return &PlayerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *PlayerClient) UpdateOneID(id int) *PlayerUpdateOne {
mutation := newPlayerMutation(c.config, OpUpdateOne, withPlayerID(id))
return &PlayerUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Player.
func (c *PlayerClient) Delete() *PlayerDelete {
mutation := newPlayerMutation(c.config, OpDelete)
return &PlayerDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a delete builder for the given entity.
func (c *PlayerClient) DeleteOne(pl *Player) *PlayerDeleteOne {
return c.DeleteOneID(pl.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *PlayerClient) DeleteOneID(id int) *PlayerDeleteOne {
builder := c.Delete().Where(player.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &PlayerDeleteOne{builder}
}
// Query returns a query builder for Player.
func (c *PlayerClient) Query() *PlayerQuery {
return &PlayerQuery{
config: c.config,
}
}
// Get returns a Player entity by its id.
func (c *PlayerClient) Get(ctx context.Context, id int) (*Player, error) {
return c.Query().Where(player.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *PlayerClient) GetX(ctx context.Context, id int) *Player {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryStats queries the stats edge of a Player.
func (c *PlayerClient) QueryStats(pl *Player) *StatsQuery {
query := &StatsQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := pl.ID
step := sqlgraph.NewStep(
sqlgraph.From(player.Table, player.FieldID, id),
sqlgraph.To(stats.Table, stats.FieldID),
sqlgraph.Edge(sqlgraph.O2M, false, player.StatsTable, player.StatsColumn),
)
fromV = sqlgraph.Neighbors(pl.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryMatches queries the matches edge of a Player.
func (c *PlayerClient) QueryMatches(pl *Player) *MatchQuery {
query := &MatchQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := pl.ID
step := sqlgraph.NewStep(
sqlgraph.From(player.Table, player.FieldID, id),
sqlgraph.To(match.Table, match.FieldID),
sqlgraph.Edge(sqlgraph.M2M, false, player.MatchesTable, player.MatchesPrimaryKey...),
)
fromV = sqlgraph.Neighbors(pl.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *PlayerClient) Hooks() []Hook {
return c.hooks.Player
}
// StatsClient is a client for the Stats schema.
type StatsClient struct {
config
}
// NewStatsClient returns a client for the Stats from the given config.
func NewStatsClient(c config) *StatsClient {
return &StatsClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `stats.Hooks(f(g(h())))`.
func (c *StatsClient) Use(hooks ...Hook) {
c.hooks.Stats = append(c.hooks.Stats, hooks...)
}
// Create returns a create builder for Stats.
func (c *StatsClient) Create() *StatsCreate {
mutation := newStatsMutation(c.config, OpCreate)
return &StatsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Stats entities.
func (c *StatsClient) CreateBulk(builders ...*StatsCreate) *StatsCreateBulk {
return &StatsCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Stats.
func (c *StatsClient) Update() *StatsUpdate {
mutation := newStatsMutation(c.config, OpUpdate)
return &StatsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *StatsClient) UpdateOne(s *Stats) *StatsUpdateOne {
mutation := newStatsMutation(c.config, OpUpdateOne, withStats(s))
return &StatsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *StatsClient) UpdateOneID(id int) *StatsUpdateOne {
mutation := newStatsMutation(c.config, OpUpdateOne, withStatsID(id))
return &StatsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Stats.
func (c *StatsClient) Delete() *StatsDelete {
mutation := newStatsMutation(c.config, OpDelete)
return &StatsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a delete builder for the given entity.
func (c *StatsClient) DeleteOne(s *Stats) *StatsDeleteOne {
return c.DeleteOneID(s.ID)
}
// DeleteOneID returns a delete builder for the given id.
func (c *StatsClient) DeleteOneID(id int) *StatsDeleteOne {
builder := c.Delete().Where(stats.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &StatsDeleteOne{builder}
}
// Query returns a query builder for Stats.
func (c *StatsClient) Query() *StatsQuery {
return &StatsQuery{
config: c.config,
}
}
// Get returns a Stats entity by its id.
func (c *StatsClient) Get(ctx context.Context, id int) (*Stats, error) {
return c.Query().Where(stats.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *StatsClient) GetX(ctx context.Context, id int) *Stats {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// QueryMatches queries the matches edge of a Stats.
func (c *StatsClient) QueryMatches(s *Stats) *MatchQuery {
query := &MatchQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := s.ID
step := sqlgraph.NewStep(
sqlgraph.From(stats.Table, stats.FieldID, id),
sqlgraph.To(match.Table, match.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, stats.MatchesTable, stats.MatchesColumn),
)
fromV = sqlgraph.Neighbors(s.driver.Dialect(), step)
return fromV, nil
}
return query
}
// QueryPlayers queries the players edge of a Stats.
func (c *StatsClient) QueryPlayers(s *Stats) *PlayerQuery {
query := &PlayerQuery{config: c.config}
query.path = func(ctx context.Context) (fromV *sql.Selector, _ error) {
id := s.ID
step := sqlgraph.NewStep(
sqlgraph.From(stats.Table, stats.FieldID, id),
sqlgraph.To(player.Table, player.FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, stats.PlayersTable, stats.PlayersColumn),
)
fromV = sqlgraph.Neighbors(s.driver.Dialect(), step)
return fromV, nil
}
return query
}
// Hooks returns the client hooks.
func (c *StatsClient) Hooks() []Hook {
return c.hooks.Stats
}

61
ent/config.go Normal file
View File

@ -0,0 +1,61 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"entgo.io/ent"
"entgo.io/ent/dialect"
)
// Option function to configure the client.
type Option func(*config)
// Config is the configuration for the client and its builder.
type config struct {
// driver used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug mode.
log func(...interface{})
// hooks to execute on mutations.
hooks *hooks
}
// hooks per client, for fast access.
type hooks struct {
Match []ent.Hook
Player []ent.Hook
Stats []ent.Hook
}
// Options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...interface{})) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}

33
ent/context.go Normal file
View File

@ -0,0 +1,33 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}

263
ent/ent.go Normal file
View File

@ -0,0 +1,263 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"csgowtfd/ent/match"
"csgowtfd/ent/player"
"csgowtfd/ent/stats"
"errors"
"fmt"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
// OrderFunc applies an ordering on the sql selector.
type OrderFunc func(*sql.Selector)
// columnChecker returns a function indicates if the column exists in the given column.
func columnChecker(table string) func(string) error {
checks := map[string]func(string) bool{
match.Table: match.ValidColumn,
player.Table: player.ValidColumn,
stats.Table: stats.ValidColumn,
}
check, ok := checks[table]
if !ok {
return func(string) error {
return fmt.Errorf("unknown table %q", table)
}
}
return func(column string) error {
if !check(column) {
return fmt.Errorf("unknown column %q for table %q", column, table)
}
return nil
}
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) OrderFunc {
return func(s *sql.Selector) {
check := columnChecker(s.TableName())
for _, f := range fields {
if err := check(f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) OrderFunc {
return func(s *sql.Selector) {
check := columnChecker(s.TableName())
for _, f := range fields {
if err := check(f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("ent: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(ent.As(ent.Sum(field1), "sum_field1"), (ent.As(ent.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
//
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
check := columnChecker(s.TableName())
if err := check(field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("ent: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validation error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "ent: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "ent: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "ent: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "ent: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}

77
ent/enttest/enttest.go Normal file
View File

@ -0,0 +1,77 @@
// Code generated by entc, DO NOT EDIT.
package enttest
import (
"context"
"csgowtfd/ent"
// required by schema hooks.
_ "csgowtfd/ent/runtime"
"entgo.io/ent/dialect/sql/schema"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...interface{})
}
// Option configures client creation.
Option func(*options)
options struct {
opts []ent.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...ent.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls ent.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *ent.Client {
o := newOptions(opts)
c, err := ent.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
return c
}
// NewClient calls ent.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *ent.Client {
o := newOptions(opts)
c := ent.NewClient(o.opts...)
if err := c.Schema.Create(context.Background(), o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
return c
}

3
ent/generate.go Normal file
View File

@ -0,0 +1,3 @@
package ent
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema

229
ent/hook/hook.go Normal file
View File

@ -0,0 +1,229 @@
// Code generated by entc, DO NOT EDIT.
package hook
import (
"context"
"csgowtfd/ent"
"fmt"
)
// The MatchFunc type is an adapter to allow the use of ordinary
// function as Match mutator.
type MatchFunc func(context.Context, *ent.MatchMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f MatchFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.MatchMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.MatchMutation", m)
}
return f(ctx, mv)
}
// The PlayerFunc type is an adapter to allow the use of ordinary
// function as Player mutator.
type PlayerFunc func(context.Context, *ent.PlayerMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f PlayerFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.PlayerMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.PlayerMutation", m)
}
return f(ctx, mv)
}
// The StatsFunc type is an adapter to allow the use of ordinary
// function as Stats mutator.
type StatsFunc func(context.Context, *ent.StatsMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f StatsFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
mv, ok := m.(*ent.StatsMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.StatsMutation", m)
}
return f(ctx, mv)
}
// Condition is a hook condition function.
type Condition func(context.Context, ent.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m ent.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op ent.Op) Condition {
return func(_ context.Context, m ent.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m ent.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
//
func If(hk ent.Hook, cond Condition) ent.Hook {
return func(next ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, ent.Delete|ent.Create)
//
func On(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, ent.Update|ent.UpdateOne)
//
func Unless(hk ent.Hook, op ent.Op) ent.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) ent.Hook {
return func(ent.Mutator) ent.Mutator {
return ent.MutateFunc(func(context.Context, ent.Mutation) (ent.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []ent.Hook {
// return []ent.Hook{
// Reject(ent.Delete|ent.Update),
// }
// }
//
func Reject(op ent.Op) ent.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []ent.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...ent.Hook) Chain {
return Chain{append([]ent.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() ent.Hook {
return func(mutator ent.Mutator) ent.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...ent.Hook) Chain {
newHooks := make([]ent.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}

277
ent/match.go Normal file
View File

@ -0,0 +1,277 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"csgowtfd/ent/match"
"encoding/json"
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
)
// Match is the model entity for the Match schema.
type Match struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// MatchID holds the value of the "match_id" field.
MatchID uint64 `json:"match_id,string"`
// ShareCode holds the value of the "share_code" field.
ShareCode string `json:"share_code,omitempty"`
// Map holds the value of the "map" field.
Map string `json:"map,omitempty"`
// Date holds the value of the "date" field.
Date time.Time `json:"date,omitempty"`
// ScoreTeamA holds the value of the "score_team_a" field.
ScoreTeamA int `json:"score_team_a,omitempty"`
// ScoreTeamB holds the value of the "score_team_b" field.
ScoreTeamB int `json:"score_team_b,omitempty"`
// ReplayURL holds the value of the "replay_url" field.
ReplayURL string `json:"-"`
// Duration holds the value of the "duration" field.
Duration int `json:"duration,omitempty"`
// MatchResult holds the value of the "match_result" field.
MatchResult int `json:"match_result,omitempty"`
// MaxRounds holds the value of the "max_rounds" field.
MaxRounds int `json:"max_rounds,omitempty"`
// DemoExpired holds the value of the "demo_expired" field.
DemoExpired bool `json:"demo_expired,omitempty"`
// DemoParsed holds the value of the "demo_parsed" field.
DemoParsed bool `json:"demo_parsed,omitempty"`
// Eco holds the value of the "eco" field.
Eco struct {
Rounds []*struct {
Team int "json:\"team\""
Bank int "json:\"bank\""
Equipment int "json:\"equipment\""
} "json:\"rounds\""
} `json:"eco,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the MatchQuery when eager-loading is set.
Edges MatchEdges `json:"edges"`
}
// MatchEdges holds the relations/edges for other nodes in the graph.
type MatchEdges struct {
// Stats holds the value of the stats edge.
Stats []*Stats `json:"stats,omitempty"`
// Players holds the value of the players edge.
Players []*Player `json:"players,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// StatsOrErr returns the Stats value or an error if the edge
// was not loaded in eager-loading.
func (e MatchEdges) StatsOrErr() ([]*Stats, error) {
if e.loadedTypes[0] {
return e.Stats, nil
}
return nil, &NotLoadedError{edge: "stats"}
}
// PlayersOrErr returns the Players value or an error if the edge
// was not loaded in eager-loading.
func (e MatchEdges) PlayersOrErr() ([]*Player, error) {
if e.loadedTypes[1] {
return e.Players, nil
}
return nil, &NotLoadedError{edge: "players"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Match) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case match.FieldEco:
values[i] = new([]byte)
case match.FieldDemoExpired, match.FieldDemoParsed:
values[i] = new(sql.NullBool)
case match.FieldID, match.FieldMatchID, match.FieldScoreTeamA, match.FieldScoreTeamB, match.FieldDuration, match.FieldMatchResult, match.FieldMaxRounds:
values[i] = new(sql.NullInt64)
case match.FieldShareCode, match.FieldMap, match.FieldReplayURL:
values[i] = new(sql.NullString)
case match.FieldDate:
values[i] = new(sql.NullTime)
default:
return nil, fmt.Errorf("unexpected column %q for type Match", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Match fields.
func (m *Match) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case match.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
m.ID = int(value.Int64)
case match.FieldMatchID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field match_id", values[i])
} else if value.Valid {
m.MatchID = uint64(value.Int64)
}
case match.FieldShareCode:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field share_code", values[i])
} else if value.Valid {
m.ShareCode = value.String
}
case match.FieldMap:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field map", values[i])
} else if value.Valid {
m.Map = value.String
}
case match.FieldDate:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field date", values[i])
} else if value.Valid {
m.Date = value.Time
}
case match.FieldScoreTeamA:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field score_team_a", values[i])
} else if value.Valid {
m.ScoreTeamA = int(value.Int64)
}
case match.FieldScoreTeamB:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field score_team_b", values[i])
} else if value.Valid {
m.ScoreTeamB = int(value.Int64)
}
case match.FieldReplayURL:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field replay_url", values[i])
} else if value.Valid {
m.ReplayURL = value.String
}
case match.FieldDuration:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field duration", values[i])
} else if value.Valid {
m.Duration = int(value.Int64)
}
case match.FieldMatchResult:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field match_result", values[i])
} else if value.Valid {
m.MatchResult = int(value.Int64)
}
case match.FieldMaxRounds:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field max_rounds", values[i])
} else if value.Valid {
m.MaxRounds = int(value.Int64)
}
case match.FieldDemoExpired:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field demo_expired", values[i])
} else if value.Valid {
m.DemoExpired = value.Bool
}
case match.FieldDemoParsed:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field demo_parsed", values[i])
} else if value.Valid {
m.DemoParsed = value.Bool
}
case match.FieldEco:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field eco", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &m.Eco); err != nil {
return fmt.Errorf("unmarshal field eco: %w", err)
}
}
}
}
return nil
}
// QueryStats queries the "stats" edge of the Match entity.
func (m *Match) QueryStats() *StatsQuery {
return (&MatchClient{config: m.config}).QueryStats(m)
}
// QueryPlayers queries the "players" edge of the Match entity.
func (m *Match) QueryPlayers() *PlayerQuery {
return (&MatchClient{config: m.config}).QueryPlayers(m)
}
// Update returns a builder for updating this Match.
// Note that you need to call Match.Unwrap() before calling this method if this Match
// was returned from a transaction, and the transaction was committed or rolled back.
func (m *Match) Update() *MatchUpdateOne {
return (&MatchClient{config: m.config}).UpdateOne(m)
}
// Unwrap unwraps the Match entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (m *Match) Unwrap() *Match {
tx, ok := m.config.driver.(*txDriver)
if !ok {
panic("ent: Match is not a transactional entity")
}
m.config.driver = tx.drv
return m
}
// String implements the fmt.Stringer.
func (m *Match) String() string {
var builder strings.Builder
builder.WriteString("Match(")
builder.WriteString(fmt.Sprintf("id=%v", m.ID))
builder.WriteString(", match_id=")
builder.WriteString(fmt.Sprintf("%v", m.MatchID))
builder.WriteString(", share_code=")
builder.WriteString(m.ShareCode)
builder.WriteString(", map=")
builder.WriteString(m.Map)
builder.WriteString(", date=")
builder.WriteString(m.Date.Format(time.ANSIC))
builder.WriteString(", score_team_a=")
builder.WriteString(fmt.Sprintf("%v", m.ScoreTeamA))
builder.WriteString(", score_team_b=")
builder.WriteString(fmt.Sprintf("%v", m.ScoreTeamB))
builder.WriteString(", replay_url=")
builder.WriteString(m.ReplayURL)
builder.WriteString(", duration=")
builder.WriteString(fmt.Sprintf("%v", m.Duration))
builder.WriteString(", match_result=")
builder.WriteString(fmt.Sprintf("%v", m.MatchResult))
builder.WriteString(", max_rounds=")
builder.WriteString(fmt.Sprintf("%v", m.MaxRounds))
builder.WriteString(", demo_expired=")
builder.WriteString(fmt.Sprintf("%v", m.DemoExpired))
builder.WriteString(", demo_parsed=")
builder.WriteString(fmt.Sprintf("%v", m.DemoParsed))
builder.WriteString(", eco=")
builder.WriteString(fmt.Sprintf("%v", m.Eco))
builder.WriteByte(')')
return builder.String()
}
// Matches is a parsable slice of Match.
type Matches []*Match
func (m Matches) config(cfg config) {
for _i := range m {
m[_i].config = cfg
}
}

95
ent/match/match.go Normal file
View File

@ -0,0 +1,95 @@
// Code generated by entc, DO NOT EDIT.
package match
const (
// Label holds the string label denoting the match type in the database.
Label = "match"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldMatchID holds the string denoting the match_id field in the database.
FieldMatchID = "match_id"
// FieldShareCode holds the string denoting the share_code field in the database.
FieldShareCode = "share_code"
// FieldMap holds the string denoting the map field in the database.
FieldMap = "map"
// FieldDate holds the string denoting the date field in the database.
FieldDate = "date"
// FieldScoreTeamA holds the string denoting the score_team_a field in the database.
FieldScoreTeamA = "score_team_a"
// FieldScoreTeamB holds the string denoting the score_team_b field in the database.
FieldScoreTeamB = "score_team_b"
// FieldReplayURL holds the string denoting the replay_url field in the database.
FieldReplayURL = "replay_url"
// FieldDuration holds the string denoting the duration field in the database.
FieldDuration = "duration"
// FieldMatchResult holds the string denoting the match_result field in the database.
FieldMatchResult = "match_result"
// FieldMaxRounds holds the string denoting the max_rounds field in the database.
FieldMaxRounds = "max_rounds"
// FieldDemoExpired holds the string denoting the demo_expired field in the database.
FieldDemoExpired = "demo_expired"
// FieldDemoParsed holds the string denoting the demo_parsed field in the database.
FieldDemoParsed = "demo_parsed"
// FieldEco holds the string denoting the eco field in the database.
FieldEco = "eco"
// EdgeStats holds the string denoting the stats edge name in mutations.
EdgeStats = "stats"
// EdgePlayers holds the string denoting the players edge name in mutations.
EdgePlayers = "players"
// Table holds the table name of the match in the database.
Table = "matches"
// StatsTable is the table that holds the stats relation/edge.
StatsTable = "stats"
// StatsInverseTable is the table name for the Stats entity.
// It exists in this package in order to avoid circular dependency with the "stats" package.
StatsInverseTable = "stats"
// StatsColumn is the table column denoting the stats relation/edge.
StatsColumn = "match_stats"
// PlayersTable is the table that holds the players relation/edge. The primary key declared below.
PlayersTable = "player_matches"
// PlayersInverseTable is the table name for the Player entity.
// It exists in this package in order to avoid circular dependency with the "player" package.
PlayersInverseTable = "players"
)
// Columns holds all SQL columns for match fields.
var Columns = []string{
FieldID,
FieldMatchID,
FieldShareCode,
FieldMap,
FieldDate,
FieldScoreTeamA,
FieldScoreTeamB,
FieldReplayURL,
FieldDuration,
FieldMatchResult,
FieldMaxRounds,
FieldDemoExpired,
FieldDemoParsed,
FieldEco,
}
var (
// PlayersPrimaryKey and PlayersColumn2 are the table columns denoting the
// primary key for the players relation (M2M).
PlayersPrimaryKey = []string{"player_id", "match_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultDemoExpired holds the default value on creation for the "demo_expired" field.
DefaultDemoExpired bool
// DefaultDemoParsed holds the default value on creation for the "demo_parsed" field.
DefaultDemoParsed bool
)

1201
ent/match/where.go Normal file

File diff suppressed because it is too large Load Diff

552
ent/match_create.go Normal file
View File

@ -0,0 +1,552 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"csgowtfd/ent/match"
"csgowtfd/ent/player"
"csgowtfd/ent/stats"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// MatchCreate is the builder for creating a Match entity.
type MatchCreate struct {
config
mutation *MatchMutation
hooks []Hook
}
// SetMatchID sets the "match_id" field.
func (mc *MatchCreate) SetMatchID(u uint64) *MatchCreate {
mc.mutation.SetMatchID(u)
return mc
}
// SetShareCode sets the "share_code" field.
func (mc *MatchCreate) SetShareCode(s string) *MatchCreate {
mc.mutation.SetShareCode(s)
return mc
}
// SetMap sets the "map" field.
func (mc *MatchCreate) SetMap(s string) *MatchCreate {
mc.mutation.SetMap(s)
return mc
}
// SetNillableMap sets the "map" field if the given value is not nil.
func (mc *MatchCreate) SetNillableMap(s *string) *MatchCreate {
if s != nil {
mc.SetMap(*s)
}
return mc
}
// SetDate sets the "date" field.
func (mc *MatchCreate) SetDate(t time.Time) *MatchCreate {
mc.mutation.SetDate(t)
return mc
}
// SetScoreTeamA sets the "score_team_a" field.
func (mc *MatchCreate) SetScoreTeamA(i int) *MatchCreate {
mc.mutation.SetScoreTeamA(i)
return mc
}
// SetScoreTeamB sets the "score_team_b" field.
func (mc *MatchCreate) SetScoreTeamB(i int) *MatchCreate {
mc.mutation.SetScoreTeamB(i)
return mc
}
// SetReplayURL sets the "replay_url" field.
func (mc *MatchCreate) SetReplayURL(s string) *MatchCreate {
mc.mutation.SetReplayURL(s)
return mc
}
// SetNillableReplayURL sets the "replay_url" field if the given value is not nil.
func (mc *MatchCreate) SetNillableReplayURL(s *string) *MatchCreate {
if s != nil {
mc.SetReplayURL(*s)
}
return mc
}
// SetDuration sets the "duration" field.
func (mc *MatchCreate) SetDuration(i int) *MatchCreate {
mc.mutation.SetDuration(i)
return mc
}
// SetMatchResult sets the "match_result" field.
func (mc *MatchCreate) SetMatchResult(i int) *MatchCreate {
mc.mutation.SetMatchResult(i)
return mc
}
// SetMaxRounds sets the "max_rounds" field.
func (mc *MatchCreate) SetMaxRounds(i int) *MatchCreate {
mc.mutation.SetMaxRounds(i)
return mc
}
// SetDemoExpired sets the "demo_expired" field.
func (mc *MatchCreate) SetDemoExpired(b bool) *MatchCreate {
mc.mutation.SetDemoExpired(b)
return mc
}
// SetNillableDemoExpired sets the "demo_expired" field if the given value is not nil.
func (mc *MatchCreate) SetNillableDemoExpired(b *bool) *MatchCreate {
if b != nil {
mc.SetDemoExpired(*b)
}
return mc
}
// SetDemoParsed sets the "demo_parsed" field.
func (mc *MatchCreate) SetDemoParsed(b bool) *MatchCreate {
mc.mutation.SetDemoParsed(b)
return mc
}
// SetNillableDemoParsed sets the "demo_parsed" field if the given value is not nil.
func (mc *MatchCreate) SetNillableDemoParsed(b *bool) *MatchCreate {
if b != nil {
mc.SetDemoParsed(*b)
}
return mc
}
// SetEco sets the "eco" field.
func (mc *MatchCreate) SetEco(s struct {
Rounds []*struct {
Team int "json:\"team\""
Bank int "json:\"bank\""
Equipment int "json:\"equipment\""
} "json:\"rounds\""
}) *MatchCreate {
mc.mutation.SetEco(s)
return mc
}
// SetNillableEco sets the "eco" field if the given value is not nil.
func (mc *MatchCreate) SetNillableEco(s *struct {
Rounds []*struct {
Team int "json:\"team\""
Bank int "json:\"bank\""
Equipment int "json:\"equipment\""
} "json:\"rounds\""
}) *MatchCreate {
if s != nil {
mc.SetEco(*s)
}
return mc
}
// AddStatIDs adds the "stats" edge to the Stats entity by IDs.
func (mc *MatchCreate) AddStatIDs(ids ...int) *MatchCreate {
mc.mutation.AddStatIDs(ids...)
return mc
}
// AddStats adds the "stats" edges to the Stats entity.
func (mc *MatchCreate) AddStats(s ...*Stats) *MatchCreate {
ids := make([]int, len(s))
for i := range s {
ids[i] = s[i].ID
}
return mc.AddStatIDs(ids...)
}
// AddPlayerIDs adds the "players" edge to the Player entity by IDs.
func (mc *MatchCreate) AddPlayerIDs(ids ...int) *MatchCreate {
mc.mutation.AddPlayerIDs(ids...)
return mc
}
// AddPlayers adds the "players" edges to the Player entity.
func (mc *MatchCreate) AddPlayers(p ...*Player) *MatchCreate {
ids := make([]int, len(p))
for i := range p {
ids[i] = p[i].ID
}
return mc.AddPlayerIDs(ids...)
}
// Mutation returns the MatchMutation object of the builder.
func (mc *MatchCreate) Mutation() *MatchMutation {
return mc.mutation
}
// Save creates the Match in the database.
func (mc *MatchCreate) Save(ctx context.Context) (*Match, error) {
var (
err error
node *Match
)
mc.defaults()
if len(mc.hooks) == 0 {
if err = mc.check(); err != nil {
return nil, err
}
node, err = mc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*MatchMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = mc.check(); err != nil {
return nil, err
}
mc.mutation = mutation
if node, err = mc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(mc.hooks) - 1; i >= 0; i-- {
if mc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = mc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, mc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (mc *MatchCreate) SaveX(ctx context.Context) *Match {
v, err := mc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (mc *MatchCreate) Exec(ctx context.Context) error {
_, err := mc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (mc *MatchCreate) ExecX(ctx context.Context) {
if err := mc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (mc *MatchCreate) defaults() {
if _, ok := mc.mutation.DemoExpired(); !ok {
v := match.DefaultDemoExpired
mc.mutation.SetDemoExpired(v)
}
if _, ok := mc.mutation.DemoParsed(); !ok {
v := match.DefaultDemoParsed
mc.mutation.SetDemoParsed(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (mc *MatchCreate) check() error {
if _, ok := mc.mutation.MatchID(); !ok {
return &ValidationError{Name: "match_id", err: errors.New(`ent: missing required field "match_id"`)}
}
if _, ok := mc.mutation.ShareCode(); !ok {
return &ValidationError{Name: "share_code", err: errors.New(`ent: missing required field "share_code"`)}
}
if _, ok := mc.mutation.Date(); !ok {
return &ValidationError{Name: "date", err: errors.New(`ent: missing required field "date"`)}
}
if _, ok := mc.mutation.ScoreTeamA(); !ok {
return &ValidationError{Name: "score_team_a", err: errors.New(`ent: missing required field "score_team_a"`)}
}
if _, ok := mc.mutation.ScoreTeamB(); !ok {
return &ValidationError{Name: "score_team_b", err: errors.New(`ent: missing required field "score_team_b"`)}
}
if _, ok := mc.mutation.Duration(); !ok {
return &ValidationError{Name: "duration", err: errors.New(`ent: missing required field "duration"`)}
}
if _, ok := mc.mutation.MatchResult(); !ok {
return &ValidationError{Name: "match_result", err: errors.New(`ent: missing required field "match_result"`)}
}
if _, ok := mc.mutation.MaxRounds(); !ok {
return &ValidationError{Name: "max_rounds", err: errors.New(`ent: missing required field "max_rounds"`)}
}
if _, ok := mc.mutation.DemoExpired(); !ok {
return &ValidationError{Name: "demo_expired", err: errors.New(`ent: missing required field "demo_expired"`)}
}
if _, ok := mc.mutation.DemoParsed(); !ok {
return &ValidationError{Name: "demo_parsed", err: errors.New(`ent: missing required field "demo_parsed"`)}
}
return nil
}
func (mc *MatchCreate) sqlSave(ctx context.Context) (*Match, error) {
_node, _spec := mc.createSpec()
if err := sqlgraph.CreateNode(ctx, mc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
return _node, nil
}
func (mc *MatchCreate) createSpec() (*Match, *sqlgraph.CreateSpec) {
var (
_node = &Match{config: mc.config}
_spec = &sqlgraph.CreateSpec{
Table: match.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: match.FieldID,
},
}
)
if value, ok := mc.mutation.MatchID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeUint64,
Value: value,
Column: match.FieldMatchID,
})
_node.MatchID = value
}
if value, ok := mc.mutation.ShareCode(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: match.FieldShareCode,
})
_node.ShareCode = value
}
if value, ok := mc.mutation.Map(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: match.FieldMap,
})
_node.Map = value
}
if value, ok := mc.mutation.Date(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: match.FieldDate,
})
_node.Date = value
}
if value, ok := mc.mutation.ScoreTeamA(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: match.FieldScoreTeamA,
})
_node.ScoreTeamA = value
}
if value, ok := mc.mutation.ScoreTeamB(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: match.FieldScoreTeamB,
})
_node.ScoreTeamB = value
}
if value, ok := mc.mutation.ReplayURL(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: match.FieldReplayURL,
})
_node.ReplayURL = value
}
if value, ok := mc.mutation.Duration(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: match.FieldDuration,
})
_node.Duration = value
}
if value, ok := mc.mutation.MatchResult(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: match.FieldMatchResult,
})
_node.MatchResult = value
}
if value, ok := mc.mutation.MaxRounds(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: match.FieldMaxRounds,
})
_node.MaxRounds = value
}
if value, ok := mc.mutation.DemoExpired(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: match.FieldDemoExpired,
})
_node.DemoExpired = value
}
if value, ok := mc.mutation.DemoParsed(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: match.FieldDemoParsed,
})
_node.DemoParsed = value
}
if value, ok := mc.mutation.Eco(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: match.FieldEco,
})
_node.Eco = value
}
if nodes := mc.mutation.StatsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: match.StatsTable,
Columns: []string{match.StatsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: stats.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := mc.mutation.PlayersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: true,
Table: match.PlayersTable,
Columns: match.PlayersPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: player.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// MatchCreateBulk is the builder for creating many Match entities in bulk.
type MatchCreateBulk struct {
config
builders []*MatchCreate
}
// Save creates the Match entities in the database.
func (mcb *MatchCreateBulk) Save(ctx context.Context) ([]*Match, error) {
specs := make([]*sqlgraph.CreateSpec, len(mcb.builders))
nodes := make([]*Match, len(mcb.builders))
mutators := make([]Mutator, len(mcb.builders))
for i := range mcb.builders {
func(i int, root context.Context) {
builder := mcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*MatchMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, mcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, mcb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
mutation.done = true
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, mcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (mcb *MatchCreateBulk) SaveX(ctx context.Context) []*Match {
v, err := mcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (mcb *MatchCreateBulk) Exec(ctx context.Context) error {
_, err := mcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (mcb *MatchCreateBulk) ExecX(ctx context.Context) {
if err := mcb.Exec(ctx); err != nil {
panic(err)
}
}

111
ent/match_delete.go Normal file
View File

@ -0,0 +1,111 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"csgowtfd/ent/match"
"csgowtfd/ent/predicate"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// MatchDelete is the builder for deleting a Match entity.
type MatchDelete struct {
config
hooks []Hook
mutation *MatchMutation
}
// Where appends a list predicates to the MatchDelete builder.
func (md *MatchDelete) Where(ps ...predicate.Match) *MatchDelete {
md.mutation.Where(ps...)
return md
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (md *MatchDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(md.hooks) == 0 {
affected, err = md.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*MatchMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
md.mutation = mutation
affected, err = md.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(md.hooks) - 1; i >= 0; i-- {
if md.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = md.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, md.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (md *MatchDelete) ExecX(ctx context.Context) int {
n, err := md.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (md *MatchDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: match.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: match.FieldID,
},
},
}
if ps := md.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, md.driver, _spec)
}
// MatchDeleteOne is the builder for deleting a single Match entity.
type MatchDeleteOne struct {
md *MatchDelete
}
// Exec executes the deletion query.
func (mdo *MatchDeleteOne) Exec(ctx context.Context) error {
n, err := mdo.md.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{match.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (mdo *MatchDeleteOne) ExecX(ctx context.Context) {
mdo.md.ExecX(ctx)
}

1089
ent/match_query.go Normal file

File diff suppressed because it is too large Load Diff

1229
ent/match_update.go Normal file

File diff suppressed because it is too large Load Diff

72
ent/migrate/migrate.go Normal file
View File

@ -0,0 +1,72 @@
// Code generated by entc, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithFixture sets the foreign-key renaming option to the migration when upgrading
// ent from v0.1.0 (issue-#285). Defaults to false.
WithFixture = schema.WithFixture
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
universalID bool
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, Tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
//
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
drv := &schema.WriteDriver{
Writer: w,
Driver: s.drv,
}
migrate, err := schema.NewMigrate(drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, Tables...)
}

128
ent/migrate/schema.go Normal file
View File

@ -0,0 +1,128 @@
// Code generated by entc, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// MatchesColumns holds the columns for the "matches" table.
MatchesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "match_id", Type: field.TypeUint64, Unique: true},
{Name: "share_code", Type: field.TypeString},
{Name: "map", Type: field.TypeString, Nullable: true},
{Name: "date", Type: field.TypeTime},
{Name: "score_team_a", Type: field.TypeInt},
{Name: "score_team_b", Type: field.TypeInt},
{Name: "replay_url", Type: field.TypeString, Nullable: true},
{Name: "duration", Type: field.TypeInt},
{Name: "match_result", Type: field.TypeInt},
{Name: "max_rounds", Type: field.TypeInt},
{Name: "demo_expired", Type: field.TypeBool, Default: false},
{Name: "demo_parsed", Type: field.TypeBool, Default: false},
{Name: "eco", Type: field.TypeJSON, Nullable: true},
}
// MatchesTable holds the schema information for the "matches" table.
MatchesTable = &schema.Table{
Name: "matches",
Columns: MatchesColumns,
PrimaryKey: []*schema.Column{MatchesColumns[0]},
}
// PlayersColumns holds the columns for the "players" table.
PlayersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "steamid", Type: field.TypeUint64, Unique: true},
{Name: "name", Type: field.TypeString, Nullable: true},
{Name: "avatar_url", Type: field.TypeString, Nullable: true},
{Name: "vanity_url", Type: field.TypeString, Nullable: true},
{Name: "vanity_url_real", Type: field.TypeString, Nullable: true},
{Name: "vac", Type: field.TypeBool, Default: false},
{Name: "vac_date", Type: field.TypeTime, Nullable: true},
{Name: "vac_count", Type: field.TypeInt, Nullable: true},
{Name: "steam_updated", Type: field.TypeTime},
{Name: "sharecode_updated", Type: field.TypeTime, Nullable: true},
{Name: "auth_code", Type: field.TypeString, Nullable: true},
}
// PlayersTable holds the schema information for the "players" table.
PlayersTable = &schema.Table{
Name: "players",
Columns: PlayersColumns,
PrimaryKey: []*schema.Column{PlayersColumns[0]},
}
// StatsColumns holds the columns for the "stats" table.
StatsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "team_id", Type: field.TypeInt},
{Name: "kills", Type: field.TypeInt},
{Name: "deaths", Type: field.TypeInt},
{Name: "assists", Type: field.TypeInt},
{Name: "headshot", Type: field.TypeInt},
{Name: "mvp", Type: field.TypeInt},
{Name: "score", Type: field.TypeInt},
{Name: "extended", Type: field.TypeJSON, Nullable: true},
{Name: "match_stats", Type: field.TypeInt, Nullable: true},
{Name: "player_stats", Type: field.TypeInt, Nullable: true},
}
// StatsTable holds the schema information for the "stats" table.
StatsTable = &schema.Table{
Name: "stats",
Columns: StatsColumns,
PrimaryKey: []*schema.Column{StatsColumns[0]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "stats_matches_stats",
Columns: []*schema.Column{StatsColumns[9]},
RefColumns: []*schema.Column{MatchesColumns[0]},
OnDelete: schema.SetNull,
},
{
Symbol: "stats_players_stats",
Columns: []*schema.Column{StatsColumns[10]},
RefColumns: []*schema.Column{PlayersColumns[0]},
OnDelete: schema.SetNull,
},
},
}
// PlayerMatchesColumns holds the columns for the "player_matches" table.
PlayerMatchesColumns = []*schema.Column{
{Name: "player_id", Type: field.TypeInt},
{Name: "match_id", Type: field.TypeInt},
}
// PlayerMatchesTable holds the schema information for the "player_matches" table.
PlayerMatchesTable = &schema.Table{
Name: "player_matches",
Columns: PlayerMatchesColumns,
PrimaryKey: []*schema.Column{PlayerMatchesColumns[0], PlayerMatchesColumns[1]},
ForeignKeys: []*schema.ForeignKey{
{
Symbol: "player_matches_player_id",
Columns: []*schema.Column{PlayerMatchesColumns[0]},
RefColumns: []*schema.Column{PlayersColumns[0]},
OnDelete: schema.Cascade,
},
{
Symbol: "player_matches_match_id",
Columns: []*schema.Column{PlayerMatchesColumns[1]},
RefColumns: []*schema.Column{MatchesColumns[0]},
OnDelete: schema.Cascade,
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
MatchesTable,
PlayersTable,
StatsTable,
PlayerMatchesTable,
}
)
func init() {
StatsTable.ForeignKeys[0].RefTable = MatchesTable
StatsTable.ForeignKeys[1].RefTable = PlayersTable
PlayerMatchesTable.ForeignKeys[0].RefTable = PlayersTable
PlayerMatchesTable.ForeignKeys[1].RefTable = MatchesTable
}

3959
ent/mutation.go Normal file

File diff suppressed because it is too large Load Diff

245
ent/player.go Normal file
View File

@ -0,0 +1,245 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"csgowtfd/ent/player"
"fmt"
"strings"
"time"
"entgo.io/ent/dialect/sql"
)
// Player is the model entity for the Player schema.
type Player struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Steamid holds the value of the "steamid" field.
Steamid uint64 `json:",string"`
// Name holds the value of the "name" field.
Name string `json:"name,omitempty"`
// AvatarURL holds the value of the "avatar_url" field.
AvatarURL string `json:"avatar_url,omitempty"`
// VanityURL holds the value of the "vanity_url" field.
VanityURL string `json:"vanity_url,omitempty"`
// VanityURLReal holds the value of the "vanity_url_real" field.
VanityURLReal string `json:"vanity_url_real,omitempty"`
// Vac holds the value of the "vac" field.
Vac bool `json:"vac,omitempty"`
// VacDate holds the value of the "vac_date" field.
VacDate time.Time `json:"vac_date,omitempty"`
// VacCount holds the value of the "vac_count" field.
VacCount int `json:"vac_count,omitempty"`
// SteamUpdated holds the value of the "steam_updated" field.
SteamUpdated time.Time `json:"-"`
// SharecodeUpdated holds the value of the "sharecode_updated" field.
SharecodeUpdated time.Time `json:"-"`
// AuthCode holds the value of the "auth_code" field.
AuthCode string `json:"-"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the PlayerQuery when eager-loading is set.
Edges PlayerEdges `json:"edges"`
}
// PlayerEdges holds the relations/edges for other nodes in the graph.
type PlayerEdges struct {
// Stats holds the value of the stats edge.
Stats []*Stats `json:"stats,omitempty"`
// Matches holds the value of the matches edge.
Matches []*Match `json:"matches,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// StatsOrErr returns the Stats value or an error if the edge
// was not loaded in eager-loading.
func (e PlayerEdges) StatsOrErr() ([]*Stats, error) {
if e.loadedTypes[0] {
return e.Stats, nil
}
return nil, &NotLoadedError{edge: "stats"}
}
// MatchesOrErr returns the Matches value or an error if the edge
// was not loaded in eager-loading.
func (e PlayerEdges) MatchesOrErr() ([]*Match, error) {
if e.loadedTypes[1] {
return e.Matches, nil
}
return nil, &NotLoadedError{edge: "matches"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Player) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case player.FieldVac:
values[i] = new(sql.NullBool)
case player.FieldID, player.FieldSteamid, player.FieldVacCount:
values[i] = new(sql.NullInt64)
case player.FieldName, player.FieldAvatarURL, player.FieldVanityURL, player.FieldVanityURLReal, player.FieldAuthCode:
values[i] = new(sql.NullString)
case player.FieldVacDate, player.FieldSteamUpdated, player.FieldSharecodeUpdated:
values[i] = new(sql.NullTime)
default:
return nil, fmt.Errorf("unexpected column %q for type Player", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Player fields.
func (pl *Player) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case player.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
pl.ID = int(value.Int64)
case player.FieldSteamid:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field steamid", values[i])
} else if value.Valid {
pl.Steamid = uint64(value.Int64)
}
case player.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field name", values[i])
} else if value.Valid {
pl.Name = value.String
}
case player.FieldAvatarURL:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field avatar_url", values[i])
} else if value.Valid {
pl.AvatarURL = value.String
}
case player.FieldVanityURL:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field vanity_url", values[i])
} else if value.Valid {
pl.VanityURL = value.String
}
case player.FieldVanityURLReal:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field vanity_url_real", values[i])
} else if value.Valid {
pl.VanityURLReal = value.String
}
case player.FieldVac:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field vac", values[i])
} else if value.Valid {
pl.Vac = value.Bool
}
case player.FieldVacDate:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field vac_date", values[i])
} else if value.Valid {
pl.VacDate = value.Time
}
case player.FieldVacCount:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field vac_count", values[i])
} else if value.Valid {
pl.VacCount = int(value.Int64)
}
case player.FieldSteamUpdated:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field steam_updated", values[i])
} else if value.Valid {
pl.SteamUpdated = value.Time
}
case player.FieldSharecodeUpdated:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field sharecode_updated", values[i])
} else if value.Valid {
pl.SharecodeUpdated = value.Time
}
case player.FieldAuthCode:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field auth_code", values[i])
} else if value.Valid {
pl.AuthCode = value.String
}
}
}
return nil
}
// QueryStats queries the "stats" edge of the Player entity.
func (pl *Player) QueryStats() *StatsQuery {
return (&PlayerClient{config: pl.config}).QueryStats(pl)
}
// QueryMatches queries the "matches" edge of the Player entity.
func (pl *Player) QueryMatches() *MatchQuery {
return (&PlayerClient{config: pl.config}).QueryMatches(pl)
}
// Update returns a builder for updating this Player.
// Note that you need to call Player.Unwrap() before calling this method if this Player
// was returned from a transaction, and the transaction was committed or rolled back.
func (pl *Player) Update() *PlayerUpdateOne {
return (&PlayerClient{config: pl.config}).UpdateOne(pl)
}
// Unwrap unwraps the Player entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (pl *Player) Unwrap() *Player {
tx, ok := pl.config.driver.(*txDriver)
if !ok {
panic("ent: Player is not a transactional entity")
}
pl.config.driver = tx.drv
return pl
}
// String implements the fmt.Stringer.
func (pl *Player) String() string {
var builder strings.Builder
builder.WriteString("Player(")
builder.WriteString(fmt.Sprintf("id=%v", pl.ID))
builder.WriteString(", steamid=")
builder.WriteString(fmt.Sprintf("%v", pl.Steamid))
builder.WriteString(", name=")
builder.WriteString(pl.Name)
builder.WriteString(", avatar_url=")
builder.WriteString(pl.AvatarURL)
builder.WriteString(", vanity_url=")
builder.WriteString(pl.VanityURL)
builder.WriteString(", vanity_url_real=")
builder.WriteString(pl.VanityURLReal)
builder.WriteString(", vac=")
builder.WriteString(fmt.Sprintf("%v", pl.Vac))
builder.WriteString(", vac_date=")
builder.WriteString(pl.VacDate.Format(time.ANSIC))
builder.WriteString(", vac_count=")
builder.WriteString(fmt.Sprintf("%v", pl.VacCount))
builder.WriteString(", steam_updated=")
builder.WriteString(pl.SteamUpdated.Format(time.ANSIC))
builder.WriteString(", sharecode_updated=")
builder.WriteString(pl.SharecodeUpdated.Format(time.ANSIC))
builder.WriteString(", auth_code=<sensitive>")
builder.WriteByte(')')
return builder.String()
}
// Players is a parsable slice of Player.
type Players []*Player
func (pl Players) config(cfg config) {
for _i := range pl {
pl[_i].config = cfg
}
}

93
ent/player/player.go Normal file
View File

@ -0,0 +1,93 @@
// Code generated by entc, DO NOT EDIT.
package player
import (
"time"
)
const (
// Label holds the string label denoting the player type in the database.
Label = "player"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldSteamid holds the string denoting the steamid field in the database.
FieldSteamid = "steamid"
// FieldName holds the string denoting the name field in the database.
FieldName = "name"
// FieldAvatarURL holds the string denoting the avatar_url field in the database.
FieldAvatarURL = "avatar_url"
// FieldVanityURL holds the string denoting the vanity_url field in the database.
FieldVanityURL = "vanity_url"
// FieldVanityURLReal holds the string denoting the vanity_url_real field in the database.
FieldVanityURLReal = "vanity_url_real"
// FieldVac holds the string denoting the vac field in the database.
FieldVac = "vac"
// FieldVacDate holds the string denoting the vac_date field in the database.
FieldVacDate = "vac_date"
// FieldVacCount holds the string denoting the vac_count field in the database.
FieldVacCount = "vac_count"
// FieldSteamUpdated holds the string denoting the steam_updated field in the database.
FieldSteamUpdated = "steam_updated"
// FieldSharecodeUpdated holds the string denoting the sharecode_updated field in the database.
FieldSharecodeUpdated = "sharecode_updated"
// FieldAuthCode holds the string denoting the auth_code field in the database.
FieldAuthCode = "auth_code"
// EdgeStats holds the string denoting the stats edge name in mutations.
EdgeStats = "stats"
// EdgeMatches holds the string denoting the matches edge name in mutations.
EdgeMatches = "matches"
// Table holds the table name of the player in the database.
Table = "players"
// StatsTable is the table that holds the stats relation/edge.
StatsTable = "stats"
// StatsInverseTable is the table name for the Stats entity.
// It exists in this package in order to avoid circular dependency with the "stats" package.
StatsInverseTable = "stats"
// StatsColumn is the table column denoting the stats relation/edge.
StatsColumn = "player_stats"
// MatchesTable is the table that holds the matches relation/edge. The primary key declared below.
MatchesTable = "player_matches"
// MatchesInverseTable is the table name for the Match entity.
// It exists in this package in order to avoid circular dependency with the "match" package.
MatchesInverseTable = "matches"
)
// Columns holds all SQL columns for player fields.
var Columns = []string{
FieldID,
FieldSteamid,
FieldName,
FieldAvatarURL,
FieldVanityURL,
FieldVanityURLReal,
FieldVac,
FieldVacDate,
FieldVacCount,
FieldSteamUpdated,
FieldSharecodeUpdated,
FieldAuthCode,
}
var (
// MatchesPrimaryKey and MatchesColumn2 are the table columns denoting the
// primary key for the matches relation (M2M).
MatchesPrimaryKey = []string{"player_id", "match_id"}
)
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultVac holds the default value on creation for the "vac" field.
DefaultVac bool
// DefaultSteamUpdated holds the default value on creation for the "steam_updated" field.
DefaultSteamUpdated func() time.Time
)

1320
ent/player/where.go Normal file

File diff suppressed because it is too large Load Diff

531
ent/player_create.go Normal file
View File

@ -0,0 +1,531 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"csgowtfd/ent/match"
"csgowtfd/ent/player"
"csgowtfd/ent/stats"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// PlayerCreate is the builder for creating a Player entity.
type PlayerCreate struct {
config
mutation *PlayerMutation
hooks []Hook
}
// SetSteamid sets the "steamid" field.
func (pc *PlayerCreate) SetSteamid(u uint64) *PlayerCreate {
pc.mutation.SetSteamid(u)
return pc
}
// SetName sets the "name" field.
func (pc *PlayerCreate) SetName(s string) *PlayerCreate {
pc.mutation.SetName(s)
return pc
}
// SetNillableName sets the "name" field if the given value is not nil.
func (pc *PlayerCreate) SetNillableName(s *string) *PlayerCreate {
if s != nil {
pc.SetName(*s)
}
return pc
}
// SetAvatarURL sets the "avatar_url" field.
func (pc *PlayerCreate) SetAvatarURL(s string) *PlayerCreate {
pc.mutation.SetAvatarURL(s)
return pc
}
// SetNillableAvatarURL sets the "avatar_url" field if the given value is not nil.
func (pc *PlayerCreate) SetNillableAvatarURL(s *string) *PlayerCreate {
if s != nil {
pc.SetAvatarURL(*s)
}
return pc
}
// SetVanityURL sets the "vanity_url" field.
func (pc *PlayerCreate) SetVanityURL(s string) *PlayerCreate {
pc.mutation.SetVanityURL(s)
return pc
}
// SetNillableVanityURL sets the "vanity_url" field if the given value is not nil.
func (pc *PlayerCreate) SetNillableVanityURL(s *string) *PlayerCreate {
if s != nil {
pc.SetVanityURL(*s)
}
return pc
}
// SetVanityURLReal sets the "vanity_url_real" field.
func (pc *PlayerCreate) SetVanityURLReal(s string) *PlayerCreate {
pc.mutation.SetVanityURLReal(s)
return pc
}
// SetNillableVanityURLReal sets the "vanity_url_real" field if the given value is not nil.
func (pc *PlayerCreate) SetNillableVanityURLReal(s *string) *PlayerCreate {
if s != nil {
pc.SetVanityURLReal(*s)
}
return pc
}
// SetVac sets the "vac" field.
func (pc *PlayerCreate) SetVac(b bool) *PlayerCreate {
pc.mutation.SetVac(b)
return pc
}
// SetNillableVac sets the "vac" field if the given value is not nil.
func (pc *PlayerCreate) SetNillableVac(b *bool) *PlayerCreate {
if b != nil {
pc.SetVac(*b)
}
return pc
}
// SetVacDate sets the "vac_date" field.
func (pc *PlayerCreate) SetVacDate(t time.Time) *PlayerCreate {
pc.mutation.SetVacDate(t)
return pc
}
// SetNillableVacDate sets the "vac_date" field if the given value is not nil.
func (pc *PlayerCreate) SetNillableVacDate(t *time.Time) *PlayerCreate {
if t != nil {
pc.SetVacDate(*t)
}
return pc
}
// SetVacCount sets the "vac_count" field.
func (pc *PlayerCreate) SetVacCount(i int) *PlayerCreate {
pc.mutation.SetVacCount(i)
return pc
}
// SetNillableVacCount sets the "vac_count" field if the given value is not nil.
func (pc *PlayerCreate) SetNillableVacCount(i *int) *PlayerCreate {
if i != nil {
pc.SetVacCount(*i)
}
return pc
}
// SetSteamUpdated sets the "steam_updated" field.
func (pc *PlayerCreate) SetSteamUpdated(t time.Time) *PlayerCreate {
pc.mutation.SetSteamUpdated(t)
return pc
}
// SetNillableSteamUpdated sets the "steam_updated" field if the given value is not nil.
func (pc *PlayerCreate) SetNillableSteamUpdated(t *time.Time) *PlayerCreate {
if t != nil {
pc.SetSteamUpdated(*t)
}
return pc
}
// SetSharecodeUpdated sets the "sharecode_updated" field.
func (pc *PlayerCreate) SetSharecodeUpdated(t time.Time) *PlayerCreate {
pc.mutation.SetSharecodeUpdated(t)
return pc
}
// SetNillableSharecodeUpdated sets the "sharecode_updated" field if the given value is not nil.
func (pc *PlayerCreate) SetNillableSharecodeUpdated(t *time.Time) *PlayerCreate {
if t != nil {
pc.SetSharecodeUpdated(*t)
}
return pc
}
// SetAuthCode sets the "auth_code" field.
func (pc *PlayerCreate) SetAuthCode(s string) *PlayerCreate {
pc.mutation.SetAuthCode(s)
return pc
}
// SetNillableAuthCode sets the "auth_code" field if the given value is not nil.
func (pc *PlayerCreate) SetNillableAuthCode(s *string) *PlayerCreate {
if s != nil {
pc.SetAuthCode(*s)
}
return pc
}
// AddStatIDs adds the "stats" edge to the Stats entity by IDs.
func (pc *PlayerCreate) AddStatIDs(ids ...int) *PlayerCreate {
pc.mutation.AddStatIDs(ids...)
return pc
}
// AddStats adds the "stats" edges to the Stats entity.
func (pc *PlayerCreate) AddStats(s ...*Stats) *PlayerCreate {
ids := make([]int, len(s))
for i := range s {
ids[i] = s[i].ID
}
return pc.AddStatIDs(ids...)
}
// AddMatchIDs adds the "matches" edge to the Match entity by IDs.
func (pc *PlayerCreate) AddMatchIDs(ids ...int) *PlayerCreate {
pc.mutation.AddMatchIDs(ids...)
return pc
}
// AddMatches adds the "matches" edges to the Match entity.
func (pc *PlayerCreate) AddMatches(m ...*Match) *PlayerCreate {
ids := make([]int, len(m))
for i := range m {
ids[i] = m[i].ID
}
return pc.AddMatchIDs(ids...)
}
// Mutation returns the PlayerMutation object of the builder.
func (pc *PlayerCreate) Mutation() *PlayerMutation {
return pc.mutation
}
// Save creates the Player in the database.
func (pc *PlayerCreate) Save(ctx context.Context) (*Player, error) {
var (
err error
node *Player
)
pc.defaults()
if len(pc.hooks) == 0 {
if err = pc.check(); err != nil {
return nil, err
}
node, err = pc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PlayerMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = pc.check(); err != nil {
return nil, err
}
pc.mutation = mutation
if node, err = pc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(pc.hooks) - 1; i >= 0; i-- {
if pc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = pc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, pc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (pc *PlayerCreate) SaveX(ctx context.Context) *Player {
v, err := pc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (pc *PlayerCreate) Exec(ctx context.Context) error {
_, err := pc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (pc *PlayerCreate) ExecX(ctx context.Context) {
if err := pc.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (pc *PlayerCreate) defaults() {
if _, ok := pc.mutation.Vac(); !ok {
v := player.DefaultVac
pc.mutation.SetVac(v)
}
if _, ok := pc.mutation.SteamUpdated(); !ok {
v := player.DefaultSteamUpdated()
pc.mutation.SetSteamUpdated(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (pc *PlayerCreate) check() error {
if _, ok := pc.mutation.Steamid(); !ok {
return &ValidationError{Name: "steamid", err: errors.New(`ent: missing required field "steamid"`)}
}
if _, ok := pc.mutation.Vac(); !ok {
return &ValidationError{Name: "vac", err: errors.New(`ent: missing required field "vac"`)}
}
if _, ok := pc.mutation.SteamUpdated(); !ok {
return &ValidationError{Name: "steam_updated", err: errors.New(`ent: missing required field "steam_updated"`)}
}
return nil
}
func (pc *PlayerCreate) sqlSave(ctx context.Context) (*Player, error) {
_node, _spec := pc.createSpec()
if err := sqlgraph.CreateNode(ctx, pc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
return _node, nil
}
func (pc *PlayerCreate) createSpec() (*Player, *sqlgraph.CreateSpec) {
var (
_node = &Player{config: pc.config}
_spec = &sqlgraph.CreateSpec{
Table: player.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: player.FieldID,
},
}
)
if value, ok := pc.mutation.Steamid(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeUint64,
Value: value,
Column: player.FieldSteamid,
})
_node.Steamid = value
}
if value, ok := pc.mutation.Name(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: player.FieldName,
})
_node.Name = value
}
if value, ok := pc.mutation.AvatarURL(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: player.FieldAvatarURL,
})
_node.AvatarURL = value
}
if value, ok := pc.mutation.VanityURL(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: player.FieldVanityURL,
})
_node.VanityURL = value
}
if value, ok := pc.mutation.VanityURLReal(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: player.FieldVanityURLReal,
})
_node.VanityURLReal = value
}
if value, ok := pc.mutation.Vac(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeBool,
Value: value,
Column: player.FieldVac,
})
_node.Vac = value
}
if value, ok := pc.mutation.VacDate(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: player.FieldVacDate,
})
_node.VacDate = value
}
if value, ok := pc.mutation.VacCount(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: player.FieldVacCount,
})
_node.VacCount = value
}
if value, ok := pc.mutation.SteamUpdated(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: player.FieldSteamUpdated,
})
_node.SteamUpdated = value
}
if value, ok := pc.mutation.SharecodeUpdated(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeTime,
Value: value,
Column: player.FieldSharecodeUpdated,
})
_node.SharecodeUpdated = value
}
if value, ok := pc.mutation.AuthCode(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeString,
Value: value,
Column: player.FieldAuthCode,
})
_node.AuthCode = value
}
if nodes := pc.mutation.StatsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
Inverse: false,
Table: player.StatsTable,
Columns: []string{player.StatsColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: stats.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := pc.mutation.MatchesIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2M,
Inverse: false,
Table: player.MatchesTable,
Columns: player.MatchesPrimaryKey,
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: match.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// PlayerCreateBulk is the builder for creating many Player entities in bulk.
type PlayerCreateBulk struct {
config
builders []*PlayerCreate
}
// Save creates the Player entities in the database.
func (pcb *PlayerCreateBulk) Save(ctx context.Context) ([]*Player, error) {
specs := make([]*sqlgraph.CreateSpec, len(pcb.builders))
nodes := make([]*Player, len(pcb.builders))
mutators := make([]Mutator, len(pcb.builders))
for i := range pcb.builders {
func(i int, root context.Context) {
builder := pcb.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PlayerMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, pcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, pcb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
mutation.done = true
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, pcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (pcb *PlayerCreateBulk) SaveX(ctx context.Context) []*Player {
v, err := pcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (pcb *PlayerCreateBulk) Exec(ctx context.Context) error {
_, err := pcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (pcb *PlayerCreateBulk) ExecX(ctx context.Context) {
if err := pcb.Exec(ctx); err != nil {
panic(err)
}
}

111
ent/player_delete.go Normal file
View File

@ -0,0 +1,111 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"csgowtfd/ent/player"
"csgowtfd/ent/predicate"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// PlayerDelete is the builder for deleting a Player entity.
type PlayerDelete struct {
config
hooks []Hook
mutation *PlayerMutation
}
// Where appends a list predicates to the PlayerDelete builder.
func (pd *PlayerDelete) Where(ps ...predicate.Player) *PlayerDelete {
pd.mutation.Where(ps...)
return pd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (pd *PlayerDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(pd.hooks) == 0 {
affected, err = pd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*PlayerMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
pd.mutation = mutation
affected, err = pd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(pd.hooks) - 1; i >= 0; i-- {
if pd.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = pd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, pd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (pd *PlayerDelete) ExecX(ctx context.Context) int {
n, err := pd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (pd *PlayerDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: player.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: player.FieldID,
},
},
}
if ps := pd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, pd.driver, _spec)
}
// PlayerDeleteOne is the builder for deleting a single Player entity.
type PlayerDeleteOne struct {
pd *PlayerDelete
}
// Exec executes the deletion query.
func (pdo *PlayerDeleteOne) Exec(ctx context.Context) error {
n, err := pdo.pd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{player.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (pdo *PlayerDeleteOne) ExecX(ctx context.Context) {
pdo.pd.ExecX(ctx)
}

1089
ent/player_query.go Normal file

File diff suppressed because it is too large Load Diff

1241
ent/player_update.go Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,16 @@
// Code generated by entc, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Match is the predicate function for match builders.
type Match func(*sql.Selector)
// Player is the predicate function for player builders.
type Player func(*sql.Selector)
// Stats is the predicate function for stats builders.
type Stats func(*sql.Selector)

36
ent/runtime.go Normal file
View File

@ -0,0 +1,36 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"csgowtfd/ent/match"
"csgowtfd/ent/player"
"csgowtfd/ent/schema"
"time"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
matchFields := schema.Match{}.Fields()
_ = matchFields
// matchDescDemoExpired is the schema descriptor for demo_expired field.
matchDescDemoExpired := matchFields[10].Descriptor()
// match.DefaultDemoExpired holds the default value on creation for the demo_expired field.
match.DefaultDemoExpired = matchDescDemoExpired.Default.(bool)
// matchDescDemoParsed is the schema descriptor for demo_parsed field.
matchDescDemoParsed := matchFields[11].Descriptor()
// match.DefaultDemoParsed holds the default value on creation for the demo_parsed field.
match.DefaultDemoParsed = matchDescDemoParsed.Default.(bool)
playerFields := schema.Player{}.Fields()
_ = playerFields
// playerDescVac is the schema descriptor for vac field.
playerDescVac := playerFields[5].Descriptor()
// player.DefaultVac holds the default value on creation for the vac field.
player.DefaultVac = playerDescVac.Default.(bool)
// playerDescSteamUpdated is the schema descriptor for steam_updated field.
playerDescSteamUpdated := playerFields[8].Descriptor()
// player.DefaultSteamUpdated holds the default value on creation for the steam_updated field.
player.DefaultSteamUpdated = playerDescSteamUpdated.Default.(func() time.Time)
}

10
ent/runtime/runtime.go Normal file
View File

@ -0,0 +1,10 @@
// Code generated by entc, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in csgowtfd/ent/runtime.go
const (
Version = "v0.9.1" // Version of ent codegen.
Sum = "h1:IG8andyeD79GG24U8Q+1Y45hQXj6gY5evSBcva5gtBk=" // Sum of ent codegen.
)

45
ent/schema/match.go Normal file
View File

@ -0,0 +1,45 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// Match holds the schema definition for the Match entity.
type Match struct {
ent.Schema
}
// Fields of the Match.
func (Match) Fields() []ent.Field {
return []ent.Field{
field.Uint64("match_id").Unique().Immutable().StructTag(`json:"match_id,string"`),
field.String("share_code"),
field.String("map").Optional(),
field.Time("date"),
field.Int("score_team_a"),
field.Int("score_team_b"),
field.String("replay_url").Optional().StructTag(`json:"-"`),
field.Int("duration"),
field.Int("match_result"),
field.Int("max_rounds"),
field.Bool("demo_expired").Default(false),
field.Bool("demo_parsed").Default(false),
field.JSON("eco", struct {
Rounds []*struct {
Team int `json:"team"`
Bank int `json:"bank"`
Equipment int `json:"equipment"`
} `json:"rounds"`
}{}).Optional(),
}
}
// Edges of the Match.
func (Match) Edges() []ent.Edge {
return []ent.Edge{
edge.To("stats", Stats.Type),
edge.From("players", Player.Type).Ref("matches"),
}
}

40
ent/schema/player.go Normal file
View File

@ -0,0 +1,40 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"time"
)
// Player holds the schema definition for the Player entity.
type Player struct {
ent.Schema
}
// Fields of the Player.
func (Player) Fields() []ent.Field {
return []ent.Field{
field.Uint64("steamid").Unique().Immutable().StructTag(`json:",string"`),
field.String("name").Optional(),
field.String("avatar_url").Optional(),
field.String("vanity_url").Optional(),
field.String("vanity_url_real").Optional(),
field.Bool("vac").Default(false),
field.Time("vac_date").Optional(),
field.Int("vac_count").Optional(),
field.Time("steam_updated").Default(func() time.Time {
return time.Now().UTC()
}).StructTag(`json:"-"`),
field.Time("sharecode_updated").Optional().StructTag(`json:"-"`),
field.String("auth_code").Optional().Sensitive(),
}
}
// Edges of the Player.
func (Player) Edges() []ent.Edge {
return []ent.Edge{
edge.To("stats", Stats.Type),
edge.To("matches", Match.Type),
}
}

81
ent/schema/stats.go Normal file
View File

@ -0,0 +1,81 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
)
// Stats holds the schema definition for the Stats entity.
type Stats struct {
ent.Schema
}
// Fields of the Stats.
func (Stats) Fields() []ent.Field {
return []ent.Field{
field.Int("team_id"),
field.Int("kills"),
field.Int("deaths"),
field.Int("assists"),
field.Int("headshot"),
field.Int("mvp"),
field.Int("score"),
field.JSON("extended", struct {
MultiKills struct {
Duo int `json:"duo,omitempty"`
Triple int `json:"triple,omitempty"`
Quad int `json:"quad,omitempty"`
Pent int `json:"pent,omitempty"`
} `json:"multi_kills,omitempty"`
Dmg struct {
Enemy int `json:"enemy,omitempty"`
Team int `json:"team,omitempty"`
UD struct {
HE int `json:"he,omitempty"`
Flames int `json:"flames,omitempty"`
Flash int `json:"flash,omitempty"`
Decoy int `json:"decoy,omitempty"`
Smoke int `json:"smoke,omitempty"`
} `json:"ud,omitempty"`
HitGroup struct {
Head int `json:"head,omitempty"`
Chest int `json:"chest,omitempty"`
Stomach int `json:"stomach,omitempty"`
LeftArm int `json:"left_arm,omitempty"`
RightArm int `json:"right_arm,omitempty"`
LeftLeg int `json:"left_leg,omitempty"`
RightLeg int `json:"right_leg,omitempty"`
Gear int `json:"gear,omitempty"`
} `json:"hit_group,omitempty"`
} `json:"dmg,omitempty"`
Crosshair string `json:"crosshair,omitempty"`
Color int `json:"color,omitempty"`
KAST int `json:"kast,omitempty"`
Rank struct {
Old int `json:"old,omitempty"`
New int `json:"new,omitempty"`
} `json:"rank,omitempty"`
Flash struct {
Duration struct {
Self float32 `json:"self,omitempty"`
Team float32 `json:"team,omitempty"`
Enemy float32 `json:"enemy,omitempty"`
} `json:"duration,omitempty"`
Total struct {
Team int `json:"team,omitempty"`
Enemy int `json:"enemy,omitempty"`
Self int `json:"self,omitempty"`
} `json:"total,omitempty"`
} `json:"flash,omitempty"`
}{}).Optional(),
}
}
// Edges of the Stats.
func (Stats) Edges() []ent.Edge {
return []ent.Edge{
edge.From("matches", Match.Type).Ref("stats").Unique(),
edge.From("players", Player.Type).Ref("stats").Unique(),
}
}

293
ent/stats.go Normal file
View File

@ -0,0 +1,293 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"csgowtfd/ent/match"
"csgowtfd/ent/player"
"csgowtfd/ent/stats"
"encoding/json"
"fmt"
"strings"
"entgo.io/ent/dialect/sql"
)
// Stats is the model entity for the Stats schema.
type Stats struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// TeamID holds the value of the "team_id" field.
TeamID int `json:"team_id,omitempty"`
// Kills holds the value of the "kills" field.
Kills int `json:"kills,omitempty"`
// Deaths holds the value of the "deaths" field.
Deaths int `json:"deaths,omitempty"`
// Assists holds the value of the "assists" field.
Assists int `json:"assists,omitempty"`
// Headshot holds the value of the "headshot" field.
Headshot int `json:"headshot,omitempty"`
// Mvp holds the value of the "mvp" field.
Mvp int `json:"mvp,omitempty"`
// Score holds the value of the "score" field.
Score int `json:"score,omitempty"`
// Extended holds the value of the "extended" field.
Extended struct {
MultiKills struct {
Duo int "json:\"duo,omitempty\""
Triple int "json:\"triple,omitempty\""
Quad int "json:\"quad,omitempty\""
Pent int "json:\"pent,omitempty\""
} "json:\"multi_kills,omitempty\""
Dmg struct {
Enemy int "json:\"enemy,omitempty\""
Team int "json:\"team,omitempty\""
UD struct {
HE int "json:\"he,omitempty\""
Flames int "json:\"flames,omitempty\""
Flash int "json:\"flash,omitempty\""
Decoy int "json:\"decoy,omitempty\""
Smoke int "json:\"smoke,omitempty\""
} "json:\"ud,omitempty\""
HitGroup struct {
Head int "json:\"head,omitempty\""
Chest int "json:\"chest,omitempty\""
Stomach int "json:\"stomach,omitempty\""
LeftArm int "json:\"left_arm,omitempty\""
RightArm int "json:\"right_arm,omitempty\""
LeftLeg int "json:\"left_leg,omitempty\""
RightLeg int "json:\"right_leg,omitempty\""
Gear int "json:\"gear,omitempty\""
} "json:\"hit_group,omitempty\""
} "json:\"dmg,omitempty\""
Crosshair string "json:\"crosshair,omitempty\""
Color int "json:\"color,omitempty\""
KAST int "json:\"kast,omitempty\""
Rank struct {
Old int "json:\"old,omitempty\""
New int "json:\"new,omitempty\""
} "json:\"rank,omitempty\""
Flash struct {
Duration struct {
Self float32 "json:\"self,omitempty\""
Team float32 "json:\"team,omitempty\""
Enemy float32 "json:\"enemy,omitempty\""
} "json:\"duration,omitempty\""
Total struct {
Team int "json:\"team,omitempty\""
Enemy int "json:\"enemy,omitempty\""
Self int "json:\"self,omitempty\""
} "json:\"total,omitempty\""
} "json:\"flash,omitempty\""
} `json:"extended,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the StatsQuery when eager-loading is set.
Edges StatsEdges `json:"edges"`
match_stats *int
player_stats *int
}
// StatsEdges holds the relations/edges for other nodes in the graph.
type StatsEdges struct {
// Matches holds the value of the matches edge.
Matches *Match `json:"matches,omitempty"`
// Players holds the value of the players edge.
Players *Player `json:"players,omitempty"`
// loadedTypes holds the information for reporting if a
// type was loaded (or requested) in eager-loading or not.
loadedTypes [2]bool
}
// MatchesOrErr returns the Matches value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e StatsEdges) MatchesOrErr() (*Match, error) {
if e.loadedTypes[0] {
if e.Matches == nil {
// The edge matches was loaded in eager-loading,
// but was not found.
return nil, &NotFoundError{label: match.Label}
}
return e.Matches, nil
}
return nil, &NotLoadedError{edge: "matches"}
}
// PlayersOrErr returns the Players value or an error if the edge
// was not loaded in eager-loading, or loaded but was not found.
func (e StatsEdges) PlayersOrErr() (*Player, error) {
if e.loadedTypes[1] {
if e.Players == nil {
// The edge players was loaded in eager-loading,
// but was not found.
return nil, &NotFoundError{label: player.Label}
}
return e.Players, nil
}
return nil, &NotLoadedError{edge: "players"}
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Stats) scanValues(columns []string) ([]interface{}, error) {
values := make([]interface{}, len(columns))
for i := range columns {
switch columns[i] {
case stats.FieldExtended:
values[i] = new([]byte)
case stats.FieldID, stats.FieldTeamID, stats.FieldKills, stats.FieldDeaths, stats.FieldAssists, stats.FieldHeadshot, stats.FieldMvp, stats.FieldScore:
values[i] = new(sql.NullInt64)
case stats.ForeignKeys[0]: // match_stats
values[i] = new(sql.NullInt64)
case stats.ForeignKeys[1]: // player_stats
values[i] = new(sql.NullInt64)
default:
return nil, fmt.Errorf("unexpected column %q for type Stats", columns[i])
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Stats fields.
func (s *Stats) assignValues(columns []string, values []interface{}) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case stats.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
s.ID = int(value.Int64)
case stats.FieldTeamID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field team_id", values[i])
} else if value.Valid {
s.TeamID = int(value.Int64)
}
case stats.FieldKills:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field kills", values[i])
} else if value.Valid {
s.Kills = int(value.Int64)
}
case stats.FieldDeaths:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field deaths", values[i])
} else if value.Valid {
s.Deaths = int(value.Int64)
}
case stats.FieldAssists:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field assists", values[i])
} else if value.Valid {
s.Assists = int(value.Int64)
}
case stats.FieldHeadshot:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field headshot", values[i])
} else if value.Valid {
s.Headshot = int(value.Int64)
}
case stats.FieldMvp:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field mvp", values[i])
} else if value.Valid {
s.Mvp = int(value.Int64)
}
case stats.FieldScore:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field score", values[i])
} else if value.Valid {
s.Score = int(value.Int64)
}
case stats.FieldExtended:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field extended", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &s.Extended); err != nil {
return fmt.Errorf("unmarshal field extended: %w", err)
}
}
case stats.ForeignKeys[0]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field match_stats", value)
} else if value.Valid {
s.match_stats = new(int)
*s.match_stats = int(value.Int64)
}
case stats.ForeignKeys[1]:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for edge-field player_stats", value)
} else if value.Valid {
s.player_stats = new(int)
*s.player_stats = int(value.Int64)
}
}
}
return nil
}
// QueryMatches queries the "matches" edge of the Stats entity.
func (s *Stats) QueryMatches() *MatchQuery {
return (&StatsClient{config: s.config}).QueryMatches(s)
}
// QueryPlayers queries the "players" edge of the Stats entity.
func (s *Stats) QueryPlayers() *PlayerQuery {
return (&StatsClient{config: s.config}).QueryPlayers(s)
}
// Update returns a builder for updating this Stats.
// Note that you need to call Stats.Unwrap() before calling this method if this Stats
// was returned from a transaction, and the transaction was committed or rolled back.
func (s *Stats) Update() *StatsUpdateOne {
return (&StatsClient{config: s.config}).UpdateOne(s)
}
// Unwrap unwraps the Stats entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (s *Stats) Unwrap() *Stats {
tx, ok := s.config.driver.(*txDriver)
if !ok {
panic("ent: Stats is not a transactional entity")
}
s.config.driver = tx.drv
return s
}
// String implements the fmt.Stringer.
func (s *Stats) String() string {
var builder strings.Builder
builder.WriteString("Stats(")
builder.WriteString(fmt.Sprintf("id=%v", s.ID))
builder.WriteString(", team_id=")
builder.WriteString(fmt.Sprintf("%v", s.TeamID))
builder.WriteString(", kills=")
builder.WriteString(fmt.Sprintf("%v", s.Kills))
builder.WriteString(", deaths=")
builder.WriteString(fmt.Sprintf("%v", s.Deaths))
builder.WriteString(", assists=")
builder.WriteString(fmt.Sprintf("%v", s.Assists))
builder.WriteString(", headshot=")
builder.WriteString(fmt.Sprintf("%v", s.Headshot))
builder.WriteString(", mvp=")
builder.WriteString(fmt.Sprintf("%v", s.Mvp))
builder.WriteString(", score=")
builder.WriteString(fmt.Sprintf("%v", s.Score))
builder.WriteString(", extended=")
builder.WriteString(fmt.Sprintf("%v", s.Extended))
builder.WriteByte(')')
return builder.String()
}
// StatsSlice is a parsable slice of Stats.
type StatsSlice []*Stats
func (s StatsSlice) config(cfg config) {
for _i := range s {
s[_i].config = cfg
}
}

81
ent/stats/stats.go Normal file
View File

@ -0,0 +1,81 @@
// Code generated by entc, DO NOT EDIT.
package stats
const (
// Label holds the string label denoting the stats type in the database.
Label = "stats"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldTeamID holds the string denoting the team_id field in the database.
FieldTeamID = "team_id"
// FieldKills holds the string denoting the kills field in the database.
FieldKills = "kills"
// FieldDeaths holds the string denoting the deaths field in the database.
FieldDeaths = "deaths"
// FieldAssists holds the string denoting the assists field in the database.
FieldAssists = "assists"
// FieldHeadshot holds the string denoting the headshot field in the database.
FieldHeadshot = "headshot"
// FieldMvp holds the string denoting the mvp field in the database.
FieldMvp = "mvp"
// FieldScore holds the string denoting the score field in the database.
FieldScore = "score"
// FieldExtended holds the string denoting the extended field in the database.
FieldExtended = "extended"
// EdgeMatches holds the string denoting the matches edge name in mutations.
EdgeMatches = "matches"
// EdgePlayers holds the string denoting the players edge name in mutations.
EdgePlayers = "players"
// Table holds the table name of the stats in the database.
Table = "stats"
// MatchesTable is the table that holds the matches relation/edge.
MatchesTable = "stats"
// MatchesInverseTable is the table name for the Match entity.
// It exists in this package in order to avoid circular dependency with the "match" package.
MatchesInverseTable = "matches"
// MatchesColumn is the table column denoting the matches relation/edge.
MatchesColumn = "match_stats"
// PlayersTable is the table that holds the players relation/edge.
PlayersTable = "stats"
// PlayersInverseTable is the table name for the Player entity.
// It exists in this package in order to avoid circular dependency with the "player" package.
PlayersInverseTable = "players"
// PlayersColumn is the table column denoting the players relation/edge.
PlayersColumn = "player_stats"
)
// Columns holds all SQL columns for stats fields.
var Columns = []string{
FieldID,
FieldTeamID,
FieldKills,
FieldDeaths,
FieldAssists,
FieldHeadshot,
FieldMvp,
FieldScore,
FieldExtended,
}
// ForeignKeys holds the SQL foreign-keys that are owned by the "stats"
// table and are not defined as standalone fields in the schema.
var ForeignKeys = []string{
"match_stats",
"player_stats",
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
for i := range ForeignKeys {
if column == ForeignKeys[i] {
return true
}
}
return false
}

776
ent/stats/where.go Normal file
View File

@ -0,0 +1,776 @@
// Code generated by entc, DO NOT EDIT.
package stats
import (
"csgowtfd/ent/predicate"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldID), id))
})
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldID), id))
})
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.In(s.C(FieldID), v...))
})
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(ids) == 0 {
s.Where(sql.False())
return
}
v := make([]interface{}, len(ids))
for i := range v {
v[i] = ids[i]
}
s.Where(sql.NotIn(s.C(FieldID), v...))
})
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldID), id))
})
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldID), id))
})
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldID), id))
})
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldID), id))
})
}
// TeamID applies equality check predicate on the "team_id" field. It's identical to TeamIDEQ.
func TeamID(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTeamID), v))
})
}
// Kills applies equality check predicate on the "kills" field. It's identical to KillsEQ.
func Kills(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldKills), v))
})
}
// Deaths applies equality check predicate on the "deaths" field. It's identical to DeathsEQ.
func Deaths(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDeaths), v))
})
}
// Assists applies equality check predicate on the "assists" field. It's identical to AssistsEQ.
func Assists(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldAssists), v))
})
}
// Headshot applies equality check predicate on the "headshot" field. It's identical to HeadshotEQ.
func Headshot(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldHeadshot), v))
})
}
// Mvp applies equality check predicate on the "mvp" field. It's identical to MvpEQ.
func Mvp(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldMvp), v))
})
}
// Score applies equality check predicate on the "score" field. It's identical to ScoreEQ.
func Score(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldScore), v))
})
}
// TeamIDEQ applies the EQ predicate on the "team_id" field.
func TeamIDEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldTeamID), v))
})
}
// TeamIDNEQ applies the NEQ predicate on the "team_id" field.
func TeamIDNEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldTeamID), v))
})
}
// TeamIDIn applies the In predicate on the "team_id" field.
func TeamIDIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldTeamID), v...))
})
}
// TeamIDNotIn applies the NotIn predicate on the "team_id" field.
func TeamIDNotIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldTeamID), v...))
})
}
// TeamIDGT applies the GT predicate on the "team_id" field.
func TeamIDGT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldTeamID), v))
})
}
// TeamIDGTE applies the GTE predicate on the "team_id" field.
func TeamIDGTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldTeamID), v))
})
}
// TeamIDLT applies the LT predicate on the "team_id" field.
func TeamIDLT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldTeamID), v))
})
}
// TeamIDLTE applies the LTE predicate on the "team_id" field.
func TeamIDLTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldTeamID), v))
})
}
// KillsEQ applies the EQ predicate on the "kills" field.
func KillsEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldKills), v))
})
}
// KillsNEQ applies the NEQ predicate on the "kills" field.
func KillsNEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldKills), v))
})
}
// KillsIn applies the In predicate on the "kills" field.
func KillsIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldKills), v...))
})
}
// KillsNotIn applies the NotIn predicate on the "kills" field.
func KillsNotIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldKills), v...))
})
}
// KillsGT applies the GT predicate on the "kills" field.
func KillsGT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldKills), v))
})
}
// KillsGTE applies the GTE predicate on the "kills" field.
func KillsGTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldKills), v))
})
}
// KillsLT applies the LT predicate on the "kills" field.
func KillsLT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldKills), v))
})
}
// KillsLTE applies the LTE predicate on the "kills" field.
func KillsLTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldKills), v))
})
}
// DeathsEQ applies the EQ predicate on the "deaths" field.
func DeathsEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldDeaths), v))
})
}
// DeathsNEQ applies the NEQ predicate on the "deaths" field.
func DeathsNEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldDeaths), v))
})
}
// DeathsIn applies the In predicate on the "deaths" field.
func DeathsIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldDeaths), v...))
})
}
// DeathsNotIn applies the NotIn predicate on the "deaths" field.
func DeathsNotIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldDeaths), v...))
})
}
// DeathsGT applies the GT predicate on the "deaths" field.
func DeathsGT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldDeaths), v))
})
}
// DeathsGTE applies the GTE predicate on the "deaths" field.
func DeathsGTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldDeaths), v))
})
}
// DeathsLT applies the LT predicate on the "deaths" field.
func DeathsLT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldDeaths), v))
})
}
// DeathsLTE applies the LTE predicate on the "deaths" field.
func DeathsLTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldDeaths), v))
})
}
// AssistsEQ applies the EQ predicate on the "assists" field.
func AssistsEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldAssists), v))
})
}
// AssistsNEQ applies the NEQ predicate on the "assists" field.
func AssistsNEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldAssists), v))
})
}
// AssistsIn applies the In predicate on the "assists" field.
func AssistsIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldAssists), v...))
})
}
// AssistsNotIn applies the NotIn predicate on the "assists" field.
func AssistsNotIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldAssists), v...))
})
}
// AssistsGT applies the GT predicate on the "assists" field.
func AssistsGT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldAssists), v))
})
}
// AssistsGTE applies the GTE predicate on the "assists" field.
func AssistsGTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldAssists), v))
})
}
// AssistsLT applies the LT predicate on the "assists" field.
func AssistsLT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldAssists), v))
})
}
// AssistsLTE applies the LTE predicate on the "assists" field.
func AssistsLTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldAssists), v))
})
}
// HeadshotEQ applies the EQ predicate on the "headshot" field.
func HeadshotEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldHeadshot), v))
})
}
// HeadshotNEQ applies the NEQ predicate on the "headshot" field.
func HeadshotNEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldHeadshot), v))
})
}
// HeadshotIn applies the In predicate on the "headshot" field.
func HeadshotIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldHeadshot), v...))
})
}
// HeadshotNotIn applies the NotIn predicate on the "headshot" field.
func HeadshotNotIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldHeadshot), v...))
})
}
// HeadshotGT applies the GT predicate on the "headshot" field.
func HeadshotGT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldHeadshot), v))
})
}
// HeadshotGTE applies the GTE predicate on the "headshot" field.
func HeadshotGTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldHeadshot), v))
})
}
// HeadshotLT applies the LT predicate on the "headshot" field.
func HeadshotLT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldHeadshot), v))
})
}
// HeadshotLTE applies the LTE predicate on the "headshot" field.
func HeadshotLTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldHeadshot), v))
})
}
// MvpEQ applies the EQ predicate on the "mvp" field.
func MvpEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldMvp), v))
})
}
// MvpNEQ applies the NEQ predicate on the "mvp" field.
func MvpNEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldMvp), v))
})
}
// MvpIn applies the In predicate on the "mvp" field.
func MvpIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldMvp), v...))
})
}
// MvpNotIn applies the NotIn predicate on the "mvp" field.
func MvpNotIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldMvp), v...))
})
}
// MvpGT applies the GT predicate on the "mvp" field.
func MvpGT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldMvp), v))
})
}
// MvpGTE applies the GTE predicate on the "mvp" field.
func MvpGTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldMvp), v))
})
}
// MvpLT applies the LT predicate on the "mvp" field.
func MvpLT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldMvp), v))
})
}
// MvpLTE applies the LTE predicate on the "mvp" field.
func MvpLTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldMvp), v))
})
}
// ScoreEQ applies the EQ predicate on the "score" field.
func ScoreEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.EQ(s.C(FieldScore), v))
})
}
// ScoreNEQ applies the NEQ predicate on the "score" field.
func ScoreNEQ(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.NEQ(s.C(FieldScore), v))
})
}
// ScoreIn applies the In predicate on the "score" field.
func ScoreIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.In(s.C(FieldScore), v...))
})
}
// ScoreNotIn applies the NotIn predicate on the "score" field.
func ScoreNotIn(vs ...int) predicate.Stats {
v := make([]interface{}, len(vs))
for i := range v {
v[i] = vs[i]
}
return predicate.Stats(func(s *sql.Selector) {
// if not arguments were provided, append the FALSE constants,
// since we can't apply "IN ()". This will make this predicate falsy.
if len(v) == 0 {
s.Where(sql.False())
return
}
s.Where(sql.NotIn(s.C(FieldScore), v...))
})
}
// ScoreGT applies the GT predicate on the "score" field.
func ScoreGT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GT(s.C(FieldScore), v))
})
}
// ScoreGTE applies the GTE predicate on the "score" field.
func ScoreGTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.GTE(s.C(FieldScore), v))
})
}
// ScoreLT applies the LT predicate on the "score" field.
func ScoreLT(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LT(s.C(FieldScore), v))
})
}
// ScoreLTE applies the LTE predicate on the "score" field.
func ScoreLTE(v int) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.LTE(s.C(FieldScore), v))
})
}
// ExtendedIsNil applies the IsNil predicate on the "extended" field.
func ExtendedIsNil() predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.IsNull(s.C(FieldExtended)))
})
}
// ExtendedNotNil applies the NotNil predicate on the "extended" field.
func ExtendedNotNil() predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s.Where(sql.NotNull(s.C(FieldExtended)))
})
}
// HasMatches applies the HasEdge predicate on the "matches" edge.
func HasMatches() predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(MatchesTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, MatchesTable, MatchesColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasMatchesWith applies the HasEdge predicate on the "matches" edge with a given conditions (other predicates).
func HasMatchesWith(preds ...predicate.Match) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(MatchesInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, MatchesTable, MatchesColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// HasPlayers applies the HasEdge predicate on the "players" edge.
func HasPlayers() predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(PlayersTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, PlayersTable, PlayersColumn),
)
sqlgraph.HasNeighbors(s, step)
})
}
// HasPlayersWith applies the HasEdge predicate on the "players" edge with a given conditions (other predicates).
func HasPlayersWith(preds ...predicate.Player) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
step := sqlgraph.NewStep(
sqlgraph.From(Table, FieldID),
sqlgraph.To(PlayersInverseTable, FieldID),
sqlgraph.Edge(sqlgraph.M2O, true, PlayersTable, PlayersColumn),
)
sqlgraph.HasNeighborsWith(s, step, func(s *sql.Selector) {
for _, p := range preds {
p(s)
}
})
})
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Stats) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for _, p := range predicates {
p(s1)
}
s.Where(s1.P())
})
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Stats) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
s1 := s.Clone().SetP(nil)
for i, p := range predicates {
if i > 0 {
s1.Or()
}
p(s1)
}
s.Where(s1.P())
})
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Stats) predicate.Stats {
return predicate.Stats(func(s *sql.Selector) {
p(s.Not())
})
}

518
ent/stats_create.go Normal file
View File

@ -0,0 +1,518 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"csgowtfd/ent/match"
"csgowtfd/ent/player"
"csgowtfd/ent/stats"
"errors"
"fmt"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// StatsCreate is the builder for creating a Stats entity.
type StatsCreate struct {
config
mutation *StatsMutation
hooks []Hook
}
// SetTeamID sets the "team_id" field.
func (sc *StatsCreate) SetTeamID(i int) *StatsCreate {
sc.mutation.SetTeamID(i)
return sc
}
// SetKills sets the "kills" field.
func (sc *StatsCreate) SetKills(i int) *StatsCreate {
sc.mutation.SetKills(i)
return sc
}
// SetDeaths sets the "deaths" field.
func (sc *StatsCreate) SetDeaths(i int) *StatsCreate {
sc.mutation.SetDeaths(i)
return sc
}
// SetAssists sets the "assists" field.
func (sc *StatsCreate) SetAssists(i int) *StatsCreate {
sc.mutation.SetAssists(i)
return sc
}
// SetHeadshot sets the "headshot" field.
func (sc *StatsCreate) SetHeadshot(i int) *StatsCreate {
sc.mutation.SetHeadshot(i)
return sc
}
// SetMvp sets the "mvp" field.
func (sc *StatsCreate) SetMvp(i int) *StatsCreate {
sc.mutation.SetMvp(i)
return sc
}
// SetScore sets the "score" field.
func (sc *StatsCreate) SetScore(i int) *StatsCreate {
sc.mutation.SetScore(i)
return sc
}
// SetExtended sets the "extended" field.
func (sc *StatsCreate) SetExtended(skkgaaaallllg struct {
MultiKills struct {
Duo int "json:\"duo,omitempty\""
Triple int "json:\"triple,omitempty\""
Quad int "json:\"quad,omitempty\""
Pent int "json:\"pent,omitempty\""
} "json:\"multi_kills,omitempty\""
Dmg struct {
Enemy int "json:\"enemy,omitempty\""
Team int "json:\"team,omitempty\""
UD struct {
HE int "json:\"he,omitempty\""
Flames int "json:\"flames,omitempty\""
Flash int "json:\"flash,omitempty\""
Decoy int "json:\"decoy,omitempty\""
Smoke int "json:\"smoke,omitempty\""
} "json:\"ud,omitempty\""
HitGroup struct {
Head int "json:\"head,omitempty\""
Chest int "json:\"chest,omitempty\""
Stomach int "json:\"stomach,omitempty\""
LeftArm int "json:\"left_arm,omitempty\""
RightArm int "json:\"right_arm,omitempty\""
LeftLeg int "json:\"left_leg,omitempty\""
RightLeg int "json:\"right_leg,omitempty\""
Gear int "json:\"gear,omitempty\""
} "json:\"hit_group,omitempty\""
} "json:\"dmg,omitempty\""
Crosshair string "json:\"crosshair,omitempty\""
Color int "json:\"color,omitempty\""
KAST int "json:\"kast,omitempty\""
Rank struct {
Old int "json:\"old,omitempty\""
New int "json:\"new,omitempty\""
} "json:\"rank,omitempty\""
Flash struct {
Duration struct {
Self float32 "json:\"self,omitempty\""
Team float32 "json:\"team,omitempty\""
Enemy float32 "json:\"enemy,omitempty\""
} "json:\"duration,omitempty\""
Total struct {
Team int "json:\"team,omitempty\""
Enemy int "json:\"enemy,omitempty\""
Self int "json:\"self,omitempty\""
} "json:\"total,omitempty\""
} "json:\"flash,omitempty\""
}) *StatsCreate {
sc.mutation.SetExtended(skkgaaaallllg)
return sc
}
// SetNillableExtended sets the "extended" field if the given value is not nil.
func (sc *StatsCreate) SetNillableExtended(skkgaaaallllg *struct {
MultiKills struct {
Duo int "json:\"duo,omitempty\""
Triple int "json:\"triple,omitempty\""
Quad int "json:\"quad,omitempty\""
Pent int "json:\"pent,omitempty\""
} "json:\"multi_kills,omitempty\""
Dmg struct {
Enemy int "json:\"enemy,omitempty\""
Team int "json:\"team,omitempty\""
UD struct {
HE int "json:\"he,omitempty\""
Flames int "json:\"flames,omitempty\""
Flash int "json:\"flash,omitempty\""
Decoy int "json:\"decoy,omitempty\""
Smoke int "json:\"smoke,omitempty\""
} "json:\"ud,omitempty\""
HitGroup struct {
Head int "json:\"head,omitempty\""
Chest int "json:\"chest,omitempty\""
Stomach int "json:\"stomach,omitempty\""
LeftArm int "json:\"left_arm,omitempty\""
RightArm int "json:\"right_arm,omitempty\""
LeftLeg int "json:\"left_leg,omitempty\""
RightLeg int "json:\"right_leg,omitempty\""
Gear int "json:\"gear,omitempty\""
} "json:\"hit_group,omitempty\""
} "json:\"dmg,omitempty\""
Crosshair string "json:\"crosshair,omitempty\""
Color int "json:\"color,omitempty\""
KAST int "json:\"kast,omitempty\""
Rank struct {
Old int "json:\"old,omitempty\""
New int "json:\"new,omitempty\""
} "json:\"rank,omitempty\""
Flash struct {
Duration struct {
Self float32 "json:\"self,omitempty\""
Team float32 "json:\"team,omitempty\""
Enemy float32 "json:\"enemy,omitempty\""
} "json:\"duration,omitempty\""
Total struct {
Team int "json:\"team,omitempty\""
Enemy int "json:\"enemy,omitempty\""
Self int "json:\"self,omitempty\""
} "json:\"total,omitempty\""
} "json:\"flash,omitempty\""
}) *StatsCreate {
if skkgaaaallllg != nil {
sc.SetExtended(*skkgaaaallllg)
}
return sc
}
// SetMatchesID sets the "matches" edge to the Match entity by ID.
func (sc *StatsCreate) SetMatchesID(id int) *StatsCreate {
sc.mutation.SetMatchesID(id)
return sc
}
// SetNillableMatchesID sets the "matches" edge to the Match entity by ID if the given value is not nil.
func (sc *StatsCreate) SetNillableMatchesID(id *int) *StatsCreate {
if id != nil {
sc = sc.SetMatchesID(*id)
}
return sc
}
// SetMatches sets the "matches" edge to the Match entity.
func (sc *StatsCreate) SetMatches(m *Match) *StatsCreate {
return sc.SetMatchesID(m.ID)
}
// SetPlayersID sets the "players" edge to the Player entity by ID.
func (sc *StatsCreate) SetPlayersID(id int) *StatsCreate {
sc.mutation.SetPlayersID(id)
return sc
}
// SetNillablePlayersID sets the "players" edge to the Player entity by ID if the given value is not nil.
func (sc *StatsCreate) SetNillablePlayersID(id *int) *StatsCreate {
if id != nil {
sc = sc.SetPlayersID(*id)
}
return sc
}
// SetPlayers sets the "players" edge to the Player entity.
func (sc *StatsCreate) SetPlayers(p *Player) *StatsCreate {
return sc.SetPlayersID(p.ID)
}
// Mutation returns the StatsMutation object of the builder.
func (sc *StatsCreate) Mutation() *StatsMutation {
return sc.mutation
}
// Save creates the Stats in the database.
func (sc *StatsCreate) Save(ctx context.Context) (*Stats, error) {
var (
err error
node *Stats
)
if len(sc.hooks) == 0 {
if err = sc.check(); err != nil {
return nil, err
}
node, err = sc.sqlSave(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*StatsMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err = sc.check(); err != nil {
return nil, err
}
sc.mutation = mutation
if node, err = sc.sqlSave(ctx); err != nil {
return nil, err
}
mutation.id = &node.ID
mutation.done = true
return node, err
})
for i := len(sc.hooks) - 1; i >= 0; i-- {
if sc.hooks[i] == nil {
return nil, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = sc.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, sc.mutation); err != nil {
return nil, err
}
}
return node, err
}
// SaveX calls Save and panics if Save returns an error.
func (sc *StatsCreate) SaveX(ctx context.Context) *Stats {
v, err := sc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (sc *StatsCreate) Exec(ctx context.Context) error {
_, err := sc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (sc *StatsCreate) ExecX(ctx context.Context) {
if err := sc.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (sc *StatsCreate) check() error {
if _, ok := sc.mutation.TeamID(); !ok {
return &ValidationError{Name: "team_id", err: errors.New(`ent: missing required field "team_id"`)}
}
if _, ok := sc.mutation.Kills(); !ok {
return &ValidationError{Name: "kills", err: errors.New(`ent: missing required field "kills"`)}
}
if _, ok := sc.mutation.Deaths(); !ok {
return &ValidationError{Name: "deaths", err: errors.New(`ent: missing required field "deaths"`)}
}
if _, ok := sc.mutation.Assists(); !ok {
return &ValidationError{Name: "assists", err: errors.New(`ent: missing required field "assists"`)}
}
if _, ok := sc.mutation.Headshot(); !ok {
return &ValidationError{Name: "headshot", err: errors.New(`ent: missing required field "headshot"`)}
}
if _, ok := sc.mutation.Mvp(); !ok {
return &ValidationError{Name: "mvp", err: errors.New(`ent: missing required field "mvp"`)}
}
if _, ok := sc.mutation.Score(); !ok {
return &ValidationError{Name: "score", err: errors.New(`ent: missing required field "score"`)}
}
return nil
}
func (sc *StatsCreate) sqlSave(ctx context.Context) (*Stats, error) {
_node, _spec := sc.createSpec()
if err := sqlgraph.CreateNode(ctx, sc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
return _node, nil
}
func (sc *StatsCreate) createSpec() (*Stats, *sqlgraph.CreateSpec) {
var (
_node = &Stats{config: sc.config}
_spec = &sqlgraph.CreateSpec{
Table: stats.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: stats.FieldID,
},
}
)
if value, ok := sc.mutation.TeamID(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: stats.FieldTeamID,
})
_node.TeamID = value
}
if value, ok := sc.mutation.Kills(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: stats.FieldKills,
})
_node.Kills = value
}
if value, ok := sc.mutation.Deaths(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: stats.FieldDeaths,
})
_node.Deaths = value
}
if value, ok := sc.mutation.Assists(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: stats.FieldAssists,
})
_node.Assists = value
}
if value, ok := sc.mutation.Headshot(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: stats.FieldHeadshot,
})
_node.Headshot = value
}
if value, ok := sc.mutation.Mvp(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: stats.FieldMvp,
})
_node.Mvp = value
}
if value, ok := sc.mutation.Score(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeInt,
Value: value,
Column: stats.FieldScore,
})
_node.Score = value
}
if value, ok := sc.mutation.Extended(); ok {
_spec.Fields = append(_spec.Fields, &sqlgraph.FieldSpec{
Type: field.TypeJSON,
Value: value,
Column: stats.FieldExtended,
})
_node.Extended = value
}
if nodes := sc.mutation.MatchesIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: stats.MatchesTable,
Columns: []string{stats.MatchesColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: match.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.match_stats = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
if nodes := sc.mutation.PlayersIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.M2O,
Inverse: true,
Table: stats.PlayersTable,
Columns: []string{stats.PlayersColumn},
Bidi: false,
Target: &sqlgraph.EdgeTarget{
IDSpec: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: player.FieldID,
},
},
}
for _, k := range nodes {
edge.Target.Nodes = append(edge.Target.Nodes, k)
}
_node.player_stats = &nodes[0]
_spec.Edges = append(_spec.Edges, edge)
}
return _node, _spec
}
// StatsCreateBulk is the builder for creating many Stats entities in bulk.
type StatsCreateBulk struct {
config
builders []*StatsCreate
}
// Save creates the Stats entities in the database.
func (scb *StatsCreateBulk) Save(ctx context.Context) ([]*Stats, error) {
specs := make([]*sqlgraph.CreateSpec, len(scb.builders))
nodes := make([]*Stats, len(scb.builders))
mutators := make([]Mutator, len(scb.builders))
for i := range scb.builders {
func(i int, root context.Context) {
builder := scb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*StatsMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
nodes[i], specs[i] = builder.createSpec()
var err error
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, scb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, scb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{err.Error(), err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
mutation.done = true
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, scb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (scb *StatsCreateBulk) SaveX(ctx context.Context) []*Stats {
v, err := scb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (scb *StatsCreateBulk) Exec(ctx context.Context) error {
_, err := scb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (scb *StatsCreateBulk) ExecX(ctx context.Context) {
if err := scb.Exec(ctx); err != nil {
panic(err)
}
}

111
ent/stats_delete.go Normal file
View File

@ -0,0 +1,111 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"csgowtfd/ent/predicate"
"csgowtfd/ent/stats"
"fmt"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// StatsDelete is the builder for deleting a Stats entity.
type StatsDelete struct {
config
hooks []Hook
mutation *StatsMutation
}
// Where appends a list predicates to the StatsDelete builder.
func (sd *StatsDelete) Where(ps ...predicate.Stats) *StatsDelete {
sd.mutation.Where(ps...)
return sd
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (sd *StatsDelete) Exec(ctx context.Context) (int, error) {
var (
err error
affected int
)
if len(sd.hooks) == 0 {
affected, err = sd.sqlExec(ctx)
} else {
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*StatsMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
sd.mutation = mutation
affected, err = sd.sqlExec(ctx)
mutation.done = true
return affected, err
})
for i := len(sd.hooks) - 1; i >= 0; i-- {
if sd.hooks[i] == nil {
return 0, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = sd.hooks[i](mut)
}
if _, err := mut.Mutate(ctx, sd.mutation); err != nil {
return 0, err
}
}
return affected, err
}
// ExecX is like Exec, but panics if an error occurs.
func (sd *StatsDelete) ExecX(ctx context.Context) int {
n, err := sd.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (sd *StatsDelete) sqlExec(ctx context.Context) (int, error) {
_spec := &sqlgraph.DeleteSpec{
Node: &sqlgraph.NodeSpec{
Table: stats.Table,
ID: &sqlgraph.FieldSpec{
Type: field.TypeInt,
Column: stats.FieldID,
},
},
}
if ps := sd.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return sqlgraph.DeleteNodes(ctx, sd.driver, _spec)
}
// StatsDeleteOne is the builder for deleting a single Stats entity.
type StatsDeleteOne struct {
sd *StatsDelete
}
// Exec executes the deletion query.
func (sdo *StatsDeleteOne) Exec(ctx context.Context) error {
n, err := sdo.sd.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{stats.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (sdo *StatsDeleteOne) ExecX(ctx context.Context) {
sdo.sd.ExecX(ctx)
}

1060
ent/stats_query.go Normal file

File diff suppressed because it is too large Load Diff

1112
ent/stats_update.go Normal file

File diff suppressed because it is too large Load Diff

216
ent/tx.go Normal file
View File

@ -0,0 +1,216 @@
// Code generated by entc, DO NOT EDIT.
package ent
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Match is the client for interacting with the Match builders.
Match *MatchClient
// Player is the client for interacting with the Player builders.
Player *PlayerClient
// Stats is the client for interacting with the Stats builders.
Stats *StatsClient
// lazily loaded.
client *Client
clientOnce sync.Once
// completion callbacks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Committer method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
tx.mu.Lock()
hooks := append([]CommitHook(nil), tx.onCommit...)
tx.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
tx.mu.Lock()
defer tx.mu.Unlock()
tx.onCommit = append(tx.onCommit, f)
}
type (
// Rollbacker is the interface that wraps the Rollbacker method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
tx.mu.Lock()
hooks := append([]RollbackHook(nil), tx.onRollback...)
tx.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
tx.mu.Lock()
defer tx.mu.Unlock()
tx.onRollback = append(tx.onRollback, f)
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.Match = NewMatchClient(tx.config)
tx.Player = NewPlayerClient(tx.config)
tx.Stats = NewStatsClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Match.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v interface{}) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v interface{}) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)

33
go.mod Normal file
View File

@ -0,0 +1,33 @@
module csgowtfd
go 1.17
require (
entgo.io/ent v0.9.1
github.com/Philipp15b/go-steamapi v0.0.0-20210114153316-ec4fdd23b4c1
github.com/an0nfunc/go-steam/v3 v3.0.1
github.com/gorilla/handlers v1.5.1
github.com/gorilla/mux v1.8.0
github.com/markus-wa/demoinfocs-golang/v2 v2.10.1
github.com/mattn/go-sqlite3 v1.14.8
github.com/sirupsen/logrus v1.2.0
go.uber.org/ratelimit v0.2.0
google.golang.org/protobuf v1.27.1
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c
)
require (
github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 // indirect
github.com/felixge/httpsnoop v1.0.1 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/konsorten/go-windows-terminal-sequences v1.0.1 // indirect
github.com/markus-wa/go-unassert v0.1.2 // indirect
github.com/markus-wa/gobitread v0.2.3 // indirect
github.com/markus-wa/godispatch v1.4.1 // indirect
github.com/markus-wa/quickhull-go/v2 v2.1.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 // indirect
golang.org/x/sys v0.0.0-20210510120138-977fb7262007 // indirect
)

438
go.sum Normal file
View File

@ -0,0 +1,438 @@
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
cloud.google.com/go v0.38.0/go.mod h1:990N+gfupTy94rShfmMCWGDn0LpTmnzTp2qbd1dvSRU=
cloud.google.com/go v0.44.1/go.mod h1:iSa0KzasP4Uvy3f1mN/7PiObzGgflwredwwASm/v6AU=
cloud.google.com/go v0.44.2/go.mod h1:60680Gw3Yr4ikxnPRS/oxxkBccT6SA1yMk63TGekxKY=
cloud.google.com/go v0.45.1/go.mod h1:RpBamKRgapWJb87xiFSdk4g1CME7QZg3uwTez+TSTjc=
cloud.google.com/go v0.46.3/go.mod h1:a6bKKbmY7er1mI7TEI4lsAkts/mkhTSZK8w33B4RAg0=
cloud.google.com/go/bigquery v1.0.1/go.mod h1:i/xbL2UlR5RvWAURpBYZTtm/cXjCha9lbfbpx4poX+o=
cloud.google.com/go/datastore v1.0.0/go.mod h1:LXYbyblFSglQ5pkeyhO+Qmw7ukd3C+pD7TKLgZqpHYE=
cloud.google.com/go/firestore v1.1.0/go.mod h1:ulACoGHTpvq5r8rxGJ4ddJZBZqakUQqClKRT5SZwBmk=
cloud.google.com/go/pubsub v1.0.1/go.mod h1:R0Gpsv3s54REJCy4fxDixWD93lHJMoZTyQ2kNxGRt3I=
cloud.google.com/go/storage v1.0.0/go.mod h1:IhtSnM/ZTZV8YYJWCY8RULGVqBDmpoyjwiyrjsg+URw=
dmitri.shuralyov.com/gpu/mtl v0.0.0-20190408044501-666a987793e9/go.mod h1:H6x//7gZCb22OMCxBHrMx7a5I7Hp++hsVxbQ4BYO7hU=
entgo.io/ent v0.9.1 h1:IG8andyeD79GG24U8Q+1Y45hQXj6gY5evSBcva5gtBk=
entgo.io/ent v0.9.1/go.mod h1:6NUeTfUN5mp5YN+5tgoH1SlakSvYPTBOYotSOvaI4ak=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/DATA-DOG/go-sqlmock v1.5.0 h1:Shsta01QNfFxHCfpW6YH2STWB0MudeXXEWMr20OEh60=
github.com/DATA-DOG/go-sqlmock v1.5.0/go.mod h1:f/Ixk793poVmq4qj/V1dPUg2JEAKC73Q5eFN3EC/SaM=
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
github.com/Philipp15b/go-steamapi v0.0.0-20210114153316-ec4fdd23b4c1 h1:PD13eMe9XAgPQ0SYWyirqwyOJG90TlEWApCw8A699l0=
github.com/Philipp15b/go-steamapi v0.0.0-20210114153316-ec4fdd23b4c1/go.mod h1:eQR7Xf64m2ALDAQE7Nr9ylFZhav1izvF3zzysKPhb0I=
github.com/alecthomas/template v0.0.0-20160405071501-a0175ee3bccc/go.mod h1:LOuyumcjzFXgccqObfd/Ljyb9UuFJ6TxHnclSeseNhc=
github.com/alecthomas/units v0.0.0-20151022065526-2efee857e7cf/go.mod h1:ybxpYRFXyAe+OPACYpWeL0wqObRcbAqCMya13uyzqw0=
github.com/an0nfunc/go-steam/v3 v3.0.1 h1:Sc/B8R3454Q3f8r/LyKX7iTK7Saiw8EiQTKyGVwn6D0=
github.com/an0nfunc/go-steam/v3 v3.0.1/go.mod h1:HnlYcTVnAJbSlyzC5lxft9jQOu2mjTw8LHfN/bYuDEs=
github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129 h1:MzBOUgng9orim59UnfUTLRjMpd09C5uEVQ6RPGeCaVI=
github.com/andres-erbsen/clock v0.0.0-20160526145045-9e14626cd129/go.mod h1:rFgpPQZYZ8vdbc+48xibu8ALc3yeyd64IhHS+PU6Yyg=
github.com/armon/circbuf v0.0.0-20150827004946-bbbad097214e/go.mod h1:3U/XgcO3hCbHZ8TKRvWD2dDTCfh9M9ya+I9JpbB7O8o=
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da/go.mod h1:Q73ZrmVTwzkszR9V5SSuryQ31EELlFMUz1kKyl939pY=
github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8=
github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q=
github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8=
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc=
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
github.com/coreos/etcd v3.3.13+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
github.com/coreos/go-semver v0.3.0/go.mod h1:nnelYz7RCh+5ahJtPPxZlU+153eP4D4r3EedlOD2RNk=
github.com/coreos/go-systemd v0.0.0-20190321100706-95778dfbb74e/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
github.com/coreos/pkg v0.0.0-20180928190104-399ea9e2e55f/go.mod h1:E3G3o1h8I7cfcXa63jLwjI0eiQQMgzzUDFVpN/nH/eA=
github.com/cpuguy83/go-md2man/v2 v2.0.0/go.mod h1:maD7wRr/U5Z6m/iR4s+kqSMx2CaBsrgA7czyZG/E6dU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgrijalva/jwt-go v3.2.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
github.com/dgryski/go-sip13 v0.0.0-20181026042036-e10d5fee7954/go.mod h1:vAd38F8PWV+bWy6jNmig1y/TA+kYO4g3RSRF0IAv0no=
github.com/dustin/go-heatmap v0.0.0-20180603032536-b89dbd73785a/go.mod h1:VBmwC4U3p2SMEKr+/m5j0eby7rmUtSoA5TGLwe6P+3A=
github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4=
github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98=
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
github.com/felixge/httpsnoop v1.0.1 h1:lvB5Jl89CsZtGIWuTcDM1E/vkVs49/Ml7JJe07l8SPQ=
github.com/felixge/httpsnoop v1.0.1/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04=
github.com/go-bindata/go-bindata v1.0.1-0.20190711162640-ee3c2418e368/go.mod h1:7xCgX1lzlrXPHkfvn3EhumqHkmSlzt8at9q7v0ax19c=
github.com/go-gl/gl v0.0.0-20180407155706-68e253793080/go.mod h1:482civXOzJJCPzJ4ZOX/pwvXBWSnzD4OKMdH4ClKGbk=
github.com/go-gl/glfw v0.0.0-20180426074136-46a8d530c326/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as=
github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE=
github.com/go-logfmt/logfmt v0.4.0/go.mod h1:3RMwSq7FuexP4Kalkev3ejPJsZTpXXBr9+V4qmtdjCk=
github.com/go-openapi/inflect v0.19.0/go.mod h1:lHpZVlpIQqLyKwJ4N+YSc9hchQy/i12fJykb83CRBH4=
github.com/go-sql-driver/mysql v1.5.1-0.20200311113236-681ffa848bae/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg=
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
github.com/gogo/protobuf v1.1.1/go.mod h1:r8qH/GZQm5c6nD/R0oafs1akxWv10x8SbQlK7atdtwQ=
github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zVXpSg4=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
github.com/golang/geo v0.0.0-20180826223333-635502111454/go.mod h1:vgWZ7cu0fq0KY3PpEHsocXOWJpRtkcbKemU4IUw0M60=
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551 h1:gtexQ/VGyN+VVFRXSFiguSNcXmS6rkKT+X7FdIrTtfo=
github.com/golang/geo v0.0.0-20210211234256-740aa86cb551/go.mod h1:QZ0nwyI2jOfgRAoBvP+ab5aRr7c9x7lhGEJrKvBwjWI=
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
github.com/golang/groupcache v0.0.0-20190129154638-5b532d6fd5ef/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.2.0/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
github.com/golang/mock v1.3.1/go.mod h1:sBzyDLLjw3U8JLTeZvSv8jJB+tU5PVekmnlKIyFUx0Y=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8=
github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/google/btree v0.0.0-20180813153112-4030bb1f1f0c/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/martian v2.1.0+incompatible/go.mod h1:9I4somxYTbIHy5NJKHRl3wXiIaQGbYVAs8BPL6v8lEs=
github.com/google/pprof v0.0.0-20181206194817-3ea8567a2e57/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/pprof v0.0.0-20190515194954-54271f7e092f/go.mod h1:zfwlbNMJ+OItoe0UupaVj+oy1omPYYDuagoSzA8v9mc=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/googleapis/gax-go/v2 v2.0.4/go.mod h1:0Wqv26UfaUD9n4G6kQubkQ+KchISgw+vpHVxEJEs9eg=
github.com/googleapis/gax-go/v2 v2.0.5/go.mod h1:DWXyrwAJ9X0FpwwEdw+IPEYBICEFu5mhpdKc/us6bOk=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gorilla/handlers v1.5.1 h1:9lRY6j8DEeeBT10CvO9hGW0gmky0BprnvDI5vfhUHH4=
github.com/gorilla/handlers v1.5.1/go.mod h1:t8XrUpc4KVXb7HGyJ4/cEnwQiaxrX/hz1Zv/4g96P1Q=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
github.com/grpc-ecosystem/go-grpc-middleware v1.0.0/go.mod h1:FiyG127CGDf3tlThmgyCl78X/SZQqEOJBCDaAfeWzPs=
github.com/grpc-ecosystem/go-grpc-prometheus v1.2.0/go.mod h1:8NvIoxWQoOIhqOTXgfV/d3M/q6VIi02HzZEHgUlZvzk=
github.com/grpc-ecosystem/grpc-gateway v1.9.0/go.mod h1:vNeuVxBJEsws4ogUvrchl83t/GYV9WGTSLVdBhOQFDY=
github.com/hashicorp/consul/api v1.1.0/go.mod h1:VmuI/Lkw1nC05EYQWNKwWGbkg+FbDBtguAZLlVdkD9Q=
github.com/hashicorp/consul/sdk v0.1.1/go.mod h1:VKf9jXwCTEY1QZP2MOLRhb5i/I/ssyNV1vwHyQBF0x8=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80=
github.com/hashicorp/go-immutable-radix v1.0.0/go.mod h1:0y9vanUI8NX6FsYoO3zeMjhV/C5i9g4Q3DwcSNZ4P60=
github.com/hashicorp/go-msgpack v0.5.3/go.mod h1:ahLV/dePpqEmjfWmKiqvPkv/twdG7iPBM1vqhUKIvfM=
github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk=
github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU=
github.com/hashicorp/go-sockaddr v1.0.0/go.mod h1:7Xibr9yA9JjQq1JpNB2Vw7kxv8xerXegt+ozgdvDeDU=
github.com/hashicorp/go-syslog v1.0.0/go.mod h1:qPfqrKkXGihmCqbJM2mZgkZGvKG1dFdvsLplgctolz4=
github.com/hashicorp/go-uuid v1.0.0/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go-uuid v1.0.1/go.mod h1:6SBZvOh/SIDV7/2o3Jml5SYk/TvGqwFJ/bN7x4byOro=
github.com/hashicorp/go.net v0.0.1/go.mod h1:hjKkEWcCURg++eb33jQU7oqQcI9XDCnUzHA0oac0k90=
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/golang-lru v0.5.1/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO+LraFDTW64=
github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ=
github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I=
github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4=
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
github.com/json-iterator/go v1.1.6/go.mod h1:+SdeFBvtyEkXs7REEP0seUULqWtbJapLOCVDaaPEHmU=
github.com/json-iterator/go v1.1.10/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4=
github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/julienschmidt/httprouter v1.2.0/go.mod h1:SYymIcj16QtmaHHD7aYtjjsJG7VTCxuUUipMqKk8s4w=
github.com/jung-kurt/gofpdf v1.0.0/go.mod h1:7Id9E/uU8ce6rXgefFLlgrJj/GYY22cpxn+r32jIOes=
github.com/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
github.com/kisielk/errcheck v1.2.0/go.mod h1:/BMXB+zMLi60iA8Vv6Ksmxu/1UDYcXs4uQLJ+jE2L00=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/konsorten/go-windows-terminal-sequences v1.0.1 h1:mweAR1A6xJ3oS2pRaGiHgQ4OO8tzTaLawm8vnODuwDk=
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/lib/pq v1.10.2/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
github.com/llgcode/draw2d v0.0.0-20200930101115-bfaf5d914d1e/go.mod h1:mVa0dA29Db2S4LVqDYLlsePDzRJLDfdhVZiI15uY0FA=
github.com/llgcode/ps v0.0.0-20150911083025-f1443b32eedb/go.mod h1:1l8ky+Ew27CMX29uG+a2hNOKpeNYEQjjtiALiBlFQbY=
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
github.com/markus-wa/demoinfocs-golang/v2 v2.10.1 h1:x/q/EMEoKsvnZA6vUjLD0fXSwxj+fG/j6212GiuIQRY=
github.com/markus-wa/demoinfocs-golang/v2 v2.10.1/go.mod h1:BPIElNIVtyVzzc2AD3w/yMbiHiaq91o6L873PdZJobo=
github.com/markus-wa/go-unassert v0.1.2 h1:uXWlMDa8JVtc4RgNq4XJIjyRejv9MOVuy/E0VECPxxo=
github.com/markus-wa/go-unassert v0.1.2/go.mod h1:XEvrxR+trvZeMDfXcZPvzqGo6eumEtdk5VjNRuvvzxQ=
github.com/markus-wa/gobitread v0.2.3 h1:COx7dtYQ7Q+77hgUmD+O4MvOcqG7y17RP3Z7BbjRvPs=
github.com/markus-wa/gobitread v0.2.3/go.mod h1:PcWXMH4gx7o2CKslbkFkLyJB/aHW7JVRG3MRZe3PINg=
github.com/markus-wa/godispatch v1.4.1 h1:Cdff5x33ShuX3sDmUbYWejk7tOuoHErFYMhUc2h7sLc=
github.com/markus-wa/godispatch v1.4.1/go.mod h1:tk8L0yzLO4oAcFwM2sABMge0HRDJMdE8E7xm4gK/+xM=
github.com/markus-wa/quickhull-go/v2 v2.1.0 h1:DA2pzEzH0k5CEnlUsouRqNdD+jzNFb4DBhrX4Hpa5So=
github.com/markus-wa/quickhull-go/v2 v2.1.0/go.mod h1:bOlBUpIzGSMMhHX0f9N8CQs0VZD4nnPeta0OocH7m4o=
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
github.com/mattn/go-sqlite3 v1.14.8 h1:gDp86IdQsN/xWjIEmr9MF6o9mpksUgh0fu+9ByFxzIU=
github.com/mattn/go-sqlite3 v1.14.8/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc=
github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eIhFbs2+BFgRtFPeD/KE+zxI=
github.com/mitchellh/gox v0.4.0/go.mod h1:Sd9lOJ0+aimLBi73mGofS1ycjY8lL3uZM3JPS42BGNg=
github.com/mitchellh/iochan v1.0.0/go.mod h1:JwYml1nuB7xOzsp52dPpHFffvOCDupsG0QubkSMEySY=
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
github.com/mitchellh/mapstructure v1.4.1/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/modern-go/reflect2 v1.0.1/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0=
github.com/mwitkow/go-conntrack v0.0.0-20161129095857-cc309e4a2223/go.mod h1:qRWi+5nqEBWmkhHvq77mSJWrCKwh8bxhgT7d/eI7P4U=
github.com/oklog/ulid v1.3.1/go.mod h1:CirwcVhetQ6Lv90oh/F+FBtV6XMibvdAFo93nm5qn4U=
github.com/olekukonko/tablewriter v0.0.5/go.mod h1:hPp6KlRPjbx+hW8ykQs1w3UBbZlj6HuIJcUGPhkA7kY=
github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI=
github.com/prometheus/client_golang v0.9.1/go.mod h1:7SWBe2y4D6OKWSNQJUaRYU/AaXPKyh/dDVn+NZz0KFw=
github.com/prometheus/client_golang v0.9.3/go.mod h1:/TN21ttK/J9q6uSwhBd54HahCDft0ttaMvbicHlPoso=
github.com/prometheus/client_model v0.0.0-20180712105110-5c3871d89910/go.mod h1:MbSGuTsp3dbXC40dX6PRTWyKYBIrTGTE9sqQNg2J8bo=
github.com/prometheus/client_model v0.0.0-20190129233127-fd36f4220a90/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/prometheus/common v0.0.0-20181113130724-41aa239b4cce/go.mod h1:daVV7qP5qjZbuso7PdcryaAu0sAZbrN9i7WWcTMWvro=
github.com/prometheus/common v0.4.0/go.mod h1:TNfzLD0ON7rHzMJeJkieUDPYmFC7Snx/y86RQel1bk4=
github.com/prometheus/procfs v0.0.0-20181005140218-185b4288413d/go.mod h1:c3At6R/oaqEKCNdg8wHV1ftS6bRYblBhIjjI8uT2IGk=
github.com/prometheus/procfs v0.0.0-20190507164030-5867b95ac084/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA=
github.com/prometheus/tsdb v0.7.1/go.mod h1:qhTCs0VvXwvX/y3TZrWD7rabWM+ijKTux40TwIPHuXU=
github.com/rogpeppe/fastuuid v0.0.0-20150106093220-6724a57986af/go.mod h1:XWv6SoW27p1b0cqNHllgS5HIMJraePCO15w5zCzIWYg=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
github.com/shurcooL/sanitized_anchor_name v1.0.0/go.mod h1:1NzhyTcUVG4SuEtjjoZeVRXNmyL/1OwPU0+IJeTBvfc=
github.com/sirupsen/logrus v1.2.0 h1:juTguoYk5qI21pwyTXY3B3Y5cOTH3ZUyZCg1v/mihuo=
github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPxbbu5VWo=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.4/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/soheilhy/cmux v0.1.4/go.mod h1:IM3LyeVVIOuxMH7sFAkER9+bJ4dT7Ms6E4xg4kGIyLM=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cobra v1.1.3/go.mod h1:pGADOWyqRD/YMrPZigI/zbliZ2wVD/23d+is3pSWzOo=
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.7.0/go.mod h1:8WkrPz2fc9jxqZNCJI/76HCieCp4Q8HaLFoCha5qpdg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.2.0 h1:Hbg2NidpLE8veEBkEZTL3CvlkUIVzuU9jDplZO54c48=
github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
github.com/tmc/grpc-websocket-proxy v0.0.0-20190109142713-0ad062ec5ee5/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
go.opencensus.io v0.21.0/go.mod h1:mSImk1erAIZhrmZN+AvHh14ztQfjbGwt4TtuofqLduU=
go.opencensus.io v0.22.0/go.mod h1:+kGneAE2xo2IficOXnaByMWTGM9T73dGwxeWcUqIpI8=
go.opencensus.io v0.23.0/go.mod h1:XItmlyltB5F7CS4xOC1DcqMoFqwtC6OG2xF7mCv7P7E=
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
go.uber.org/atomic v1.7.0 h1:ADUqmZGgLDDfbSL9ZmPxKTybcoEYHgpYfELNoN+7hsw=
go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
go.uber.org/ratelimit v0.2.0 h1:UQE2Bgi7p2B85uP5dC2bbRtig0C+OeNRnNEafLjsLPA=
go.uber.org/ratelimit v0.2.0/go.mod h1:YYBV4e4naJvhpitQrWJu1vCpgB7CboMe0qhltKt6mUg=
go.uber.org/zap v1.10.0/go.mod h1:vwi/ZaCAaUcBkycHslxD9B2zi4UTXhF60s6SWpuDF0Q=
golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190605123033-f99c8df09eb5/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9 h1:psW17arqaxU48Z5kZ0CQnkZWQJsqcURM6tKiBApRjXI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
golang.org/x/exp v0.0.0-20190829153037-c13cbed26979/go.mod h1:86+5VVa7VpoJ4kLfm080zCjGlMRFzhUhsZKEZO7MGek=
golang.org/x/exp v0.0.0-20191030013958-a1ab85dbe136/go.mod h1:JXzH8nQsPlswgeRAPE3MuO9GYsAcnJvJ4vnMwN/5qkY=
golang.org/x/image v0.0.0-20180708004352-c73c2afc3b81/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
golang.org/x/lint v0.0.0-20190301231843-5614ed5bae6f/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190409202823-959b441ac422/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190909230951-414d861bb4ac/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/lint v0.0.0-20190930215403-16217165b5de/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20190719004257-d2bd2a29d028/go.mod h1:E/iHnbuqvinMTCcRqshq8CkpyQDoeVncDDYHnLhea+o=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181114220301-adae6a3d119a/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20181220203305-927f97764cc3/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190501004415-9ce7a6920f09/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190503192946-f4e77d36d62c/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190227155943-e225da77a7e6/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181107165924-66b7b1311ac8/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20181116152217-5ac8a444bdc5/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190502145724-3ef323f4f1fd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190507160741-ecd444e8653b/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190606165138-5da285871e9c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190624142023-c5567b49c5d0/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007 h1:gG67DSER+11cZvqIMb8S8bt0vZtiN6xWYARwirrOSfE=
golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20181030221726-6c7e314b6563/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY=
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190312170243-e65039ee4138/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190425150028-36563e24a262/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190506145303-2d16b83fe98c/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q=
golang.org/x/tools v0.0.0-20190606124116-d0a3d012864b/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190628153133-6cdbf07be9d0/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
golang.org/x/tools v0.0.0-20190816200558-6889da9d5479/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20190911174233-4f2ddba30aff/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191012152004-8de300cfc20a/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191112195655-aa38f8e97acc/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.1.5/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/api v0.4.0/go.mod h1:8k5glujaEP+g9n7WNsDg8QP6cUVNI86fCNMcbazEtwE=
google.golang.org/api v0.7.0/go.mod h1:WtwebWUNSVBH/HAw79HIFXZNqEvBhG+Ra+ax0hx3E3M=
google.golang.org/api v0.8.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.9.0/go.mod h1:o4eAsZoiT+ibD93RtjEohWalFOjRDx6CVaqeizhEnKg=
google.golang.org/api v0.13.0/go.mod h1:iLdEw5Ide6rF15KTC1Kkl0iskquN2gFfn9o9XIsbkAI=
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.5.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
google.golang.org/appengine v1.6.1/go.mod h1:i06prIuMbXzDqacNJfV5OdTW448YApPu5ww/cMBSeb0=
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
google.golang.org/genproto v0.0.0-20190307195333-5fe7a883aa19/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190418145605-e7d98fc518a7/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190425155659-357c62f0e4bb/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190502173448-54afdca5d873/go.mod h1:VzzqZJRnGkLBvHegQrXjBqPurQTc5/KpmUdxsrq26oE=
google.golang.org/genproto v0.0.0-20190801165951-fa694d86fc64/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc=
google.golang.org/genproto v0.0.0-20190911173649-1774047e7e51/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8=
google.golang.org/genproto v0.0.0-20191108220845-16a3f7862a1a/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc=
google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg=
google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY=
google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk=
google.golang.org/grpc v1.33.2/go.mod h1:JMHMWHQWaTccqQQlmk3MJZS+GWXOdAesneDmEnv2fbc=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ=
google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/alecthomas/kingpin.v2 v2.2.6/go.mod h1:FMv+mEhP44yOT+4EoQTLFTRgOQ1FBLkstjWtayDeSgw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/ini.v1 v1.51.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/resty.v1 v1.12.0/go.mod h1:mDo4pnntr5jdWRML875a/NmxYqAlA73dVijT2AXvQQo=
gopkg.in/yaml.v2 v2.0.0-20170812160011-eb3733d160e7/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190106161140-3f1c8253044a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190418001031-e561f6794a2a/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
honnef.co/go/tools v0.0.1-2019.2.3/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=
rsc.io/binaryregexp v0.2.0/go.mod h1:qTv7/COck+e2FymRvadv62gMdZztPaShugOCi3I+8D8=

403
main.go Normal file
View File

@ -0,0 +1,403 @@
package main
import (
"context"
"csgowtfd/csgo"
"csgowtfd/ent"
"csgowtfd/ent/match"
"csgowtfd/ent/migrate"
"csgowtfd/ent/player"
"csgowtfd/ent/stats"
"csgowtfd/utils"
"flag"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
_ "github.com/mattn/go-sqlite3"
log "github.com/sirupsen/logrus"
"go.uber.org/ratelimit"
"gopkg.in/yaml.v3"
"net/http"
"os"
"strconv"
"sync"
"time"
)
var (
conf = utils.Conf{}
demoLoader = &csgo.DemoMatchLoader{}
router *mux.Router
db *utils.DBWithLock
sendGC chan *csgo.Demo
demoParser = &csgo.DemoParser{}
firstHK = true
rL ratelimit.Limiter
)
type PlayerResponse struct {
SteamID64 uint64 `json:"steamid64,string"`
Name string `json:"name"`
Avatar string `json:"avatar"`
VAC bool `json:"vac"`
Tracked bool `json:"tracked"`
VanityURL string `json:"vanity_url,omitempty"`
Matches []*MatchResponse `json:"matches,omitempty"`
}
type MatchResponse struct {
MatchId uint64 `json:"match_id,string"`
ShareCode string `json:"share_code"`
Map string `json:"map"`
Date time.Time `json:"date"`
Score [2]int `json:"score"`
Duration int `json:"duration"`
MatchResult int `json:"match_result"`
Rounds int `json:"rounds"`
Parsed bool `json:"parsed"`
Stats []*StatsResponse `json:"stats"`
}
type StatsResponse struct {
TeamID int `json:"team_id"`
Kills int `json:"kills"`
Deaths int `json:"deaths"`
Assists int `json:"assists"`
Headshot int `json:"headshot"`
MVP int `json:"mvp"`
Score int `json:"score"`
Player PlayerResponse `json:"player"`
Extended interface{} `json:"extended,omitempty"`
}
func housekeeping() {
for {
if !firstHK {
time.Sleep(5 * time.Minute)
}
firstHK = false
db.Lock.RLock()
tPlayerNeedSteamUpdate, err := db.Client.Player.Query().Where(
player.SteamUpdatedLTE(time.Now().UTC().AddDate(0, 0, -1)),
).All(context.Background())
db.Lock.RUnlock()
if err != nil {
log.Errorf("[HK] Can't query players: %v", err)
continue
}
for _, tPlayer := range tPlayerNeedSteamUpdate {
_, err = utils.UpdatePlayerFromSteam(tPlayer, conf.Steam.APIKey, db.Lock, rL)
}
if !demoLoader.GCReady {
log.Warningf("[HK] GC not ready, skipping sharecode refresh")
continue
}
db.Lock.RLock()
tPlayerNeedShareCodeUpdate, err := db.Client.Player.Query().Where(
player.And(
player.Or(
player.SharecodeUpdatedLTE(time.Now().UTC().Add(time.Duration(-30)*time.Minute)),
player.SharecodeUpdatedIsNil(),
),
player.Not(player.AuthCodeIsNil()),
)).All(context.Background())
db.Lock.RUnlock()
if err != nil {
log.Errorf("[HK] Can't query players: %v", err)
continue
}
for _, tPlayer := range tPlayerNeedShareCodeUpdate {
shareCodes, err := utils.GetNewShareCodesForPlayer(tPlayer, db.Lock, conf.Steam.APIKey, rL)
if err != nil {
log.Errorf("[HK] Error while request sharecodes: %v", err)
continue
}
for _, code := range shareCodes {
sendGC <- &csgo.Demo{
ShareCode: code,
}
}
}
}
}
func getPlayer(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
tPlayer, err := utils.GetPlayer(db, id, conf.Steam.APIKey, rL)
if err != nil {
log.Warningf("[GP] Player not found: %+v", err)
w.WriteHeader(http.StatusNotFound)
return
}
response := PlayerResponse{
SteamID64: tPlayer.Steamid,
Name: tPlayer.Name,
Avatar: tPlayer.AvatarURL,
VAC: tPlayer.Vac,
VanityURL: tPlayer.VanityURLReal,
Tracked: tPlayer.AuthCode != "",
Matches: []*MatchResponse{},
}
db.Lock.RLock()
tMatches, err := tPlayer.QueryMatches().Order(ent.Desc(match.FieldDate)).Limit(20).All(context.Background())
db.Lock.RUnlock()
if err != nil {
log.Debugf("[GP] No matches found for player %s", id)
err := utils.SendJSON(response, w)
if err != nil {
log.Errorf("[GP] Unable to marshal JSON: %v", err)
w.WriteHeader(http.StatusInternalServerError)
}
}
for _, iMatch := range tMatches {
mResponse := &MatchResponse{
MatchId: iMatch.MatchID,
ShareCode: iMatch.ShareCode,
Map: iMatch.Map,
Date: iMatch.Date,
Score: [2]int{iMatch.ScoreTeamA, iMatch.ScoreTeamB},
Duration: iMatch.Duration,
MatchResult: iMatch.MatchResult,
Rounds: iMatch.MaxRounds,
Parsed: iMatch.DemoParsed,
Stats: []*StatsResponse{},
}
db.Lock.RLock()
tStats, err := iMatch.QueryStats().Where(stats.HasPlayersWith(player.Steamid(tPlayer.Steamid))).WithPlayers().All(context.Background())
db.Lock.RUnlock()
if err != nil {
response.Matches = append(response.Matches, mResponse)
continue
}
for _, iStats := range tStats {
sResponse := &StatsResponse{
TeamID: iStats.TeamID,
Kills: iStats.Kills,
Deaths: iStats.Deaths,
Assists: iStats.Assists,
Headshot: iStats.Headshot,
MVP: iStats.Mvp,
Score: iStats.Score,
Extended: iStats.Extended,
}
mResponse.Stats = append(mResponse.Stats, sResponse)
}
response.Matches = append(response.Matches, mResponse)
}
err = utils.SendJSON(response, w)
if err != nil {
log.Errorf("[GP] Unable to marshal JSON: %v", err)
w.WriteHeader(http.StatusInternalServerError)
}
}
func postPlayerTrackMe(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
log.Errorf("[postPlayerTrackMe] %+v", err)
w.WriteHeader(http.StatusBadRequest)
return
}
id := r.Form.Get("id")
authCode := r.Form.Get("authcode")
shareCode := r.Form.Get("sharecode")
if id == "" || authCode == "" || !utils.AuthCodeRegEx.MatchString(authCode) {
log.Warningf("[PPTM] invalid arguments: %+v, %+v, %+v", id, authCode, shareCode)
w.WriteHeader(http.StatusBadRequest)
return
}
tPlayer, err := utils.GetPlayer(db, id, conf.Steam.APIKey, rL)
if err != nil {
log.Warningf("[PPTM] player not found: %+v", err)
w.WriteHeader(http.StatusNotFound)
return
}
_, err = utils.IsAuthCodeValid(tPlayer, db.Lock, conf.Steam.APIKey, shareCode, authCode, rL)
if err != nil {
log.Warningf("[PPTM] authCode provided for player %s is invalid: %v", id, err)
w.WriteHeader(http.StatusUnauthorized)
return
}
db.Lock.Lock()
err = tPlayer.Update().SetAuthCode(authCode).Exec(context.Background())
db.Lock.Unlock()
if err != nil {
log.Warningf("[PPTM] update player failed: %+v", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
if shareCode != "" && utils.ShareCodeRegEx.MatchString(shareCode) {
sendGC <- &csgo.Demo{ShareCode: shareCode}
}
w.WriteHeader(http.StatusOK)
}
func getMatchParse(w http.ResponseWriter, r *http.Request) {
shareCode := mux.Vars(r)["sharecode"]
if shareCode == "" || !utils.ShareCodeRegEx.MatchString(shareCode) {
log.Warningf("[PPTM] invalid arguments")
w.WriteHeader(http.StatusBadRequest)
return
}
sendGC <- &csgo.Demo{
ShareCode: shareCode,
}
w.WriteHeader(http.StatusOK)
}
func getMatch(w http.ResponseWriter, r *http.Request) {
id := mux.Vars(r)["id"]
if id == "" {
w.WriteHeader(http.StatusBadRequest)
return
}
matchId, err := strconv.ParseUint(id, 10, 64)
if err != nil {
log.Warningf("[GM] Error parsing matchID %s: %v", id, err)
w.WriteHeader(http.StatusBadRequest)
return
}
db.Lock.RLock()
tMatch, err := db.Client.Match.Query().Where(match.MatchID(matchId)).Only(context.Background())
db.Lock.RUnlock()
if err != nil {
log.Warningf("[GM] match %d not found: %+v", matchId, err)
w.WriteHeader(http.StatusNotFound)
}
mResponse := &MatchResponse{
MatchId: tMatch.MatchID,
ShareCode: tMatch.ShareCode,
Map: tMatch.Map,
Date: tMatch.Date,
Score: [2]int{tMatch.ScoreTeamA, tMatch.ScoreTeamB},
Duration: tMatch.Duration,
MatchResult: tMatch.MatchResult,
Rounds: tMatch.MaxRounds,
Parsed: tMatch.DemoParsed,
Stats: []*StatsResponse{},
}
db.Lock.RLock()
tStats, err := tMatch.QueryStats().WithPlayers().All(context.Background())
db.Lock.RUnlock()
if err != nil {
log.Errorf("[GM] can't find stats for match %d: %v", tMatch.MatchID, err)
}
for _, iStats := range tStats {
sResponse := &StatsResponse{
Player: PlayerResponse{
SteamID64: iStats.Edges.Players.Steamid,
Name: iStats.Edges.Players.Name,
Avatar: iStats.Edges.Players.AvatarURL,
VAC: iStats.Edges.Players.Vac,
VanityURL: iStats.Edges.Players.VanityURLReal,
Tracked: iStats.Edges.Players.AuthCode != "",
},
TeamID: iStats.TeamID,
Kills: iStats.Kills,
Deaths: iStats.Deaths,
Assists: iStats.Assists,
Headshot: iStats.Headshot,
MVP: iStats.Mvp,
Score: iStats.Score,
Extended: iStats.Extended,
}
mResponse.Stats = append(mResponse.Stats, sResponse)
}
err = utils.SendJSON(mResponse, w)
if err != nil {
log.Errorf("[GM] JSON: %+v", err)
w.WriteHeader(http.StatusInternalServerError)
}
}
/*
/player/<id> GET player internal or if not found: steamAPI data + overall stats
/player/trackme POST id, authcode, [sharecode]
/match/<id> GET CSGO-GC response + internal data if parsed <- may be big (ALL RELEVANT DATA)
/match/parse/<sharecode> GET parses sharecode provided
*/
func main() {
flag.Parse()
confStr, err := os.ReadFile("config.yaml")
utils.Check(err)
err = yaml.Unmarshal(confStr, &conf)
utils.Check(err)
lvl, err := log.ParseLevel(conf.Logging.Level)
utils.Check(err)
log.SetLevel(lvl)
db = &utils.DBWithLock{
Lock: new(sync.RWMutex),
}
db.Client, err = ent.Open("sqlite3", "file:opencsgo.db?_fk=1&cache=shared")
if err != nil {
log.Panicf("Failed to open database %s: %v", "opencsgo.db", err)
}
defer func(dbSQLite *ent.Client) {
utils.Check(dbSQLite.Close())
}(db.Client)
if err := db.Client.Schema.Create(context.Background(), migrate.WithDropIndex(true), migrate.WithDropColumn(true)); err != nil {
log.Panicf("Automigrate failed: %v", err)
}
rL = ratelimit.New(conf.Steam.RatePerSecond)
// setup GC
err = demoLoader.Setup(conf.Steam.Username)
if err != nil {
log.Fatalf("Unbale to setup DemoLoader: %v", err)
}
log.Info("Waiting for GC to be ready")
for demoLoader.GCReady != true {
time.Sleep(time.Second)
}
log.Info("GC ready, starting HTTP server")
sendGC = make(chan *csgo.Demo, 100)
utils.Check(demoParser.Setup(db.Client, db.Lock))
go utils.GCInfoParser(sendGC, demoLoader, demoParser, db, conf.Steam.APIKey, rL)
go housekeeping()
router = mux.NewRouter().StrictSlash(true)
router.HandleFunc("/player/{id}", getPlayer).Methods("GET")
router.HandleFunc("/player/trackme", postPlayerTrackMe).Methods("POST")
router.HandleFunc("/match/parse/{sharecode}", getMatchParse).Methods("GET")
router.HandleFunc("/match/{id:[0-9]{19}}", getMatch).Methods("GET")
loggedRouter := handlers.LoggingHandler(os.Stdout, router)
utils.Check(http.ListenAndServe(":8000", loggedRouter))
}

410
utils/utils.go Normal file
View File

@ -0,0 +1,410 @@
package utils
import (
"context"
"csgowtfd/csgo"
"csgowtfd/ent"
"csgowtfd/ent/match"
"csgowtfd/ent/player"
"encoding/json"
"encoding/xml"
"fmt"
"github.com/Philipp15b/go-steamapi"
log "github.com/sirupsen/logrus"
"go.uber.org/ratelimit"
"io"
"io/ioutil"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
type Conf struct {
Logging struct {
Level string
}
Steam struct {
Username string
APIKey string `yaml:"api_key"`
RatePerSecond int `yaml:"rate_per_sec"`
}
}
type DBWithLock struct {
Client *ent.Client
Lock *sync.RWMutex
}
type CommunityXML struct {
SteamID64 uint64 `xml:"steamID64"`
AvatarURL string `xml:"avatarFull"`
VacBanned bool `xml:"vacBanned"`
ProfileName string `xml:"steamID"`
Error string `xml:"error"`
VanityURL string `xml:"customURL"`
}
type shareCodeResponse struct {
Result struct {
Code string `json:"nextcode"`
} `json:"result"`
}
const (
steamID64Entry = "https://steamcommunity.com/profiles/%d?xml=1"
steamVanityURLEntry = "https://steamcommunity.com/id/%s?xml=1"
shareCodeURLEntry = "https://api.steampowered.com/ICSGOPlayers_730/GetNextMatchSharingCode/v1?key=%s&steamid=%d&steamidkey=%s&knowncode=%s"
)
var (
SteamId64RegEx = regexp.MustCompile(`^\d{17}$`)
ShareCodeRegEx = regexp.MustCompile(`^CSGO(?:-?[ABCDEFGHJKLMNOPQRSTUVWXYZabcdefhijkmnopqrstuvwxyz23456789]{5}){5}$`)
AuthCodeRegEx = regexp.MustCompile(`^[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{4}-[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{5}-[ABCDEFGHJKLMNOPQRSTUVWXYZ23456789]{4}$`)
)
func SendJSON(data interface{}, w http.ResponseWriter) error {
playerJson, err := json.Marshal(data)
if err != nil {
return err
}
w.WriteHeader(http.StatusOK)
_, err = w.Write(playerJson)
if err != nil {
return err
}
return nil
}
func IsAuthCodeValid(player *ent.Player, lock *sync.RWMutex, apiKey string, shareCode string, authCode string, rl ratelimit.Limiter) (bool, error) {
var tMatch *ent.Match
var err error
if shareCode == "" {
lock.RLock()
tMatch, err = player.QueryMatches().Order(ent.Desc(match.FieldDate)).First(context.Background())
lock.RUnlock()
if err != nil {
return false, err
}
_, err := getNextShareCode(tMatch.ShareCode, apiKey, authCode, player.Steamid, rl)
if err != nil {
return false, err
}
return true, nil
} else {
_, err := getNextShareCode(shareCode, apiKey, authCode, player.Steamid, rl)
if err != nil {
return false, err
}
return true, nil
}
}
func GetNewShareCodesForPlayer(player *ent.Player, lock *sync.RWMutex, apiKey string, rl ratelimit.Limiter) ([]string, error) {
lock.RLock()
tMatch, err := player.QueryMatches().Order(ent.Desc(match.FieldDate)).First(context.Background())
lock.RUnlock()
if err != nil {
return nil, err
}
var rCodes []string
newShareCode, err := getNextShareCode(tMatch.ShareCode, apiKey, player.AuthCode, player.Steamid, rl)
if err != nil {
return nil, err
}
for newShareCode != "n/a" {
rCodes = append(rCodes, newShareCode)
newShareCode, err = getNextShareCode(rCodes[len(rCodes)-1], apiKey, player.AuthCode, player.Steamid, rl)
if err != nil {
return nil, err
}
time.Sleep(time.Second)
}
lock.Lock()
err = player.Update().SetSharecodeUpdated(time.Now().UTC()).Exec(context.Background())
lock.Unlock()
if err != nil {
return nil, err
}
return rCodes, nil
}
func getNextShareCode(lastCode string, apiKey string, authCode string, steamId uint64, rl ratelimit.Limiter) (string, error) {
if lastCode == "" || apiKey == "" || authCode == "" || steamId == 0 {
return "", fmt.Errorf("invalid arguments")
}
rl.Take()
log.Debugf("[SC] STEAMPI with %s", fmt.Sprintf(shareCodeURLEntry, apiKey, steamId, authCode, lastCode))
r, err := http.Get(fmt.Sprintf(shareCodeURLEntry, apiKey, steamId, authCode, lastCode))
if err != nil {
return "", err
}
if r.StatusCode == 202 {
return "n/a", nil
} else if r.StatusCode != 200 {
return "", fmt.Errorf("bad response from steam api (HTTP%d)", r.StatusCode)
}
defer r.Body.Close()
bJson, err := ioutil.ReadAll(r.Body)
if err != nil {
return "", err
}
rJson := new(shareCodeResponse)
err = json.Unmarshal(bJson, rJson)
if err != nil {
return "", err
}
return rJson.Result.Code, nil
}
func GetPlayer(db *DBWithLock, id interface{}, apiKey string, rl ratelimit.Limiter) (*ent.Player, error) {
switch e := id.(type) {
case uint64:
return GetPlayerFromSteamID64(db, e, apiKey, rl)
case string:
if SteamId64RegEx.MatchString(e) {
steamID64, err := strconv.ParseUint(e, 10, 64)
if err != nil {
return nil, err
}
return GetPlayerFromSteamID64(db, steamID64, apiKey, rl)
}
return GetPlayerFromVanityURL(db, e)
default:
return nil, fmt.Errorf("invalid arguments")
}
}
func GetPlayerFromVanityURL(db *DBWithLock, id string) (*ent.Player, error) {
if id == "" {
return nil, fmt.Errorf("invalid arguments")
}
db.Lock.RLock()
tPlayer, err := db.Client.Player.Query().Where(player.VanityURL(strings.ToLower(id))).Only(context.Background())
db.Lock.RUnlock()
if err == nil {
return tPlayer, nil
} else {
profile, err := SteamProfile2XML(id, 0)
if err != nil {
return nil, err
}
if profile.Error != "" {
return nil, fmt.Errorf("profile not found")
}
db.Lock.Lock()
nPlayer, err := db.Client.Player.Create().SetSteamid(profile.SteamID64).SetVanityURL(strings.ToLower(profile.VanityURL)).SetVac(profile.VacBanned).SetAvatarURL(profile.AvatarURL).SetName(profile.ProfileName).Save(context.Background())
db.Lock.Unlock()
if err != nil {
return nil, err
}
return nPlayer, nil
}
}
func GetPlayerFromSteamID64(db *DBWithLock, steamID uint64, apiKey string, rl ratelimit.Limiter) (*ent.Player, error) {
db.Lock.RLock()
tPlayer, err := db.Client.Player.Query().Where(player.Steamid(steamID)).Only(context.Background())
db.Lock.RUnlock()
if err == nil {
return tPlayer, nil
} else {
db.Lock.Lock()
nPlayer, err := db.Client.Player.Create().SetSteamid(steamID).Save(context.Background())
db.Lock.Unlock()
if err != nil {
return nil, err
}
nPlayer, err = UpdatePlayerFromSteam(nPlayer, apiKey, db.Lock, rl)
if err != nil {
return nil, err
}
return nPlayer, nil
}
}
func GCInfoParser(channel chan *csgo.Demo, dl *csgo.DemoMatchLoader, dp *csgo.DemoParser, db *DBWithLock, apiKey string, rl ratelimit.Limiter) {
for {
select {
case demo := <-channel:
if !dl.GCReady {
time.Sleep(5 * time.Second)
channel <- demo
}
matchId, _, _, err := csgo.DecodeSharecode(demo.ShareCode)
Check(err)
if matchId == 0 {
log.Warningf("Can't parse match with sharecode %s", demo.ShareCode)
continue
}
db.Lock.RLock()
iMatch, err := db.Client.Match.Query().Where(match.MatchID(matchId)).Only(context.Background())
db.Lock.RUnlock()
if err != nil {
switch e := err.(type) {
case *ent.NotFoundError:
break
default:
Check(e)
}
} else {
if iMatch.DemoParsed == false && !iMatch.DemoExpired {
log.Infof("Match %d is loaded, but not parsed. Try parsing.", demo.MatchId)
demo.MatchId = matchId
demo.Url = iMatch.ReplayURL
dp.ParseDemo(demo)
continue
}
log.Debugf("Skipped match %d: already parsed", matchId)
continue
}
matchDetails, err := dl.GetMatchDetails(demo.ShareCode)
Check(err)
matchZero := matchDetails.GetMatches()[0]
lastRound := matchZero.GetRoundstatsall()[len(matchZero.Roundstatsall)-1]
var players []*ent.Player
for _, accountId := range lastRound.GetReservation().GetAccountIds() {
tPlayer, err := GetPlayer(db, csgo.AccountId2SteamId(accountId), apiKey, rl)
Check(err)
players = append(players, tPlayer)
}
demo.Url = lastRound.GetMap()
demo.MatchId = matchZero.GetMatchid()
db.Lock.Lock()
tMatch, err := db.Client.Match.Create().
SetMatchID(matchZero.GetMatchid()).
AddPlayers(players...).
SetDate(time.Unix(int64(matchZero.GetMatchtime()), 0).UTC()).
SetMaxRounds(int(lastRound.GetMaxRounds())).
SetDuration(int(lastRound.GetMatchDuration())).
SetShareCode(demo.ShareCode).
SetReplayURL(lastRound.GetMap()).
SetScoreTeamA(int(lastRound.GetTeamScores()[0])).
SetScoreTeamB(int(lastRound.GetTeamScores()[1])).
SetMatchResult(int(lastRound.GetMatchResult())).
Save(context.Background())
db.Lock.Unlock()
Check(err)
for i, mPlayer := range players {
var teamId int
if i > 4 {
teamId = 2
} else {
teamId = 1
}
db.Lock.Lock()
err := db.Client.Stats.Create().
SetMatches(tMatch).
SetPlayers(mPlayer).
SetTeamID(teamId).
SetKills(int(lastRound.GetKills()[i])).
SetDeaths(int(lastRound.GetDeaths()[i])).
SetAssists(int(lastRound.GetAssists()[i])).
SetMvp(int(lastRound.GetMvps()[i])).
SetScore(int(lastRound.GetScores()[i])).
SetHeadshot(int(lastRound.GetEnemyHeadshots()[i])).
Exec(context.Background())
db.Lock.Unlock()
Check(err)
}
dp.ParseDemo(demo)
}
}
}
func SteamProfile2XML(id string, steamID64 uint64) (*CommunityXML, error) {
var r *http.Response
var err error
if steamID64 != 0 {
r, err = http.Get(fmt.Sprintf(steamID64Entry, steamID64))
} else {
r, err = http.Get(fmt.Sprintf(steamVanityURLEntry, id))
}
Check(err)
defer func(Body io.ReadCloser) {
err := Body.Close()
Check(err)
}(r.Body)
body, err := ioutil.ReadAll(r.Body)
if err != nil {
return nil, err
}
cXML := &CommunityXML{}
err = xml.Unmarshal(body, cXML)
if err != nil {
return nil, err
}
return cXML, nil
}
func UpdatePlayerFromSteam(player *ent.Player, apiKey string, lock *sync.RWMutex, rl ratelimit.Limiter) (*ent.Player, error) {
profile, err := SteamProfile2XML("", player.Steamid)
if err != nil {
return nil, err
}
if profile.Error != "" {
return nil, fmt.Errorf("profile not found")
}
lock.Lock()
tPlayer, err := player.Update().SetName(profile.ProfileName).SetVac(profile.VacBanned).SetAvatarURL(profile.AvatarURL).SetSteamUpdated(time.Now().UTC()).SetVanityURL(strings.ToLower(profile.VanityURL)).SetVanityURLReal(profile.VanityURL).SetSteamUpdated(time.Now().UTC()).Save(context.Background())
lock.Unlock()
if err != nil {
return nil, err
}
rl.Take()
bans, err := steamapi.GetPlayerBans([]uint64{profile.SteamID64}, apiKey)
if err != nil {
return nil, err
}
if len(bans) > 0 && bans[0].NumberOfVACBans > 0 {
banDate := time.Now().UTC().AddDate(0, 0, -1*int(bans[0].DaysSinceLastBan))
lock.Lock()
err := tPlayer.Update().SetVacCount(int(bans[0].NumberOfVACBans)).SetVacDate(banDate).Exec(context.Background())
lock.Unlock()
if err != nil {
return nil, err
}
}
return tPlayer, nil
}
func Check(e error) {
if e != nil {
panic(e)
}
}