第一次上传
This commit is contained in:
commit
79fa5bf76e
17
.vscode/launch.json
vendored
Normal file
17
.vscode/launch.json
vendored
Normal file
@ -0,0 +1,17 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Launch",
|
||||
"type": "go",
|
||||
"request": "launch",
|
||||
"mode": "auto",
|
||||
"program": "${fileDirname}",
|
||||
"env": {},
|
||||
"args": []
|
||||
}
|
||||
]
|
||||
}
|
661
LICENSE
Normal file
661
LICENSE
Normal file
@ -0,0 +1,661 @@
|
||||
GNU AFFERO GENERAL PUBLIC LICENSE
|
||||
Version 3, 19 November 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU Affero General Public License is a free, copyleft license for
|
||||
software and other kinds of works, specifically designed to ensure
|
||||
cooperation with the community in the case of network server software.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
our General Public Licenses are intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
Developers that use our General Public Licenses protect your rights
|
||||
with two steps: (1) assert copyright on the software, and (2) offer
|
||||
you this License which gives you legal permission to copy, distribute
|
||||
and/or modify the software.
|
||||
|
||||
A secondary benefit of defending all users' freedom is that
|
||||
improvements made in alternate versions of the program, if they
|
||||
receive widespread use, become available for other developers to
|
||||
incorporate. Many developers of free software are heartened and
|
||||
encouraged by the resulting cooperation. However, in the case of
|
||||
software used on network servers, this result may fail to come about.
|
||||
The GNU General Public License permits making a modified version and
|
||||
letting the public access it on a server without ever releasing its
|
||||
source code to the public.
|
||||
|
||||
The GNU Affero General Public License is designed specifically to
|
||||
ensure that, in such cases, the modified source code becomes available
|
||||
to the community. It requires the operator of a network server to
|
||||
provide the source code of the modified version running there to the
|
||||
users of that server. Therefore, public use of a modified version, on
|
||||
a publicly accessible server, gives the public access to the source
|
||||
code of the modified version.
|
||||
|
||||
An older license, called the Affero General Public License and
|
||||
published by Affero, was designed to accomplish similar goals. This is
|
||||
a different license, not a version of the Affero GPL, but Affero has
|
||||
released a new version of the Affero GPL which permits relicensing under
|
||||
this license.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU Affero General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Remote Network Interaction; Use with the GNU General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, if you modify the
|
||||
Program, your modified version must prominently offer all users
|
||||
interacting with it remotely through a computer network (if your version
|
||||
supports such interaction) an opportunity to receive the Corresponding
|
||||
Source of your version by providing access to the Corresponding Source
|
||||
from a network server at no charge, through some standard or customary
|
||||
means of facilitating copying of software. This Corresponding Source
|
||||
shall include the Corresponding Source for any work covered by version 3
|
||||
of the GNU General Public License that is incorporated pursuant to the
|
||||
following paragraph.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the work with which it is combined will remain governed by version
|
||||
3 of the GNU General Public License.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU Affero General Public License from time to time. Such new versions
|
||||
will be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU Affero General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU Affero General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU Affero General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<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 Affero General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Affero General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU Affero General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If your software can interact with users remotely through a computer
|
||||
network, you should also make sure that it provides a way for users to
|
||||
get its source. For example, if your program is a web application, its
|
||||
interface could display a "Source" link that leads users to an archive
|
||||
of the code. There are many ways you could offer source, and different
|
||||
solutions will be better for different programs; see section 13 for the
|
||||
specific requirements.
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
25
README.md
Normal file
25
README.md
Normal file
@ -0,0 +1,25 @@
|
||||
# netplay-lobby-server-go
|
||||
|
||||
Netplay lobby server written in GO. Needs Go v1.13.
|
||||
|
||||
## Deployment
|
||||
|
||||
```bash
|
||||
go build
|
||||
./netplay-lobby-server-go
|
||||
```
|
||||
|
||||
## Configuration
|
||||
Rename the ```config/lobby.template.yaml``` to ```config/lobby.yaml``` and place the configuration file in one of the
|
||||
following directories:
|
||||
|
||||
- /etc/lobby
|
||||
- $HOME/.lobby
|
||||
- ./config
|
||||
|
||||
## LICENSE
|
||||
|
||||
The server itself is licensed under AGPLv3.
|
||||
|
||||
This product includes GeoLite2 data created by MaxMind, available from
|
||||
[https://www.maxmind.com](https://www.maxmind.com)
|
28
config.go
Normal file
28
config.go
Normal file
@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
// Config is the struct that holds the lobby server configuration
|
||||
type Config struct {
|
||||
Server ServerConfig
|
||||
Database DatabaseConfig
|
||||
Relay map[string]string
|
||||
Blacklist BlacklistConfig
|
||||
}
|
||||
|
||||
// ServerConfig holds the basic server config.
|
||||
type ServerConfig struct {
|
||||
Address string
|
||||
GeoLite2Path string
|
||||
TemplatePath string
|
||||
}
|
||||
|
||||
// DatabaseConfig holds the database config.
|
||||
type DatabaseConfig struct {
|
||||
Type string
|
||||
Connection string
|
||||
}
|
||||
|
||||
// BlacklistConfig configures the different blacklists.
|
||||
type BlacklistConfig struct {
|
||||
Strings []string // General blacklisted words as RE
|
||||
IPs []string
|
||||
}
|
21
config/lobby.template.yaml
Normal file
21
config/lobby.template.yaml
Normal file
@ -0,0 +1,21 @@
|
||||
server:
|
||||
address: 0.0.0.0:7777
|
||||
geolite2path: ./geolite2/GeoLite2-Country.mmdb
|
||||
templatepath: ./web/templates
|
||||
|
||||
database:
|
||||
# mysql, postgres, sqlite
|
||||
type: sqlite
|
||||
# database specific connection string
|
||||
connection: ":memory:"
|
||||
|
||||
relay:
|
||||
nyc: "example.relay.com"
|
||||
|
||||
blacklist:
|
||||
nickname:
|
||||
- someRE1.*
|
||||
- someRE2.*
|
||||
ips:
|
||||
- 1.1.1.1
|
||||
- 8.8.8.8
|
21
config/lobby.yaml
Normal file
21
config/lobby.yaml
Normal file
@ -0,0 +1,21 @@
|
||||
server:
|
||||
address: 0.0.0.0:7777
|
||||
geolite2path: ./geolite2/GeoLite2-Country.mmdb
|
||||
templatepath: ./web/templates
|
||||
|
||||
database:
|
||||
# mysql, postgres, sqlite
|
||||
type: sqlite
|
||||
# database specific connection string
|
||||
connection: ":memory:"
|
||||
|
||||
relay:
|
||||
nyc: "example.relay.com"
|
||||
|
||||
blacklist:
|
||||
nickname:
|
||||
- someRE1.*
|
||||
- someRE2.*
|
||||
ips:
|
||||
- 1.1.1.1
|
||||
- 8.8.8.8
|
204
controller/sessioncontroller.go
Normal file
204
controller/sessioncontroller.go
Normal file
@ -0,0 +1,204 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/libretro/netplay-lobby-server-go/domain"
|
||||
"github.com/libretro/netplay-lobby-server-go/model/entity"
|
||||
)
|
||||
|
||||
// Template 抽象模板渲染。
|
||||
type Template struct {
|
||||
templates *template.Template
|
||||
}
|
||||
|
||||
// Render 实现 echo 模板渲染接口
|
||||
func (t *Template) Render(w io.Writer, name string, data interface{}, c echo.Context) error {
|
||||
return t.templates.ExecuteTemplate(w, name, data)
|
||||
}
|
||||
|
||||
// SessionDomain 接口,用于将控制器逻辑与领域代码解耦。
|
||||
type SessionDomain interface {
|
||||
Add(request *domain.AddSessionRequest, ip net.IP) (*entity.Session, error)
|
||||
Get(roomID int32) (*entity.Session, error)
|
||||
List() ([]entity.Session, error)
|
||||
GetTunnel(tunnelName string) *domain.MitmInfo
|
||||
PurgeOld() error
|
||||
}
|
||||
|
||||
// ListSessionsResponse 是一个自定义的 DTO,用于向后兼容。
|
||||
type SessionsResponse struct {
|
||||
Fields entity.Session `json:"fields"`
|
||||
}
|
||||
|
||||
// SessionController 处理所有与会话相关的请求
|
||||
type SessionController struct {
|
||||
sessionDomain SessionDomain
|
||||
}
|
||||
|
||||
// NewSessionController 返回一个新的会话控制器
|
||||
func NewSessionController(sessionDomain SessionDomain) *SessionController {
|
||||
return &SessionController{sessionDomain}
|
||||
}
|
||||
|
||||
// RegisterRoutes 在 echo 框架实例中注册所有控制器路由。
|
||||
func (c *SessionController) RegisterRoutes(server *echo.Echo) {
|
||||
server.POST("/add", c.Add)
|
||||
server.POST("/add/", c.Add) // 旧路径
|
||||
server.GET("/list", c.List)
|
||||
server.GET("/list/", c.List) // 旧路径
|
||||
server.GET("/tunnel", c.Tunnel)
|
||||
server.GET("/tunnel/", c.Tunnel) // 旧路径
|
||||
server.GET("/", c.Index)
|
||||
server.GET("/:roomID", c.Get)
|
||||
server.GET("/:roomID/", c.Get) // 旧路径
|
||||
}
|
||||
|
||||
// PrerenderTemplates 预渲染所有模板
|
||||
func (c *SessionController) PrerenderTemplates(server *echo.Echo, filePattern string) error {
|
||||
templates, err := template.New("").Funcs(
|
||||
template.FuncMap{
|
||||
"prettyBool": func(b bool) string {
|
||||
if b {
|
||||
return "Yes"
|
||||
}
|
||||
return "No"
|
||||
},
|
||||
"prettyDate": func(d time.Time) string {
|
||||
utc, _ := time.LoadLocation("UTC")
|
||||
return d.In(utc).Format(time.RFC822)
|
||||
},
|
||||
},
|
||||
).ParseGlob(filePattern)
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("无法解析模板: %w", err)
|
||||
}
|
||||
|
||||
t := &Template{
|
||||
templates: templates,
|
||||
}
|
||||
server.Renderer = t
|
||||
return nil
|
||||
}
|
||||
|
||||
// Index 处理器
|
||||
// GET /
|
||||
func (c *SessionController) Index(ctx echo.Context) error {
|
||||
logger := ctx.Logger()
|
||||
|
||||
sessions, err := c.sessionDomain.List()
|
||||
if err != nil {
|
||||
logger.Errorf("无法渲染会话列表: %v", err)
|
||||
return ctx.NoContent(http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
return ctx.Render(http.StatusOK, "index.html", sessions)
|
||||
}
|
||||
|
||||
// Get 处理器
|
||||
// GET /:roomID
|
||||
func (c *SessionController) Get(ctx echo.Context) error {
|
||||
logger := ctx.Logger()
|
||||
|
||||
roomIDString := ctx.Param("roomID")
|
||||
roomID, err := strconv.ParseInt(roomIDString, 10, 32)
|
||||
if err != nil {
|
||||
logger.Errorf("无法通过 roomID 获取会话。RoomID 不是有效的 int32: %v", err)
|
||||
return ctx.NoContent(http.StatusBadRequest)
|
||||
}
|
||||
|
||||
session, err := c.sessionDomain.Get(int32(roomID))
|
||||
if err != nil || session == nil {
|
||||
logger.Errorf("无法获取会话: %v", err)
|
||||
return ctx.NoContent(http.StatusNotFound)
|
||||
}
|
||||
|
||||
// 出于兼容旧实现的原因,我们需要将会话放在一个包装对象中,
|
||||
// 该对象的会话可以通过键 "fields" 访问。旧实现还返回一个条目的列表...
|
||||
response := make([]SessionsResponse, 1)
|
||||
response[0] = SessionsResponse{*session}
|
||||
return ctx.JSONPretty(http.StatusOK, response, " ")
|
||||
}
|
||||
|
||||
// List 处理器
|
||||
// GET /list
|
||||
func (c *SessionController) List(ctx echo.Context) error {
|
||||
logger := ctx.Logger()
|
||||
|
||||
sessions, err := c.sessionDomain.List()
|
||||
if err != nil {
|
||||
logger.Errorf("无法渲染会话列表: %v", err)
|
||||
return ctx.NoContent(http.StatusInternalServerError)
|
||||
}
|
||||
|
||||
// 出于兼容旧实现的原因,我们需要将会话放在一个包装对象中,
|
||||
// 该对象的会话可以通过键 "fields" 访问
|
||||
response := make([]SessionsResponse, len(sessions))
|
||||
for i, session := range sessions {
|
||||
response[i].Fields = session
|
||||
}
|
||||
|
||||
return ctx.JSONPretty(http.StatusOK, response, " ")
|
||||
}
|
||||
|
||||
// Add 处理器
|
||||
// POST /add
|
||||
func (c *SessionController) Add(ctx echo.Context) error {
|
||||
logger := ctx.Logger()
|
||||
var err error
|
||||
var session *entity.Session
|
||||
|
||||
var req domain.AddSessionRequest
|
||||
if err := ctx.Bind(&req); err != nil {
|
||||
logger.Errorf("无法解析传入的会话: %v", err)
|
||||
return ctx.NoContent(http.StatusBadRequest)
|
||||
}
|
||||
|
||||
ip := net.ParseIP(ctx.RealIP())
|
||||
|
||||
if session, err = c.sessionDomain.Add(&req, ip); err != nil {
|
||||
logger.Errorf("不会添加会话: %v", err)
|
||||
|
||||
if errors.Is(err, domain.ErrSessionRejected) {
|
||||
logger.Errorf("会话被拒绝: %v", session)
|
||||
return ctx.NoContent(http.StatusBadRequest)
|
||||
} else if errors.Is(err, domain.ErrRateLimited) {
|
||||
return ctx.NoContent(http.StatusTooManyRequests)
|
||||
}
|
||||
return ctx.NoContent(http.StatusBadRequest)
|
||||
}
|
||||
|
||||
result := "status=OK\n"
|
||||
result += session.PrintForRetroarch()
|
||||
return ctx.String(http.StatusOK, result)
|
||||
}
|
||||
|
||||
// Tunnel 处理器
|
||||
// GET /tunnel
|
||||
func (c *SessionController) Tunnel(ctx echo.Context) error {
|
||||
logger := ctx.Logger()
|
||||
|
||||
tunnelName := ctx.QueryParam("name")
|
||||
if tunnelName == "" {
|
||||
return ctx.NoContent(http.StatusBadRequest)
|
||||
}
|
||||
|
||||
tunnel := c.sessionDomain.GetTunnel(tunnelName)
|
||||
if tunnel == nil {
|
||||
logger.Errorf("找不到隧道服务器: '%s'", tunnelName)
|
||||
return ctx.NoContent(http.StatusNotFound)
|
||||
}
|
||||
|
||||
result := "status=OK\n"
|
||||
result += tunnel.PrintForRetroarch()
|
||||
return ctx.String(http.StatusOK, result)
|
||||
}
|
208
controller/sessioncontroller_test.go
Normal file
208
controller/sessioncontroller_test.go
Normal file
@ -0,0 +1,208 @@
|
||||
package controller
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/libretro/netplay-lobby-server-go/domain"
|
||||
"github.com/libretro/netplay-lobby-server-go/model/entity"
|
||||
)
|
||||
|
||||
var testSession = entity.Session{
|
||||
ID: "",
|
||||
RoomID: 0,
|
||||
Username: "zelda",
|
||||
Country: "en",
|
||||
GameName: "supergame",
|
||||
GameCRC: "FFFFFFFF",
|
||||
CoreName: "unes",
|
||||
CoreVersion: "0.2.1",
|
||||
SubsystemName: "subsub",
|
||||
RetroArchVersion: "1.1.1",
|
||||
Frontend: "retro",
|
||||
IP: net.ParseIP("127.0.0.1"),
|
||||
Port: 55355,
|
||||
MitmAddress: "",
|
||||
MitmPort: 0,
|
||||
MitmSession: "",
|
||||
HostMethod: entity.HostMethodUPNP,
|
||||
HasPassword: false,
|
||||
HasSpectatePassword: false,
|
||||
Connectable: true,
|
||||
IsRetroArch: true,
|
||||
CreatedAt: time.Date(2010, 9, 12, 11, 33, 05, 0, time.UTC),
|
||||
UpdatedAt: time.Date(2010, 9, 12, 11, 33, 05, 0, time.UTC),
|
||||
ContentHash: "",
|
||||
}
|
||||
|
||||
type SessionDomainMock struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *SessionDomainMock) Add(request *domain.AddSessionRequest, ip net.IP) (*entity.Session, error) {
|
||||
args := m.Called(request, ip)
|
||||
session, _ := args.Get(0).(*entity.Session)
|
||||
return session, args.Error(1)
|
||||
}
|
||||
|
||||
func (m *SessionDomainMock) Get(roomID int32) (*entity.Session, error) {
|
||||
args := m.Called(roomID)
|
||||
session, _ := args.Get(0).(*entity.Session)
|
||||
return session, args.Error(1)
|
||||
}
|
||||
|
||||
func (m *SessionDomainMock) List() ([]entity.Session, error) {
|
||||
args := m.Called()
|
||||
sessions, _ := args.Get(0).([]entity.Session)
|
||||
return sessions, args.Error(1)
|
||||
}
|
||||
|
||||
func (m *SessionDomainMock) PurgeOld() error {
|
||||
args := m.Called()
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
func TestSessionControllerIndex(t *testing.T) {
|
||||
domainMock := &SessionDomainMock{}
|
||||
|
||||
server := echo.New()
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
ctx := server.NewContext(req, rec)
|
||||
handler := NewSessionController(domainMock)
|
||||
err := handler.PrerenderTemplates(server, "../web/templates/*.html")
|
||||
require.NoError(t, err)
|
||||
|
||||
session1 := testSession
|
||||
session1.Username = "Player 1"
|
||||
session2 := testSession
|
||||
session2.Username = "Player 2"
|
||||
sessions := []entity.Session{session1, session2}
|
||||
domainMock.On("List").Return(sessions, nil)
|
||||
|
||||
handler.Index(ctx)
|
||||
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
assert.Contains(t, rec.Body.String(), "Player 1")
|
||||
assert.Contains(t, rec.Body.String(), "Player 2")
|
||||
}
|
||||
|
||||
func TestSessionControllerGet(t *testing.T) {
|
||||
domainMock := &SessionDomainMock{}
|
||||
|
||||
server := echo.New()
|
||||
req := httptest.NewRequest(http.MethodGet, "/", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
ctx := server.NewContext(req, rec)
|
||||
ctx.SetPath("/:roomID")
|
||||
ctx.SetParamNames("roomID")
|
||||
ctx.SetParamValues("100")
|
||||
handler := NewSessionController(domainMock)
|
||||
|
||||
session := testSession
|
||||
expectedResultBody := `[
|
||||
{
|
||||
"fields": {
|
||||
"id": 0,
|
||||
"username": "zelda",
|
||||
"country": "en",
|
||||
"game_name": "supergame",
|
||||
"game_crc": "FFFFFFFF",
|
||||
"core_name": "unes",
|
||||
"core_version": "0.2.1",
|
||||
"subsystem_name": "subsub",
|
||||
"retroarch_version": "1.1.1",
|
||||
"frontend": "retro",
|
||||
"ip": "127.0.0.1",
|
||||
"port": 55355,
|
||||
"mitm_ip": "",
|
||||
"mitm_port": 0,
|
||||
"mitm_session": "",
|
||||
"host_method": 2,
|
||||
"has_password": false,
|
||||
"has_spectate_password": false,
|
||||
"connectable": true,
|
||||
"is_retroarch": true,
|
||||
"created": "2010-09-12T11:33:05Z",
|
||||
"updated": "2010-09-12T11:33:05Z"
|
||||
}
|
||||
}
|
||||
]
|
||||
`
|
||||
domainMock.On("Get", int32(100)).Return(&session, nil)
|
||||
|
||||
handler.Get(ctx)
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
assert.Equal(t, expectedResultBody, rec.Body.String())
|
||||
}
|
||||
|
||||
func TestSessionControllerList(t *testing.T) {
|
||||
domainMock := &SessionDomainMock{}
|
||||
|
||||
server := echo.New()
|
||||
req := httptest.NewRequest(http.MethodGet, "/list", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
ctx := server.NewContext(req, rec)
|
||||
handler := NewSessionController(domainMock)
|
||||
|
||||
sessions := make([]entity.Session, 1)
|
||||
expectedResultBody := `[
|
||||
{
|
||||
"fields": {
|
||||
"id": 0,
|
||||
"username": "",
|
||||
"country": "",
|
||||
"game_name": "",
|
||||
"game_crc": "",
|
||||
"core_name": "",
|
||||
"core_version": "",
|
||||
"subsystem_name": "",
|
||||
"retroarch_version": "",
|
||||
"frontend": "",
|
||||
"ip": "",
|
||||
"port": 0,
|
||||
"mitm_ip": "",
|
||||
"mitm_port": 0,
|
||||
"mitm_session": "",
|
||||
"host_method": 0,
|
||||
"has_password": false,
|
||||
"has_spectate_password": false,
|
||||
"connectable": true,
|
||||
"is_retroarch": true,
|
||||
"created": "0001-01-01T00:00:00Z",
|
||||
"updated": "0001-01-01T00:00:00Z"
|
||||
}
|
||||
}
|
||||
]
|
||||
`
|
||||
domainMock.On("List").Return(sessions, nil)
|
||||
|
||||
handler.List(ctx)
|
||||
assert.Equal(t, http.StatusOK, rec.Code)
|
||||
assert.Equal(t, expectedResultBody, rec.Body.String())
|
||||
}
|
||||
|
||||
func TestSessionControllerListError(t *testing.T) {
|
||||
domainMock := &SessionDomainMock{}
|
||||
|
||||
e := echo.New()
|
||||
req := httptest.NewRequest(http.MethodGet, "/list", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
ctx := e.NewContext(req, rec)
|
||||
handler := NewSessionController(domainMock)
|
||||
|
||||
domainMock.On("List").Return(nil, errors.New("test error"))
|
||||
|
||||
handler.List(ctx)
|
||||
assert.Equal(t, http.StatusInternalServerError, rec.Code)
|
||||
assert.Equal(t, "", rec.Body.String())
|
||||
}
|
47
domain/geoip2domain.go
Normal file
47
domain/geoip2domain.go
Normal file
@ -0,0 +1,47 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/oschwald/maxminddb-golang"
|
||||
)
|
||||
|
||||
// GeoIP2Domain 抽象了 GeoIP2 国家数据库的领域逻辑。
|
||||
type GeoIP2Domain struct {
|
||||
db *maxminddb.Reader
|
||||
}
|
||||
|
||||
type countryRecord struct {
|
||||
Country struct {
|
||||
ISOCode string `maxminddb:"iso_code"`
|
||||
} `maxminddb:"country"`
|
||||
}
|
||||
|
||||
// NewGeoIP2Domain 创建一个新的 GeoIP2 国家数据库领域对象。需要 maxminddb 文件的路径。
|
||||
func NewGeoIP2Domain(path string) (*GeoIP2Domain, error) {
|
||||
db, err := maxminddb.Open(path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("无法打开 geoip2 国家数据库 %s: %w", path, err)
|
||||
}
|
||||
|
||||
return &GeoIP2Domain{db}, nil
|
||||
}
|
||||
|
||||
// GetCountryCodeForIP 返回给定 IP 的两字母国家代码(ISO 3166-1)。
|
||||
func (d *GeoIP2Domain) GetCountryCodeForIP(ip net.IP) (string, error) {
|
||||
record := &countryRecord{}
|
||||
|
||||
err := d.db.Lookup(ip, record)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("无法查找 IP %s 的国家: %w", ip, err)
|
||||
}
|
||||
|
||||
return strings.ToLower(record.Country.ISOCode), nil
|
||||
}
|
||||
|
||||
// Close 需要被调用以正确关闭内部的 maxminddb 数据库。
|
||||
func (d *GeoIP2Domain) Close() {
|
||||
d.db.Close()
|
||||
}
|
43
domain/geoip2domain_test.go
Normal file
43
domain/geoip2domain_test.go
Normal file
@ -0,0 +1,43 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const geoip2Path = "../geoip2/GeoLite2-Country.mmdb"
|
||||
|
||||
func setupGeoip2Domain(t *testing.T) *GeoIP2Domain {
|
||||
geoip2, err := NewGeoIP2Domain(geoip2Path)
|
||||
require.NoError(t, err, "Can't create the GeoIP2Domain logic")
|
||||
return geoip2
|
||||
}
|
||||
|
||||
func TestGeoIP2GetCountryCodeForIP(t *testing.T) {
|
||||
geoip2Domain := setupGeoip2Domain(t)
|
||||
assert.NotNil(t, geoip2Domain)
|
||||
if geoip2Domain != nil {
|
||||
germanCode, err := geoip2Domain.GetCountryCodeForIP(net.ParseIP("46.243.122.48"))
|
||||
assert.NoError(t, err, "Can't get germany country code")
|
||||
assert.Equal(t, "de", germanCode)
|
||||
|
||||
usCode, err := geoip2Domain.GetCountryCodeForIP(net.ParseIP("54.208.114.32"))
|
||||
assert.NoError(t, err, "Can't get US country code")
|
||||
assert.Equal(t, "us", usCode)
|
||||
|
||||
localCode, err := geoip2Domain.GetCountryCodeForIP(net.ParseIP("127.0.0.1"))
|
||||
assert.NoError(t, err, "Can't get local code")
|
||||
assert.Equal(t, "", localCode)
|
||||
|
||||
localCode, err = geoip2Domain.GetCountryCodeForIP(net.ParseIP("192.168.178.2"))
|
||||
assert.NoError(t, err, "Can't get local code")
|
||||
assert.Equal(t, "", localCode)
|
||||
|
||||
localCode, err = geoip2Domain.GetCountryCodeForIP(net.ParseIP("10.0.0.1"))
|
||||
assert.NoError(t, err, "Can't get local code")
|
||||
assert.Equal(t, "", localCode)
|
||||
}
|
||||
}
|
57
domain/mitmdomain.go
Normal file
57
domain/mitmdomain.go
Normal file
@ -0,0 +1,57 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// MitmInfo represents a relay server info.
|
||||
type MitmInfo struct {
|
||||
Address string
|
||||
Port uint16
|
||||
}
|
||||
|
||||
// MitmDomain abstracts the mitm logic for handling netplay relays.
|
||||
type MitmDomain struct {
|
||||
server map[string]string
|
||||
}
|
||||
|
||||
// NewMitmDomain creates a new MITM domain logic.
|
||||
func NewMitmDomain(servers map[string]string) *MitmDomain {
|
||||
return &MitmDomain{servers}
|
||||
}
|
||||
|
||||
// GetInfo translates a MITM server handle into an address/port pair.
|
||||
func (d *MitmDomain) GetInfo(handle string) *MitmInfo {
|
||||
var server MitmInfo
|
||||
|
||||
address, found := d.server[handle]
|
||||
if !found || address == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
info := strings.Split(address, ":")
|
||||
if len(info) != 2 {
|
||||
return nil
|
||||
}
|
||||
|
||||
addr := info[0]
|
||||
if addr == "" {
|
||||
return nil
|
||||
}
|
||||
port, err := strconv.ParseInt(info[1], 10, 32)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return nil
|
||||
}
|
||||
|
||||
server.Address = addr
|
||||
server.Port = uint16(port)
|
||||
|
||||
return &server
|
||||
}
|
||||
|
||||
// PrintForRetroarch prints out the MITM information in a format that retroarch is expecting.
|
||||
func (i *MitmInfo) PrintForRetroarch() string {
|
||||
return fmt.Sprintf("tunnel_addr=%s\ntunnel_port=%d\n", i.Address, i.Port)
|
||||
}
|
332
domain/sessiondomain.go
Normal file
332
domain/sessiondomain.go
Normal file
@ -0,0 +1,332 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/libretro/netplay-lobby-server-go/model/entity"
|
||||
)
|
||||
|
||||
// SessionDeadline 是一个会话在没有收到任何更新的情况下的生命周期(以秒为单位)。
|
||||
const SessionDeadline = 60
|
||||
|
||||
// RateLimit 是客户端可以发送更新的最大速率(每五秒)。
|
||||
const RateLimit = 5
|
||||
|
||||
// requestType 枚举
|
||||
type requestType int
|
||||
|
||||
// SessionAddType 枚举值
|
||||
const (
|
||||
SessionCreate requestType = iota
|
||||
SessionUpdate
|
||||
SessionTouch
|
||||
)
|
||||
|
||||
// AddSessionRequest 定义了 SessionDomain.Add() 请求的请求结构。
|
||||
type AddSessionRequest struct {
|
||||
Username string `form:"username"`
|
||||
CoreName string `form:"core_name"`
|
||||
CoreVersion string `form:"core_version"`
|
||||
GameName string `form:"game_name"`
|
||||
GameCRC string `form:"game_crc"`
|
||||
Port uint16 `form:"port"`
|
||||
MITMServer string `form:"mitm_server"`
|
||||
HasPassword bool `form:"has_password"` // 1/0(可以绑定到 bool 吗?)
|
||||
HasSpectatePassword bool `form:"has_spectate_password"`
|
||||
ForceMITM bool `form:"force_mitm"`
|
||||
RetroArchVersion string `form:"retroarch_version"`
|
||||
Frontend string `form:"frontend"`
|
||||
SubsystemName string `form:"subsystem_name"`
|
||||
MITMSession string `form:"mitm_session"`
|
||||
MITMCustomServer string `form:"mitm_custom_addr"`
|
||||
MITMCustomPort uint16 `form:"mitm_custom_port"`
|
||||
}
|
||||
|
||||
// ErrSessionRejected 当会话被域逻辑拒绝时抛出。
|
||||
var ErrSessionRejected = errors.New("会话被拒绝")
|
||||
|
||||
// ErrRateLimited 当达到特定会话的速率限制时抛出。
|
||||
var ErrRateLimited = errors.New("速率限制已达到")
|
||||
|
||||
// SessionRepository 接口用于将域逻辑与存储库代码解耦。
|
||||
type SessionRepository interface {
|
||||
Create(s *entity.Session) error
|
||||
GetByID(id string) (*entity.Session, error)
|
||||
GetByRoomID(roomID int32) (*entity.Session, error)
|
||||
GetAll(deadline time.Time) ([]entity.Session, error)
|
||||
Update(s *entity.Session) error
|
||||
Touch(id string) error
|
||||
PurgeOld(deadline time.Time) error
|
||||
}
|
||||
|
||||
// SessionDomain 抽象了 netplay 会话处理的域逻辑。
|
||||
type SessionDomain struct {
|
||||
sessionRepo SessionRepository
|
||||
geopip2Domain *GeoIP2Domain
|
||||
validationDomain *ValidationDomain
|
||||
mitmDomain *MitmDomain
|
||||
}
|
||||
|
||||
// NewSessionDomain 返回一个初始化的 SessionDomain 结构。
|
||||
func NewSessionDomain(
|
||||
sessionRepo SessionRepository,
|
||||
geoIP2Domain *GeoIP2Domain,
|
||||
validationDomain *ValidationDomain,
|
||||
mitmDomain *MitmDomain) *SessionDomain {
|
||||
return &SessionDomain{sessionRepo, geoIP2Domain, validationDomain, mitmDomain}
|
||||
}
|
||||
|
||||
// Add 添加或更新会话,基于来自给定 IP 的传入请求。
|
||||
// 如果会话被拒绝,则返回 ErrSessionRejected。
|
||||
// 如果达到会话的速率限制,则返回 ErrRateLimited。
|
||||
func (d *SessionDomain) Add(request *AddSessionRequest, ip net.IP) (*entity.Session, error) {
|
||||
var err error
|
||||
var savedSession *entity.Session
|
||||
var requestType requestType = SessionCreate
|
||||
|
||||
session := d.parseSession(request, ip)
|
||||
|
||||
if session.IP == nil || session.Port == 0 {
|
||||
return nil, errors.New("IP 或端口未设置")
|
||||
}
|
||||
|
||||
// 决定这是 CREATE、UPDATE 还是 TOUCH 操作
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
if savedSession, err = d.sessionRepo.GetByID(session.ID); err != nil {
|
||||
return nil, fmt.Errorf("无法获取已保存的会话: %w", err)
|
||||
}
|
||||
if savedSession != nil {
|
||||
session.RoomID = savedSession.RoomID
|
||||
session.Country = savedSession.Country
|
||||
session.Connectable = savedSession.Connectable
|
||||
session.IsRetroArch = savedSession.IsRetroArch
|
||||
session.CreatedAt = savedSession.CreatedAt
|
||||
session.UpdatedAt = savedSession.UpdatedAt
|
||||
if savedSession.ContentHash != session.ContentHash {
|
||||
requestType = SessionUpdate
|
||||
} else {
|
||||
requestType = SessionTouch
|
||||
}
|
||||
}
|
||||
|
||||
// 在 UPDATE 或 TOUCH 上进行速率限制
|
||||
if requestType == SessionUpdate || requestType == SessionTouch {
|
||||
threshold := time.Now().Add(-5 * time.Second)
|
||||
if savedSession.UpdatedAt.After(threshold) {
|
||||
return nil, ErrRateLimited
|
||||
}
|
||||
}
|
||||
|
||||
if requestType == SessionCreate || requestType == SessionUpdate {
|
||||
// 在 CREATE 和 UPDATE 上验证会话
|
||||
if !d.validateSession(session) {
|
||||
return nil, ErrSessionRejected
|
||||
}
|
||||
}
|
||||
|
||||
// 持久化会话更改
|
||||
switch requestType {
|
||||
case SessionCreate:
|
||||
if session.Country, err = d.geopip2Domain.GetCountryCodeForIP(session.IP); err != nil {
|
||||
return nil, fmt.Errorf("无法找到给定 IP %s 的国家: %w", session.IP, err)
|
||||
}
|
||||
|
||||
d.trySessionConnect(session)
|
||||
|
||||
if err = d.sessionRepo.Create(session); err != nil {
|
||||
return nil, fmt.Errorf("无法创建新会话: %w", err)
|
||||
}
|
||||
case SessionUpdate:
|
||||
d.trySessionConnect(session)
|
||||
|
||||
if err = d.sessionRepo.Update(session); err != nil {
|
||||
return nil, fmt.Errorf("无法更新旧会话: %w", err)
|
||||
}
|
||||
case SessionTouch:
|
||||
if !session.Connectable {
|
||||
d.trySessionConnect(session)
|
||||
if session.Connectable {
|
||||
if err = d.sessionRepo.Update(session); err != nil {
|
||||
return nil, fmt.Errorf("无法更新旧会话: %w", err)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if err = d.sessionRepo.Touch(session.ID); err != nil {
|
||||
return nil, fmt.Errorf("无法触碰旧会话: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
// Get 返回具有给定 RoomID 的会话
|
||||
func (d *SessionDomain) Get(roomID int32) (*entity.Session, error) {
|
||||
session, err := d.sessionRepo.GetByRoomID(roomID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
// List 返回当前正在托管的所有会话的列表
|
||||
func (d *SessionDomain) List() ([]entity.Session, error) {
|
||||
sessions, err := d.sessionRepo.GetAll(d.getDeadline())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return sessions, nil
|
||||
}
|
||||
|
||||
// PurgeOld 删除所有超过 45 秒未更新的会话。
|
||||
func (d *SessionDomain) PurgeOld() error {
|
||||
if err := d.sessionRepo.PurgeOld(d.getDeadline()); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseSession 将请求转换为可以与持久化会话进行比较的会话信息
|
||||
func (d *SessionDomain) parseSession(req *AddSessionRequest, ip net.IP) *entity.Session {
|
||||
var hostMethod entity.HostMethod = entity.HostMethodUnknown
|
||||
var mitmHandle string = ""
|
||||
var mitmAddress string = ""
|
||||
var mitmPort uint16 = 0
|
||||
var mitmSession string = ""
|
||||
|
||||
// 设置默认用户名
|
||||
if req.Username == "" {
|
||||
req.Username = "匿名"
|
||||
}
|
||||
|
||||
if req.ForceMITM && req.MITMServer != "" && req.MITMSession != "" {
|
||||
if req.MITMServer == "custom" {
|
||||
if req.MITMCustomServer != "" && req.MITMCustomPort != 0 {
|
||||
hostMethod = entity.HostMethodMITM
|
||||
mitmHandle = req.MITMServer
|
||||
mitmAddress = req.MITMCustomServer
|
||||
mitmPort = req.MITMCustomPort
|
||||
mitmSession = req.MITMSession
|
||||
}
|
||||
} else {
|
||||
if info := d.GetTunnel(req.MITMServer); info != nil {
|
||||
hostMethod = entity.HostMethodMITM
|
||||
mitmHandle = req.MITMServer
|
||||
mitmAddress = info.Address
|
||||
mitmPort = info.Port
|
||||
mitmSession = req.MITMSession
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &entity.Session{
|
||||
Username: req.Username,
|
||||
GameName: req.GameName,
|
||||
GameCRC: strings.ToUpper(req.GameCRC),
|
||||
CoreName: req.CoreName,
|
||||
CoreVersion: req.CoreVersion,
|
||||
SubsystemName: req.SubsystemName,
|
||||
RetroArchVersion: req.RetroArchVersion,
|
||||
Frontend: req.Frontend,
|
||||
IP: ip,
|
||||
Port: req.Port,
|
||||
MitmHandle: mitmHandle,
|
||||
MitmAddress: mitmAddress,
|
||||
MitmPort: mitmPort,
|
||||
MitmSession: mitmSession,
|
||||
HostMethod: hostMethod,
|
||||
HasPassword: req.HasPassword,
|
||||
HasSpectatePassword: req.HasSpectatePassword,
|
||||
}
|
||||
}
|
||||
|
||||
// validateSession 验证传入的会话
|
||||
func (d *SessionDomain) validateSession(s *entity.Session) bool {
|
||||
if len(s.Username) > 32 ||
|
||||
len(s.CoreName) > 255 ||
|
||||
len(s.GameName) > 255 ||
|
||||
len(s.GameCRC) != 8 ||
|
||||
len(s.RetroArchVersion) > 32 ||
|
||||
len(s.CoreVersion) > 255 ||
|
||||
len(s.SubsystemName) > 255 ||
|
||||
len(s.Frontend) > 255 ||
|
||||
len(s.MitmSession) > 32 {
|
||||
return false
|
||||
}
|
||||
|
||||
if !d.validationDomain.ValidateString(s.Username) ||
|
||||
!d.validationDomain.ValidateString(s.CoreName) ||
|
||||
!d.validationDomain.ValidateString(s.CoreVersion) ||
|
||||
!d.validationDomain.ValidateString(s.Frontend) ||
|
||||
!d.validationDomain.ValidateString(s.SubsystemName) ||
|
||||
!d.validationDomain.ValidateString(s.RetroArchVersion) {
|
||||
return false
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// trySessionConnect 测试会话是否可连接以及是否为 RetroArch
|
||||
func (d *SessionDomain) trySessionConnect(s *entity.Session) error {
|
||||
s.Connectable = true
|
||||
s.IsRetroArch = true
|
||||
|
||||
// 如果是 MITM,假设既可连接又是 RetroArch
|
||||
if s.HostMethod == entity.HostMethodMITM {
|
||||
return nil
|
||||
}
|
||||
|
||||
address := fmt.Sprintf("%s:%d", s.IP, s.Port)
|
||||
conn, err := net.DialTimeout("tcp", address, time.Second*3)
|
||||
if err != nil {
|
||||
s.Connectable = false
|
||||
return err
|
||||
}
|
||||
|
||||
ranp := []byte{0x52, 0x41, 0x4E, 0x50} // RANP
|
||||
full := []byte{0x46, 0x55, 0x4C, 0x4C} // FULL
|
||||
poke := []byte{0x50, 0x4F, 0x4B, 0x45} // POKE
|
||||
magic := make([]byte, 4)
|
||||
|
||||
// 忽略写入错误
|
||||
conn.SetWriteDeadline(time.Now().Add(time.Second * 3))
|
||||
conn.Write(poke)
|
||||
|
||||
conn.SetReadDeadline(time.Now().Add(time.Second * 3))
|
||||
read, err := conn.Read(magic)
|
||||
|
||||
conn.Close()
|
||||
|
||||
// 在接收错误时假设它是 RetroArch
|
||||
if err != nil || read == 0 {
|
||||
return err
|
||||
}
|
||||
|
||||
// 在不完整的魔术上假设它不是 RetroArch
|
||||
if read != len(magic) {
|
||||
s.IsRetroArch = false
|
||||
} else if !bytes.Equal(magic, ranp) && !bytes.Equal(magic, full) {
|
||||
s.IsRetroArch = false
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *SessionDomain) getDeadline() time.Time {
|
||||
return time.Now().Add(-SessionDeadline * time.Second)
|
||||
}
|
||||
|
||||
// GetTunnel 返回隧道的地址/端口对。
|
||||
func (d *SessionDomain) GetTunnel(tunnelName string) *MitmInfo {
|
||||
return d.mitmDomain.GetInfo(tunnelName)
|
||||
}
|
351
domain/sessiondomain_test.go
Normal file
351
domain/sessiondomain_test.go
Normal file
@ -0,0 +1,351 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/libretro/netplay-lobby-server-go/model/entity"
|
||||
)
|
||||
|
||||
var testIP = net.ParseIP("192.168.178.2")
|
||||
|
||||
// testRequest and testSession should have the same values for the test below.
|
||||
var testRequest = AddSessionRequest{
|
||||
Username: "zelda",
|
||||
CoreName: "bsnes",
|
||||
CoreVersion: "0.2.1",
|
||||
GameName: "supergame",
|
||||
GameCRC: "FFFFFFFF",
|
||||
Port: 55355,
|
||||
MITMServer: "",
|
||||
HasPassword: false,
|
||||
HasSpectatePassword: false,
|
||||
ForceMITM: false,
|
||||
RetroArchVersion: "1.1.1",
|
||||
Frontend: "retro",
|
||||
SubsystemName: "subsub",
|
||||
MITMSession: "",
|
||||
MITMCustomServer: "",
|
||||
MITMCustomPort: 0,
|
||||
}
|
||||
|
||||
var testSession = entity.Session{
|
||||
ID: "",
|
||||
RoomID: 100,
|
||||
Username: "zelda",
|
||||
Country: "en",
|
||||
GameName: "supergame",
|
||||
GameCRC: "FFFFFFFF",
|
||||
CoreName: "bsnes",
|
||||
CoreVersion: "0.2.1",
|
||||
SubsystemName: "subsub",
|
||||
RetroArchVersion: "1.1.1",
|
||||
Frontend: "retro",
|
||||
IP: net.ParseIP("192.168.178.2"),
|
||||
Port: 55355,
|
||||
MitmHandle: "",
|
||||
MitmAddress: "",
|
||||
MitmPort: 0,
|
||||
MitmSession: "",
|
||||
HostMethod: entity.HostMethodUnknown,
|
||||
HasPassword: false,
|
||||
HasSpectatePassword: false,
|
||||
Connectable: true,
|
||||
IsRetroArch: true,
|
||||
CreatedAt: time.Now().Add(-5 * time.Minute),
|
||||
UpdatedAt: time.Now().Add(-5 * time.Minute),
|
||||
ContentHash: "",
|
||||
}
|
||||
|
||||
type SessionRepositoryMock struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
func (m *SessionRepositoryMock) Create(s *entity.Session) error {
|
||||
args := m.Called(s)
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
func (m *SessionRepositoryMock) Update(s *entity.Session) error {
|
||||
args := m.Called(s)
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
func (m *SessionRepositoryMock) Touch(id string) error {
|
||||
args := m.Called(id)
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
func (m *SessionRepositoryMock) GetByID(id string) (*entity.Session, error) {
|
||||
args := m.Called(id)
|
||||
session, _ := args.Get(0).(*entity.Session)
|
||||
return session, args.Error(1)
|
||||
}
|
||||
|
||||
func (m *SessionRepositoryMock) GetByRoomID(roomID int32) (*entity.Session, error) {
|
||||
args := m.Called(roomID)
|
||||
session, _ := args.Get(0).(*entity.Session)
|
||||
return session, args.Error(1)
|
||||
}
|
||||
|
||||
func (m *SessionRepositoryMock) GetAll(deadline time.Time) ([]entity.Session, error) {
|
||||
args := m.Called(deadline)
|
||||
sessions, _ := args.Get(0).([]entity.Session)
|
||||
return sessions, args.Error(1)
|
||||
}
|
||||
|
||||
func (m *SessionRepositoryMock) PurgeOld(deadline time.Time) error {
|
||||
args := m.Called(deadline)
|
||||
return args.Error(0)
|
||||
}
|
||||
|
||||
func setupSessionDomain(t *testing.T) (*SessionDomain, *SessionRepositoryMock) {
|
||||
repoMock := SessionRepositoryMock{}
|
||||
|
||||
validationDomain, err := NewValidationDomain(testStringBlacklist, testIPBlacklist)
|
||||
require.NoError(t, err)
|
||||
|
||||
geoip2Domain := setupGeoip2Domain(t)
|
||||
|
||||
sessionDomain := NewSessionDomain(&repoMock, geoip2Domain, validationDomain, &MitmDomain{})
|
||||
require.NoError(t, err)
|
||||
|
||||
return sessionDomain, &repoMock
|
||||
}
|
||||
|
||||
func TestSessionDomainPurgeOld(t *testing.T) {
|
||||
sessionDomain, repoMock := setupSessionDomain(t)
|
||||
|
||||
// Test the deadline duration
|
||||
repoMock.On("PurgeOld", mock.MatchedBy(
|
||||
func(d time.Time) bool {
|
||||
before := time.Now().Add(-(SessionDeadline - 1) * time.Second)
|
||||
after := time.Now().Add(-(SessionDeadline + 1) * time.Second)
|
||||
return d.Before(before) && d.After(after)
|
||||
})).Return(nil)
|
||||
|
||||
err := sessionDomain.PurgeOld()
|
||||
require.NoError(t, err, "Can't purge old sessions")
|
||||
}
|
||||
|
||||
func TestSessionDomainList(t *testing.T) {
|
||||
sessionDomain, repoMock := setupSessionDomain(t)
|
||||
|
||||
// Test the deadline duration
|
||||
repoMock.On("GetAll", mock.MatchedBy(
|
||||
func(d time.Time) bool {
|
||||
before := time.Now().Add(-(SessionDeadline - 1) * time.Second)
|
||||
after := time.Now().Add(-(SessionDeadline + 1) * time.Second)
|
||||
return d.Before(before) && d.After(after)
|
||||
})).Return(make([]entity.Session, 3), nil)
|
||||
|
||||
sessions, err := sessionDomain.List()
|
||||
require.NoError(t, err, "Can't list sessions")
|
||||
require.NotNil(t, sessions)
|
||||
assert.Equal(t, 3, len(sessions))
|
||||
}
|
||||
|
||||
func TestSessionDomainValidateSessionAtCreate(t *testing.T) {
|
||||
sessionDomain, repoMock := setupSessionDomain(t)
|
||||
|
||||
request := testRequest
|
||||
comp := testSession
|
||||
comp.CalculateID()
|
||||
comp.CalculateContentHash()
|
||||
|
||||
request.GameCRC = "123456789"
|
||||
|
||||
repoMock.On("GetByID", mock.MatchedBy(
|
||||
func(s string) bool {
|
||||
return s == comp.ID
|
||||
})).Return(nil, nil)
|
||||
|
||||
newSession, err := sessionDomain.Add(&request, testIP)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, newSession)
|
||||
assert.True(t, errors.Is(err, ErrSessionRejected))
|
||||
}
|
||||
|
||||
func TestSessionDomainValidateSessionAtUpdate(t *testing.T) {
|
||||
sessionDomain, repoMock := setupSessionDomain(t)
|
||||
|
||||
request := testRequest
|
||||
comp := testSession
|
||||
comp.CalculateID()
|
||||
comp.CalculateContentHash()
|
||||
|
||||
request.RetroArchVersion = "0123456789ABCDEF0123456789ABCDEF_INVALID"
|
||||
|
||||
repoMock.On("GetByID", mock.MatchedBy(
|
||||
func(s string) bool {
|
||||
return s == comp.ID
|
||||
})).Return(&comp, nil)
|
||||
|
||||
newSession, err := sessionDomain.Add(&request, testIP)
|
||||
require.Error(t, err)
|
||||
assert.Nil(t, newSession)
|
||||
assert.True(t, errors.Is(err, ErrSessionRejected))
|
||||
}
|
||||
|
||||
func TestSessionDomainAddSessionTypeCreate(t *testing.T) {
|
||||
sessionDomain, repoMock := setupSessionDomain(t)
|
||||
|
||||
request := testRequest
|
||||
comp := testSession
|
||||
comp.CalculateID()
|
||||
comp.CalculateContentHash()
|
||||
|
||||
repoMock.On("GetByID", mock.MatchedBy(
|
||||
func(s string) bool {
|
||||
return s == comp.ID
|
||||
})).Return(nil, nil)
|
||||
|
||||
repoMock.On("Create", mock.MatchedBy(
|
||||
func(s *entity.Session) bool {
|
||||
return s.ID == comp.ID && s.ContentHash == comp.ContentHash
|
||||
})).Return(nil)
|
||||
|
||||
newSession, err := sessionDomain.Add(&request, testIP)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, newSession)
|
||||
assert.Equal(t, comp.ID, newSession.ID)
|
||||
assert.Equal(t, comp.ContentHash, newSession.ContentHash)
|
||||
}
|
||||
|
||||
func TestSessionDomainAddSessionTypeCreateShouldSetDefaultUsername(t *testing.T) {
|
||||
sessionDomain, repoMock := setupSessionDomain(t)
|
||||
|
||||
request := testRequest
|
||||
request.Username = ""
|
||||
|
||||
comp := testSession
|
||||
comp.Username = "Anonymous"
|
||||
comp.CalculateID()
|
||||
comp.CalculateContentHash()
|
||||
|
||||
repoMock.On("GetByID", mock.MatchedBy(
|
||||
func(s string) bool {
|
||||
return s == comp.ID
|
||||
})).Return(nil, nil)
|
||||
|
||||
repoMock.On("Create", mock.MatchedBy(
|
||||
func(s *entity.Session) bool {
|
||||
return s.ID == comp.ID && s.ContentHash == comp.ContentHash
|
||||
})).Return(nil)
|
||||
|
||||
newSession, err := sessionDomain.Add(&request, testIP)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, newSession)
|
||||
assert.Equal(t, comp.ID, newSession.ID)
|
||||
assert.Equal(t, comp.ContentHash, newSession.ContentHash)
|
||||
}
|
||||
|
||||
func TestSessionDomainAddSessionTypeUpdate(t *testing.T) {
|
||||
sessionDomain, repoMock := setupSessionDomain(t)
|
||||
|
||||
request := testRequest
|
||||
comp := testSession
|
||||
comp.CalculateID()
|
||||
comp.CalculateContentHash()
|
||||
|
||||
request.GameCRC = "88888888"
|
||||
|
||||
repoMock.On("GetByID", mock.MatchedBy(
|
||||
func(s string) bool {
|
||||
return s == comp.ID
|
||||
})).Return(&comp, nil)
|
||||
|
||||
repoMock.On("Update", mock.MatchedBy(
|
||||
func(s *entity.Session) bool {
|
||||
return s.ID == comp.ID && s.ContentHash != comp.ContentHash
|
||||
})).Return(nil)
|
||||
|
||||
newSession, err := sessionDomain.Add(&request, testIP)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, newSession)
|
||||
assert.Equal(t, comp.ID, newSession.ID)
|
||||
assert.NotEqual(t, comp.ContentHash, newSession.ContentHash)
|
||||
}
|
||||
|
||||
func TestSessionDomainAddSessionTypeTouch(t *testing.T) {
|
||||
sessionDomain, repoMock := setupSessionDomain(t)
|
||||
|
||||
request := testRequest
|
||||
comp := testSession
|
||||
comp.CalculateID()
|
||||
comp.CalculateContentHash()
|
||||
|
||||
repoMock.On("GetByID", mock.MatchedBy(
|
||||
func(s string) bool {
|
||||
return s == comp.ID
|
||||
})).Return(&comp, nil)
|
||||
|
||||
repoMock.On("Touch", mock.MatchedBy(
|
||||
func(id string) bool {
|
||||
return id == comp.ID
|
||||
})).Return(nil)
|
||||
|
||||
newSession, err := sessionDomain.Add(&request, testIP)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, newSession)
|
||||
assert.Equal(t, comp.ID, newSession.ID)
|
||||
assert.Equal(t, comp.ContentHash, newSession.ContentHash)
|
||||
}
|
||||
|
||||
func TestSessionDomainAddSessionTypeUpdateRateLimit(t *testing.T) {
|
||||
sessionDomain, repoMock := setupSessionDomain(t)
|
||||
|
||||
request := testRequest
|
||||
comp := testSession
|
||||
comp.UpdatedAt = time.Now().Add(-4 * time.Second)
|
||||
comp.CalculateID()
|
||||
comp.CalculateContentHash()
|
||||
|
||||
request.GameCRC = "88888888"
|
||||
|
||||
repoMock.On("GetByID", mock.MatchedBy(
|
||||
func(s string) bool {
|
||||
return s == comp.ID
|
||||
})).Return(&comp, nil)
|
||||
|
||||
repoMock.On("Update", mock.MatchedBy(
|
||||
func(s *entity.Session) bool {
|
||||
return s.ID == comp.ID && s.ContentHash != comp.ContentHash
|
||||
})).Return(nil)
|
||||
|
||||
newSession, err := sessionDomain.Add(&request, testIP)
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, ErrRateLimited))
|
||||
assert.Nil(t, newSession)
|
||||
}
|
||||
|
||||
func TestSessionDomainAddSessionTypeTouchRateLimit(t *testing.T) {
|
||||
sessionDomain, repoMock := setupSessionDomain(t)
|
||||
|
||||
request := testRequest
|
||||
comp := testSession
|
||||
comp.UpdatedAt = time.Now().Add(-4 * time.Second)
|
||||
comp.CalculateID()
|
||||
comp.CalculateContentHash()
|
||||
|
||||
repoMock.On("GetByID", mock.MatchedBy(
|
||||
func(s string) bool {
|
||||
return s == comp.ID
|
||||
})).Return(&comp, nil)
|
||||
|
||||
repoMock.On("Touch", mock.MatchedBy(
|
||||
func(id string) bool {
|
||||
return id == comp.ID
|
||||
})).Return(nil)
|
||||
|
||||
newSession, err := sessionDomain.Add(&request, testIP)
|
||||
require.Error(t, err)
|
||||
assert.True(t, errors.Is(err, ErrRateLimited))
|
||||
assert.Nil(t, newSession)
|
||||
}
|
73
domain/validationdomain.go
Normal file
73
domain/validationdomain.go
Normal file
@ -0,0 +1,73 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"regexp"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// ValidationDomain provides the domain logic for session validation
|
||||
type ValidationDomain struct {
|
||||
stringBlacklist []regexp.Regexp
|
||||
ipBlacklist []net.IP
|
||||
}
|
||||
|
||||
// NewValidationDomain creates a new initalized Validation domain logic struct.
|
||||
func NewValidationDomain(stringBlacklist []string, ipBlacklist []string) (*ValidationDomain, error) {
|
||||
ub := make([]regexp.Regexp, 0, len(stringBlacklist))
|
||||
for _, entry := range stringBlacklist {
|
||||
exp, err := regexp.Compile(entry)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Can't compile username blacklist regexp '%s': %w", entry, err)
|
||||
}
|
||||
ub = append(ub, *exp)
|
||||
}
|
||||
|
||||
ib := make([]net.IP, 0, len(ipBlacklist))
|
||||
for _, entry := range ipBlacklist {
|
||||
ip := net.ParseIP(entry)
|
||||
if ip == nil {
|
||||
return nil, fmt.Errorf("Can't parse ip blacklist entry '%s'", entry)
|
||||
}
|
||||
ib = append(ib, ip)
|
||||
}
|
||||
|
||||
return &ValidationDomain{ub, ib}, nil
|
||||
}
|
||||
|
||||
// ValidateString validates a string against a regexp based blacklist and other rulesets. The validation has linear complexity.
|
||||
func (d *ValidationDomain) ValidateString(s string) bool {
|
||||
if !d.isASCII(s) {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, entry := range d.stringBlacklist {
|
||||
if entry.MatchString(s) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// ValdateIP validates an IP address against a IP blacklist. The validation has linear complexity.
|
||||
func (d *ValidationDomain) ValdateIP(ip net.IP) bool {
|
||||
for _, entry := range d.ipBlacklist {
|
||||
if entry.Equal(ip) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (d *ValidationDomain) isASCII(s string) bool {
|
||||
for _, char := range s {
|
||||
if char > unicode.MaxASCII {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
68
domain/validationdomain_test.go
Normal file
68
domain/validationdomain_test.go
Normal file
@ -0,0 +1,68 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
var testStringBlacklist = []string{
|
||||
".*badWord.*",
|
||||
"^prefixTest.*$",
|
||||
"\\s{3,}",
|
||||
}
|
||||
|
||||
var testIPBlacklist = []string{
|
||||
"127.0.0.1",
|
||||
"2001:db8:0:8d3:0:8a2e:70:7344",
|
||||
}
|
||||
|
||||
func TestValidationDomainValidCreation(t *testing.T) {
|
||||
_, err := NewValidationDomain(testStringBlacklist, testIPBlacklist)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestValidationDomainInvalidIP(t *testing.T) {
|
||||
_, err := NewValidationDomain(testStringBlacklist, []string{"256.123.12.3"})
|
||||
require.Error(t, err)
|
||||
|
||||
_, err = NewValidationDomain(testStringBlacklist, []string{"2001:db8:0:8d3:0:8a2ef:70:7344"})
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestValidationDomainRegexpShouldNotCompile(t *testing.T) {
|
||||
_, err := NewValidationDomain([]string{"["}, testIPBlacklist)
|
||||
require.Error(t, err)
|
||||
|
||||
_, err = NewValidationDomain([]string{"[0-9]++"}, testIPBlacklist)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestValidationDomainValidateString(t *testing.T) {
|
||||
validationDomain, err := NewValidationDomain(testStringBlacklist, testIPBlacklist)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.False(t, validationDomain.ValidateString("non ascii ä"))
|
||||
assert.False(t, validationDomain.ValidateString("utf-8 𝄞"))
|
||||
assert.False(t, validationDomain.ValidateString(" spaces"))
|
||||
assert.False(t, validationDomain.ValidateString("spaces "))
|
||||
assert.True(t, validationDomain.ValidateString("mario"))
|
||||
assert.True(t, validationDomain.ValidateString("zelda"))
|
||||
assert.False(t, validationDomain.ValidateString("prefixTestZelda"))
|
||||
assert.True(t, validationDomain.ValidateString("ZeldaprefixTest"))
|
||||
}
|
||||
|
||||
func TestValidationDomainValidateIP(t *testing.T) {
|
||||
validationDomain, err := NewValidationDomain(testStringBlacklist, testIPBlacklist)
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.True(t, validationDomain.ValdateIP(net.ParseIP("192.168.178.2")))
|
||||
assert.True(t, validationDomain.ValdateIP(net.ParseIP("8.8.8.8")))
|
||||
assert.True(t, validationDomain.ValdateIP(net.ParseIP("88.12.123.77")))
|
||||
assert.True(t, validationDomain.ValdateIP(net.ParseIP("2001:db8::1428:57ab")))
|
||||
assert.True(t, validationDomain.ValdateIP(net.ParseIP("2001:db8:0:0:0:8d3:0:0")))
|
||||
assert.False(t, validationDomain.ValdateIP(net.ParseIP("127.0.0.1")))
|
||||
assert.False(t, validationDomain.ValdateIP(net.ParseIP("2001:db8:0:8d3:0:8a2e:70:7344")))
|
||||
}
|
1
geoip2/COPYRIGHT
Normal file
1
geoip2/COPYRIGHT
Normal file
@ -0,0 +1 @@
|
||||
Database and Contents Copyright (c) 2020 MaxMind, Inc.
|
BIN
geoip2/GeoLite2-Country.mmdb
Normal file
BIN
geoip2/GeoLite2-Country.mmdb
Normal file
Binary file not shown.
8
geoip2/LICENSE
Normal file
8
geoip2/LICENSE
Normal file
@ -0,0 +1,8 @@
|
||||
This license applies only to the provided GeoLite2 database file.
|
||||
|
||||
Use of this MaxMind product is governed by MaxMind's GeoLite2 End User License Agreement,
|
||||
which can be viewed at https://www.maxmind.com/en/geolite2/eula.
|
||||
|
||||
This database incorporates GeoNames [https://www.geonames.org] geographical data, which is
|
||||
made available under the Creative Commons Attribution 4.0 License. To view a copy of this
|
||||
license, visit https://creativecommons.org/licenses/by/4.0/.
|
1
geolite2/COPYRIGHT
Normal file
1
geolite2/COPYRIGHT
Normal file
@ -0,0 +1 @@
|
||||
Database and Contents Copyright (c) 2020 MaxMind, Inc.
|
BIN
geolite2/GeoLite2-Country.mmdb
Normal file
BIN
geolite2/GeoLite2-Country.mmdb
Normal file
Binary file not shown.
8
geolite2/LICENSE
Normal file
8
geolite2/LICENSE
Normal file
@ -0,0 +1,8 @@
|
||||
This license applies only to the provided GeoLite2 database file.
|
||||
|
||||
Use of this MaxMind product is governed by MaxMind's GeoLite2 End User License Agreement,
|
||||
which can be viewed at https://www.maxmind.com/en/geolite2/eula.
|
||||
|
||||
This database incorporates GeoNames [https://www.geonames.org] geographical data, which is
|
||||
made available under the Creative Commons Attribution 4.0 License. To view a copy of this
|
||||
license, visit https://creativecommons.org/licenses/by/4.0/.
|
15
go.mod
Normal file
15
go.mod
Normal file
@ -0,0 +1,15 @@
|
||||
module github.com/libretro/netplay-lobby-server-go
|
||||
|
||||
go 1.13
|
||||
|
||||
require (
|
||||
github.com/jinzhu/gorm v1.9.12
|
||||
github.com/labstack/echo/v4 v4.1.13
|
||||
github.com/labstack/gommon v0.3.0
|
||||
github.com/oschwald/geoip2-golang v1.4.0
|
||||
github.com/oschwald/maxminddb-golang v1.6.0
|
||||
github.com/spf13/viper v1.6.2
|
||||
github.com/stretchr/testify v1.4.0
|
||||
golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876
|
||||
rsc.io/quote v1.5.2
|
||||
)
|
214
go.sum
Normal file
214
go.sum
Normal file
@ -0,0 +1,214 @@
|
||||
cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/OneOfOne/xxhash v1.2.2/go.mod h1:HSdplMjZKSmBqAxg5vPj2TmRDmfkzw+cTzAElWljhcU=
|
||||
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/armon/consul-api v0.0.0-20180202201655-eb2c6b5be1b6/go.mod h1:grANhF5doyWs3UAsr3K4I6qtAmlQcZDesFNEHPZAzj8=
|
||||
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/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
|
||||
github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw=
|
||||
github.com/coreos/bbolt v1.3.2/go.mod h1:iRUV2dpdMOn7Bo10OQBFzIJO9kkE559Wcmn+qkEiiKk=
|
||||
github.com/coreos/etcd v3.3.10+incompatible/go.mod h1:uF7uidLiAD3TWHmW31ZFd/JWoc32PjwdhPthX9715RE=
|
||||
github.com/coreos/go-semver v0.2.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/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/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/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd h1:83Wprp6ROGeiHFAP8WJdI2RoxALQYgdllERc3N5N2DM=
|
||||
github.com/denisenkom/go-mssqldb v0.0.0-20191124224453-732737034ffd/go.mod h1:xbL0rPBG9cCiLr28tMa8zpbdarY27NDyej4t/EjAShU=
|
||||
github.com/dgrijalva/jwt-go v3.2.0+incompatible h1:7qlOGliEKZXTDg6OTjfoBKDXWrumCAMpl/TFQ4/5kLM=
|
||||
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/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5 h1:Yzb9+7DPaBjB8zlTR87/ElzFsnQfuHnVUVqpZZIcV5Y=
|
||||
github.com/erikstmartin/go-testdb v0.0.0-20160219214506-8d10e4a1bae5/go.mod h1:a2zkGnVExMxdzMo3M0Hi/3sEU+cWnZpSni0O6/Yb/P0=
|
||||
github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I=
|
||||
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-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-sql-driver/mysql v1.4.1 h1:g24URVg0OFbNUTx9qqY1IRZ9D9z3iPyi5zKhQZpNwpA=
|
||||
github.com/go-sql-driver/mysql v1.4.1/go.mod h1:zAC/RDZ24gD3HViQzih4MyKcchzm+sOG5ZlKdlhCg5w=
|
||||
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/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe h1:lXe2qZdvpiX5WZkZR4hgp4KJVfY3nMkvmwbVkpv1rVY=
|
||||
github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0=
|
||||
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/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A=
|
||||
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/google/btree v1.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
||||
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
|
||||
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/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||
github.com/jinzhu/gorm v1.9.12 h1:Drgk1clyWT9t9ERbzHza6Mj/8FY/CqMyVzOiHviMo6Q=
|
||||
github.com/jinzhu/gorm v1.9.12/go.mod h1:vhTjlKSJUTWNtcbQtrMBFCxy7eXTzeCAzfL5fBZT/Qs=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.0.1 h1:HjfetcXq097iXP0uoPCdnM4Efp5/9MsM0/M+XOTeR3M=
|
||||
github.com/jinzhu/now v1.0.1/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo=
|
||||
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/kisielk/errcheck v1.1.0/go.mod h1:EZBBE59ingxPouuu3KfxchcWSUPOHkagtvWXihfKN4Q=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
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/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/labstack/echo v3.3.10+incompatible h1:pGRcYk231ExFAyoAjAfD85kQzRJCRI8bbnE7CX5OEgg=
|
||||
github.com/labstack/echo v3.3.10+incompatible/go.mod h1:0INS7j/VjnFxD4E2wkz67b8cVwCLbBmJyDaka6Cmk1s=
|
||||
github.com/labstack/echo/v4 v4.1.13 h1:JYgKq6NQQSaKbQcsOadAKX1kUVLCUzLGwu8sxN5tC34=
|
||||
github.com/labstack/echo/v4 v4.1.13/go.mod h1:3WZNypykZ3tnqpF2Qb4fPg27XDunFqgP3HGDmCMgv7U=
|
||||
github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0=
|
||||
github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k=
|
||||
github.com/lib/pq v1.1.1 h1:sJZmqHoEaY7f+NPP8pgLB/WxulyR3fewgCM2qaSlBb4=
|
||||
github.com/lib/pq v1.1.1/go.mod h1:5WUZQaWbwv1U+lTReE5YruASi9Al49XbQIvNi/34Woo=
|
||||
github.com/magiconair/properties v1.8.1 h1:ZC2Vc7/ZFkGmsVC9KvOjumD+G5lXy2RtTKyzRKO2BQ4=
|
||||
github.com/magiconair/properties v1.8.1/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
||||
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
|
||||
github.com/mattn/go-colorable v0.1.4 h1:snbPLB8fVfU9iwbbo30TPtbLRzwWu6aJS6Xh4eaaviA=
|
||||
github.com/mattn/go-colorable v0.1.4/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
|
||||
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
github.com/mattn/go-isatty v0.0.9/go.mod h1:YNRxwqDuOph6SZLI9vUUz6OYw3QyUt7WiY2yME+cCiQ=
|
||||
github.com/mattn/go-isatty v0.0.11 h1:FxPOTFNqGkuDUGi3H/qkUbQO4ZiBa2brKq5r0l8TGeM=
|
||||
github.com/mattn/go-isatty v0.0.11/go.mod h1:PhnuNfih5lzO57/f3n+odYbM4JtupLOxQOAqxQCu2WE=
|
||||
github.com/mattn/go-sqlite3 v2.0.1+incompatible h1:xQ15muvnzGBHpIpdrNi1DA5x0+TcBZzsIDwmw9uTHzw=
|
||||
github.com/mattn/go-sqlite3 v2.0.1+incompatible/go.mod h1:FPy6KqzDD04eiIsT53CuJW3U88zkxoIYsOqkbpncsNc=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE=
|
||||
github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
|
||||
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/oschwald/geoip2-golang v1.4.0/go.mod h1:8QwxJvRImBH+Zl6Aa6MaIcs5YdlZSTKtzmPGzQqi9ng=
|
||||
github.com/oschwald/maxminddb-golang v1.6.0 h1:KAJSjdHQ8Kv45nFIbtoLGrGWqHFajOIm7skTyz/+Dls=
|
||||
github.com/oschwald/maxminddb-golang v1.6.0/go.mod h1:DUJFucBg2cvqx42YmDa/+xHvb0elJtOm3o4aFQ/nb/w=
|
||||
github.com/pelletier/go-toml v1.2.0 h1:T5zMGML61Wp+FlcbWjRDT7yAxhJNAiPPLOFECq181zc=
|
||||
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/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
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/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/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 h1:m8/z1t7/fwjysjQRYbP0RD+bUIF/8tJwPdEZsI83ACI=
|
||||
github.com/spf13/afero v1.1.2/go.mod h1:j4pytiNVoe2o6bmDsKpLACNPDBIoEAkihy7loJ1B0CQ=
|
||||
github.com/spf13/cast v1.3.0 h1:oget//CVOEoFewqQxwr0Ej5yjygnqGkvggSE/gB35Q8=
|
||||
github.com/spf13/cast v1.3.0/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
|
||||
github.com/spf13/jwalterweatherman v1.0.0 h1:XHEdyB+EcvlqZamSM4ZOMGlc93t6AcsBEu9Gc1vn7yk=
|
||||
github.com/spf13/jwalterweatherman v1.0.0/go.mod h1:cQK4TGJAtQXfYWX+Ddv3mKDzgVb68N+wFjFa4jdeBTo=
|
||||
github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
|
||||
github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
|
||||
github.com/spf13/viper v1.6.2 h1:7aKfF+e8/k68gda3LOjo5RxiUqddoFxVq4BKBPrxk5E=
|
||||
github.com/spf13/viper v1.6.2/go.mod h1:t3iDnF5Jlj76alVNuyFBk5oUMCvsrkbvZK0WQdfDi5k=
|
||||
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.1.1 h1:2vfRuCMp5sSVIDSqO8oNnWJq7mPa6KVP3iPIwFBuy8A=
|
||||
github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.4.0 h1:2E4SXV/wtOkTonXsotYi4li6zVWxYlZuYNCXe9XRJyk=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
|
||||
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/ugorji/go v1.1.4/go.mod h1:uQMGLiO92mf5W77hV/PUCpI3pbzQx3CRekS0kk+RGrc=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fasttemplate v1.0.1/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
|
||||
github.com/valyala/fasttemplate v1.1.0 h1:RZqt0yGBsps8NGvLSGW804QQqCUYYLsaOjTVHy1Ocw4=
|
||||
github.com/valyala/fasttemplate v1.1.0/go.mod h1:UQGH1tvbgY+Nz5t2n7tXsz52dQxojPUpymEIMZ47gx8=
|
||||
github.com/xiang90/probing v0.0.0-20190116061207-43a291ad63a2/go.mod h1:UETIi67q53MR2AWcXfiuqkDkRtnGDLqkBTpCHuJHxtU=
|
||||
github.com/xordataexchange/crypt v0.0.3-0.20170626215501-b2862e3d0a77/go.mod h1:aYKd//L2LvnjZzWKhF00oedf4jCCReLcmhLdhm1A27Q=
|
||||
go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
|
||||
go.uber.org/atomic v1.4.0/go.mod h1:gD2HeocX3+yG+ygLZcrzQJaqmWj9AIm7n08wl/qW/PE=
|
||||
go.uber.org/multierr v1.1.0/go.mod h1:wR5kodmAFQ0UK8QlbwjlSNy0Z68gJhDJUG5sjR94q/0=
|
||||
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-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20190325154230-a5d413f7728c/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd h1:GGJVjV8waZKRHrgwvtH66z9ZGVurTD1MT0n1Bb+q4aM=
|
||||
golang.org/x/crypto v0.0.0-20191205180655-e7c4368fe9dd/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876 h1:sKJQZMuxjOAR/Uo2LBfU90onWEf1dF4C+0hPJCc9Mpc=
|
||||
golang.org/x/crypto v0.0.0-20191227163750-53104e6ec876/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc=
|
||||
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-20181114220301-adae6a3d119a/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-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-20190522155817-f3200d17e092/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
|
||||
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553 h1:efeOvDhwQ29Dj3SdAV/MJf8oukgn+8D8WgaCaRMchF8=
|
||||
golang.org/x/net v0.0.0-20191209160850-c0dbc17a3553/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
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/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-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-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20190813064441-fde4db37ae7a/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191026070338-33540a1f6037/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191224085550-c709ea063b76 h1:Dho5nD6R3PcW2SH1or8vS0dszDaXRxIw55lBX7XiE5g=
|
||||
golang.org/x/sys v0.0.0-20191224085550-c709ea063b76/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8 h1:JA8d3MPx/IToSyXZG/RhwYEtfrKO1Fxrqe8KrkiLXKM=
|
||||
golang.org/x/sys v0.0.0-20191228213918-04cbcbbfeed8/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.2 h1:tW2bmiBqwgJj/UpqtC8EpXEZVYOwU0yG4iWbprSVAcs=
|
||||
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
|
||||
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-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
|
||||
google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508=
|
||||
google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4=
|
||||
google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
|
||||
google.golang.org/grpc v1.21.0/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
|
||||
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/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/ini.v1 v1.51.0 h1:AQvPpx3LzTDM0AjnIRlVFwFFGC+npRopjZxLJj6gdno=
|
||||
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 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.2.4 h1:/eiJrUcujPVeJ3xlSWaiNi3uSVmDGBK1pDHUHAnao1I=
|
||||
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
rsc.io/quote v1.5.2/go.mod h1:LzX7hefJvL54yjefDEDHNONDjII0t9xZLPXsUe+TKr0=
|
||||
rsc.io/sampler v1.3.0/go.mod h1:T1hPZKmBbMNahiBKFy5HrXp6adAjACjK9JXDnKaTXpA=
|
126
main.go
Normal file
126
main.go
Normal file
@ -0,0 +1,126 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/labstack/echo/v4"
|
||||
"github.com/labstack/echo/v4/middleware"
|
||||
"github.com/labstack/gommon/log"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"github.com/libretro/netplay-lobby-server-go/controller"
|
||||
"github.com/libretro/netplay-lobby-server-go/domain"
|
||||
"github.com/libretro/netplay-lobby-server-go/model"
|
||||
"github.com/libretro/netplay-lobby-server-go/model/entity"
|
||||
"github.com/libretro/netplay-lobby-server-go/model/repository"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var verbose = flag.Bool("v", false, "详细日志记录")
|
||||
flag.Parse()
|
||||
|
||||
server := echo.New()
|
||||
server.HideBanner = true
|
||||
server.Server.ReadTimeout = 5 * time.Second
|
||||
server.Server.WriteTimeout = 5 * time.Second
|
||||
|
||||
config, err := readConfig()
|
||||
if err != nil {
|
||||
server.Logger.Fatalf("无法获取配置值: %v", err)
|
||||
}
|
||||
|
||||
// 初始化领域逻辑和模型
|
||||
db, err := initDatabase(config.Database.Type, config.Database.Connection)
|
||||
if err != nil {
|
||||
server.Logger.Fatalf("无法初始化数据库: %v", err)
|
||||
}
|
||||
db = db.AutoMigrate(&entity.Session{})
|
||||
|
||||
if *verbose {
|
||||
server.Logger.SetLevel(log.INFO)
|
||||
} else {
|
||||
server.Logger.SetLevel(log.WARN)
|
||||
}
|
||||
|
||||
sessionDomain, err := initDomain(db, config)
|
||||
if err != nil {
|
||||
server.Logger.Fatalf("无法初始化领域逻辑: %v", err)
|
||||
}
|
||||
|
||||
sessionCotroller := controller.NewSessionController(sessionDomain)
|
||||
|
||||
// 启动清理作业以清除旧会话
|
||||
go func() {
|
||||
for true {
|
||||
err := sessionDomain.PurgeOld()
|
||||
if err != nil {
|
||||
server.Logger.Fatalf("无法清除旧会话: %v", err)
|
||||
}
|
||||
time.Sleep(2 * time.Minute)
|
||||
}
|
||||
}()
|
||||
|
||||
// 服务器设置
|
||||
server.Use(middleware.Logger())
|
||||
server.Use(middleware.Recover())
|
||||
server.Use(middleware.BodyLimit("64K"))
|
||||
|
||||
// 设置路由和预渲染模板
|
||||
sessionCotroller.RegisterRoutes(server)
|
||||
templatePath := fmt.Sprintf("%s/*.html", config.Server.TemplatePath)
|
||||
if err = sessionCotroller.PrerenderTemplates(server, templatePath); err != nil {
|
||||
server.Logger.Fatalf("无法预渲染模板: %v", err)
|
||||
}
|
||||
|
||||
// 开始服务
|
||||
server.Logger.Fatal(server.Start(config.Server.Address))
|
||||
}
|
||||
|
||||
func readConfig() (*Config, error) {
|
||||
viper := viper.New()
|
||||
viper.SetConfigName("lobby")
|
||||
viper.SetConfigType("yaml")
|
||||
viper.AddConfigPath("/etc/lobby")
|
||||
viper.AddConfigPath("$HOME/.lobby")
|
||||
viper.AddConfigPath("./config")
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
return nil, fmt.Errorf("无法读取配置文件: %w", err)
|
||||
}
|
||||
var conf Config
|
||||
if err := viper.Unmarshal(&conf); err != nil {
|
||||
return nil, fmt.Errorf("无法解组配置文件: %w", err)
|
||||
}
|
||||
return &conf, nil
|
||||
}
|
||||
|
||||
func initDatabase(databaseType string, connectionString string) (*gorm.DB, error) {
|
||||
switch databaseType {
|
||||
case "mysql":
|
||||
return model.GetMysqlDB(connectionString)
|
||||
case "postgres":
|
||||
return model.GetPostgreDB(connectionString)
|
||||
case "sqlite":
|
||||
return model.GetSqliteDB(connectionString)
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("配置中未知的数据库类型: %s", databaseType)
|
||||
}
|
||||
|
||||
func initDomain(db *gorm.DB, config *Config) (*domain.SessionDomain, error) {
|
||||
repo := repository.NewSessionRepository(db)
|
||||
geo2Domain, err := domain.NewGeoIP2Domain(config.Server.GeoLite2Path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("无法初始化 GeoLite2 数据库: %w", err)
|
||||
}
|
||||
validationDomain, err := domain.NewValidationDomain(config.Blacklist.Strings, config.Blacklist.IPs)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("无法初始化验证域: %w", err)
|
||||
}
|
||||
mitmDomain := domain.NewMitmDomain(config.Relay)
|
||||
sessionDomain := domain.NewSessionDomain(repo, geo2Domain, validationDomain, mitmDomain)
|
||||
|
||||
return sessionDomain, nil
|
||||
}
|
133
model/entity/session.go
Normal file
133
model/entity/session.go
Normal file
@ -0,0 +1,133 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/crypto/sha3"
|
||||
)
|
||||
|
||||
// HostMethod 是托管方法的枚举。
|
||||
type HostMethod int64
|
||||
|
||||
// HostMethod 的枚举值。
|
||||
const (
|
||||
HostMethodUnknown = 0
|
||||
HostMethodManual = 1
|
||||
HostMethodUPNP = 2
|
||||
HostMethodMITM = 3
|
||||
)
|
||||
|
||||
// Session 是 netplay 会话的数据库表示。
|
||||
type Session struct {
|
||||
ID string `json:"-" gorm:"primary_key;size:64"`
|
||||
ContentHash string `json:"-" gorm:"size:64"`
|
||||
RoomID int32 `json:"id" gorm:"AUTO_INCREMENT;unique_index"`
|
||||
Username string `json:"username"`
|
||||
Country string `json:"country" gorm:"size:2"`
|
||||
GameName string `json:"game_name"`
|
||||
GameCRC string `json:"game_crc"`
|
||||
CoreName string `json:"core_name"`
|
||||
CoreVersion string `json:"core_version"`
|
||||
SubsystemName string `json:"subsystem_name"`
|
||||
RetroArchVersion string `json:"retroarch_version"`
|
||||
Frontend string `json:"frontend"`
|
||||
IP net.IP `json:"ip" gorm:"not null"`
|
||||
Port uint16 `json:"port"`
|
||||
MitmHandle string `json:"-"`
|
||||
MitmAddress string `json:"mitm_ip"`
|
||||
MitmPort uint16 `json:"mitm_port"`
|
||||
MitmSession string `json:"mitm_session"`
|
||||
HostMethod HostMethod `json:"host_method"`
|
||||
HasPassword bool `json:"has_password"`
|
||||
HasSpectatePassword bool `json:"has_spectate_password"`
|
||||
Connectable bool `json:"connectable"`
|
||||
IsRetroArch bool `json:"is_retroarch"`
|
||||
CreatedAt time.Time `json:"created"`
|
||||
UpdatedAt time.Time `json:"updated" gorm:"index"`
|
||||
}
|
||||
|
||||
// CalculateID 创建一个 32 字节的 SHAKE256 (SHA3) 哈希值作为会话的数据库主键。
|
||||
func (s *Session) CalculateID() {
|
||||
hash := make([]byte, 32)
|
||||
shake := sha3.NewShake256()
|
||||
|
||||
shake.Write([]byte(s.Username))
|
||||
shake.Write([]byte(s.IP))
|
||||
shake.Write([]byte(strconv.FormatUint(uint64(s.Port), 10)))
|
||||
|
||||
shake.Read(hash)
|
||||
|
||||
s.ID = hex.EncodeToString(hash)
|
||||
}
|
||||
|
||||
// CalculateContentHash 创建一个 32 字节的 SHAKE256 (SHA3) 哈希值作为会话内容的哈希值。
|
||||
func (s *Session) CalculateContentHash() {
|
||||
hash := make([]byte, 32)
|
||||
shake := sha3.NewShake256()
|
||||
|
||||
shake.Write([]byte(s.Username))
|
||||
shake.Write([]byte(s.GameName))
|
||||
shake.Write([]byte(s.GameCRC))
|
||||
shake.Write([]byte(s.CoreName))
|
||||
shake.Write([]byte(s.CoreVersion))
|
||||
shake.Write([]byte(s.SubsystemName))
|
||||
shake.Write([]byte(s.RetroArchVersion))
|
||||
shake.Write([]byte(s.Frontend))
|
||||
shake.Write([]byte(s.IP))
|
||||
shake.Write([]byte(strconv.FormatUint(uint64(s.Port), 10)))
|
||||
shake.Write([]byte(strconv.FormatUint(uint64(s.HostMethod), 10)))
|
||||
shake.Write([]byte(s.MitmHandle))
|
||||
shake.Write([]byte(s.MitmSession))
|
||||
shake.Write([]byte(strconv.FormatBool(s.HasPassword)))
|
||||
shake.Write([]byte(strconv.FormatBool(s.HasSpectatePassword)))
|
||||
|
||||
shake.Read(hash)
|
||||
|
||||
s.ContentHash = hex.EncodeToString(hash)
|
||||
}
|
||||
|
||||
// PrintForRetroarch 以 retroarch 期望的格式打印会话信息。
|
||||
func (s *Session) PrintForRetroarch() string {
|
||||
var str string
|
||||
var hasPassword = 0
|
||||
var hasSpectatePassword = 0
|
||||
var connectable = 0
|
||||
|
||||
if s.HasPassword {
|
||||
hasPassword = 1
|
||||
}
|
||||
|
||||
if s.HasSpectatePassword {
|
||||
hasSpectatePassword = 1
|
||||
}
|
||||
|
||||
if s.Connectable {
|
||||
connectable = 1
|
||||
}
|
||||
|
||||
str += fmt.Sprintf("id=%d\nusername=%s\ncore_name=%s\ngame_name=%s\ngame_crc=%s\ncore_version=%s\nip=%s\nport=%d\nhost_method=%d\nhas_password=%d\nhas_spectate_password=%d\nretroarch_version=%s\nfrontend=%s\nsubsystem_name=%s\ncountry=%s\nconnectable=%d\n",
|
||||
s.RoomID,
|
||||
s.Username,
|
||||
s.CoreName,
|
||||
s.GameName,
|
||||
strings.ToUpper(s.GameCRC),
|
||||
s.CoreVersion,
|
||||
s.IP,
|
||||
s.Port,
|
||||
s.HostMethod,
|
||||
hasPassword,
|
||||
hasSpectatePassword,
|
||||
s.RetroArchVersion,
|
||||
s.Frontend,
|
||||
s.SubsystemName,
|
||||
strings.ToUpper(s.Country),
|
||||
connectable,
|
||||
)
|
||||
|
||||
return str
|
||||
}
|
122
model/entity/session_test.go
Normal file
122
model/entity/session_test.go
Normal file
@ -0,0 +1,122 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
var testSession = Session{
|
||||
ID: "",
|
||||
RoomID: 0,
|
||||
Username: "zelda",
|
||||
Country: "en",
|
||||
GameName: "supergame",
|
||||
GameCRC: "FFFFFFFF",
|
||||
CoreName: "unes",
|
||||
CoreVersion: "0.2.1",
|
||||
SubsystemName: "subsub",
|
||||
RetroArchVersion: "1.1.1",
|
||||
Frontend: "retro",
|
||||
IP: net.ParseIP("127.0.0.1"),
|
||||
Port: 55355,
|
||||
MitmHandle: "",
|
||||
MitmAddress: "",
|
||||
MitmPort: 0,
|
||||
MitmSession: "",
|
||||
HostMethod: HostMethodUPNP,
|
||||
HasPassword: false,
|
||||
HasSpectatePassword: false,
|
||||
Connectable: true,
|
||||
IsRetroArch: true,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
ContentHash: "",
|
||||
}
|
||||
|
||||
func TestSessionIDDoesNotChangeID(t *testing.T) {
|
||||
session := testSession
|
||||
session.CalculateID()
|
||||
oldHash := session.ID
|
||||
|
||||
session.ID = "CHANGED ID"
|
||||
session.CalculateID()
|
||||
newHash := session.ID
|
||||
|
||||
assert.Equal(t, oldHash, newHash)
|
||||
}
|
||||
|
||||
func TestSessionCreatedAtDoesNotChangeID(t *testing.T) {
|
||||
session := testSession
|
||||
session.CalculateID()
|
||||
oldHash := session.ID
|
||||
|
||||
session.CreatedAt = time.Now()
|
||||
session.CalculateID()
|
||||
newHash := session.ID
|
||||
|
||||
assert.Equal(t, oldHash, newHash)
|
||||
}
|
||||
|
||||
func TestSessionUpdatedAtDoesNotChangeID(t *testing.T) {
|
||||
session := testSession
|
||||
session.CalculateID()
|
||||
oldHash := session.ID
|
||||
|
||||
session.UpdatedAt = time.Now()
|
||||
session.CalculateID()
|
||||
newHash := session.ID
|
||||
|
||||
assert.Equal(t, oldHash, newHash)
|
||||
}
|
||||
|
||||
func TestSessionIDDoesNotChangeContentHash(t *testing.T) {
|
||||
session := testSession
|
||||
session.CalculateContentHash()
|
||||
oldHash := session.ContentHash
|
||||
|
||||
session.ID = "CHANGED ID"
|
||||
session.CalculateContentHash()
|
||||
newHash := session.ContentHash
|
||||
|
||||
assert.Equal(t, oldHash, newHash)
|
||||
}
|
||||
|
||||
func TestSessionCreatedAtDoesNotChangeContentHash(t *testing.T) {
|
||||
session := testSession
|
||||
session.CalculateContentHash()
|
||||
oldHash := session.ContentHash
|
||||
|
||||
session.CreatedAt = time.Now()
|
||||
session.CalculateContentHash()
|
||||
newHash := session.ContentHash
|
||||
|
||||
assert.Equal(t, oldHash, newHash)
|
||||
}
|
||||
|
||||
func TestSessionUpdatedAtDoesNotChangeContentHash(t *testing.T) {
|
||||
session := testSession
|
||||
session.CalculateContentHash()
|
||||
oldHash := session.ContentHash
|
||||
|
||||
session.UpdatedAt = time.Now()
|
||||
session.CalculateContentHash()
|
||||
newHash := session.ContentHash
|
||||
|
||||
assert.Equal(t, oldHash, newHash)
|
||||
}
|
||||
|
||||
func TestSessionHostMethodChangesContentHash(t *testing.T) {
|
||||
session := testSession
|
||||
session.CalculateContentHash()
|
||||
oldHash := session.ContentHash
|
||||
|
||||
session.HostMethod = HostMethodManual
|
||||
session.CalculateContentHash()
|
||||
newHash := session.ContentHash
|
||||
|
||||
assert.NotEqual(t, oldHash, newHash)
|
||||
}
|
11
model/mysql.go
Normal file
11
model/mysql.go
Normal file
@ -0,0 +1,11 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/jinzhu/gorm"
|
||||
_ "github.com/jinzhu/gorm/dialects/mysql"
|
||||
)
|
||||
|
||||
// GetMysqlDB returns a mysql interface using GORM.
|
||||
func GetMysqlDB(connection string) (*gorm.DB, error) {
|
||||
return gorm.Open("mysql", connection)
|
||||
}
|
11
model/postgres.go
Normal file
11
model/postgres.go
Normal file
@ -0,0 +1,11 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/jinzhu/gorm"
|
||||
_ "github.com/jinzhu/gorm/dialects/postgres"
|
||||
)
|
||||
|
||||
// GetPostgreDB returns a postgresql interface using GORM.
|
||||
func GetPostgreDB(connection string) (*gorm.DB, error) {
|
||||
return gorm.Open("postgres", connection)
|
||||
}
|
96
model/repository/sessionrepository.go
Normal file
96
model/repository/sessionrepository.go
Normal file
@ -0,0 +1,96 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jinzhu/gorm"
|
||||
|
||||
"github.com/libretro/netplay-lobby-server-go/model/entity"
|
||||
)
|
||||
|
||||
// SessionRepository 抽象了会话的数据库操作。
|
||||
type SessionRepository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
// NewSessionRepository 返回一个新的 SessionRepository。
|
||||
func NewSessionRepository(db *gorm.DB) *SessionRepository {
|
||||
return &SessionRepository{db}
|
||||
}
|
||||
|
||||
// GetAll 返回当前所有正在托管的会话。Deadline 用于过滤旧会话。零值的 Deadline 会停用此过滤器。
|
||||
func (r *SessionRepository) GetAll(deadline time.Time) ([]entity.Session, error) {
|
||||
var s []entity.Session
|
||||
if deadline.IsZero() {
|
||||
if err := r.db.Order("username").Find(&s).Error; err != nil {
|
||||
return nil, fmt.Errorf("无法查询所有会话: %w", err)
|
||||
}
|
||||
} else if err := r.db.Where("updated_at > ?", deadline).Order("username").Find(&s).Error; err != nil {
|
||||
return nil, fmt.Errorf("无法查询带有截止日期 %s 的所有会话: %w", deadline, err)
|
||||
}
|
||||
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// GetByID 返回具有给定 ID 的会话。如果找不到会话,则返回 nil。
|
||||
func (r *SessionRepository) GetByID(id string) (*entity.Session, error) {
|
||||
var s entity.Session
|
||||
if err := r.db.Where("id = ?", id).First(&s).Error; err != nil {
|
||||
if gorm.IsRecordNotFoundError(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("无法查询 ID 为 %s 的会话: %w", id, err)
|
||||
}
|
||||
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
// GetByRoomID 返回具有给定 RoomID 的会话。如果找不到会话,则返回 nil。
|
||||
func (r *SessionRepository) GetByRoomID(id int32) (*entity.Session, error) {
|
||||
var s entity.Session
|
||||
if err := r.db.Where("room_id = ?", id).First(&s).Error; err != nil {
|
||||
if gorm.IsRecordNotFoundError(err) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("无法查询 RoomID 为 %d 的会话: %w", id, err)
|
||||
}
|
||||
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
// Create 创建一个新的会话。
|
||||
func (r *SessionRepository) Create(s *entity.Session) error {
|
||||
if err := r.db.Create(s).Error; err != nil {
|
||||
return fmt.Errorf("无法创建会话 %v: %w", s, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Update 更新一个会话。
|
||||
func (r *SessionRepository) Update(s *entity.Session) error {
|
||||
if err := r.db.Model(&s).Save(&s).Error; err != nil {
|
||||
return fmt.Errorf("无法更新会话 %v: %w", s, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Touch 更新 UpdatedAt 时间戳。
|
||||
func (r *SessionRepository) Touch(id string) error {
|
||||
if err := r.db.Model(&entity.Session{}).Where("id = ?", id).Update("updated_at", time.Now()).Error; err != nil {
|
||||
return fmt.Errorf("无法触碰 ID 为 %s 的会话: %w", id, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// PurgeOld 清除所有早于给定时间戳的会话。
|
||||
func (r *SessionRepository) PurgeOld(deadline time.Time) error {
|
||||
if err := r.db.Where("updated_at < ?", deadline).Delete(entity.Session{}).Error; err != nil {
|
||||
return fmt.Errorf("无法删除旧会话: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
261
model/repository/sessionrepository_test.go
Normal file
261
model/repository/sessionrepository_test.go
Normal file
@ -0,0 +1,261 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/libretro/netplay-lobby-server-go/model"
|
||||
"github.com/libretro/netplay-lobby-server-go/model/entity"
|
||||
)
|
||||
|
||||
var testSession = entity.Session{
|
||||
ID: "",
|
||||
RoomID: 0,
|
||||
Username: "zelda",
|
||||
Country: "en",
|
||||
GameName: "supergame",
|
||||
GameCRC: "FFFFFFFF",
|
||||
CoreName: "unes",
|
||||
CoreVersion: "0.2.1",
|
||||
SubsystemName: "subsub",
|
||||
RetroArchVersion: "1.1.1",
|
||||
Frontend: "retro",
|
||||
IP: net.ParseIP("127.0.0.1"),
|
||||
Port: 55355,
|
||||
MitmAddress: "",
|
||||
MitmPort: 0,
|
||||
MitmSession "",
|
||||
HostMethod: entity.HostMethodUPNP,
|
||||
HasPassword: false,
|
||||
HasSpectatePassword: false,
|
||||
Connectable: true,
|
||||
IsRetroArch: true,
|
||||
CreatedAt: time.Now(),
|
||||
UpdatedAt: time.Now(),
|
||||
ContentHash: "",
|
||||
}
|
||||
|
||||
func setupSessionRepository(t *testing.T) *SessionRepository {
|
||||
db, err := model.GetSqliteDB(":memory:")
|
||||
//db = db.LogMode(true)
|
||||
if err != nil {
|
||||
t.Fatalf("Can't open sqlite3 db: %v", err)
|
||||
}
|
||||
db.AutoMigrate(entity.Session{})
|
||||
|
||||
return NewSessionRepository(db)
|
||||
}
|
||||
|
||||
func TestSessionRepositoryCreate(t *testing.T) {
|
||||
sessionRepository := setupSessionRepository(t)
|
||||
session := testSession
|
||||
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
err := sessionRepository.Create(&session)
|
||||
require.NoError(t, err, "Can't create session")
|
||||
}
|
||||
|
||||
func TestSessionRepositoryCreateIPNotNull(t *testing.T) {
|
||||
sessionRepository := setupSessionRepository(t)
|
||||
session := testSession
|
||||
|
||||
session.IP = nil
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
err := sessionRepository.Create(&session)
|
||||
require.Error(t, err, "Should not be able to create nil value for IP")
|
||||
}
|
||||
|
||||
func TestSessionRepositoryGetByID(t *testing.T) {
|
||||
sessionRepository := setupSessionRepository(t)
|
||||
session := testSession
|
||||
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
err := sessionRepository.Create(&session)
|
||||
require.NoError(t, err, "Can't create session")
|
||||
|
||||
newSession, err := sessionRepository.GetByID(session.ID)
|
||||
require.NoError(t, err, "Can't get session by ID")
|
||||
|
||||
require.NotNil(t, newSession)
|
||||
|
||||
assert.NotEmpty(t, newSession.ID)
|
||||
assert.NotEmpty(t, newSession.ContentHash)
|
||||
|
||||
assert.NotEqual(t, session.CreatedAt, newSession.CreatedAt)
|
||||
assert.NotEqual(t, session.UpdatedAt, newSession.UpdatedAt)
|
||||
|
||||
// Make sure the rest is the same
|
||||
session.CreatedAt = newSession.CreatedAt
|
||||
session.UpdatedAt = newSession.UpdatedAt
|
||||
assert.Equal(t, &session, newSession)
|
||||
|
||||
noSession, err := sessionRepository.GetByID("should_not_exists")
|
||||
require.NoError(t, err, "Can't get nil session")
|
||||
assert.Nil(t, noSession)
|
||||
}
|
||||
|
||||
func TestSessionRepositoryGetByRoomID(t *testing.T) {
|
||||
sessionRepository := setupSessionRepository(t)
|
||||
session := testSession
|
||||
|
||||
session.RoomID = 400
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
err := sessionRepository.Create(&session)
|
||||
require.NoError(t, err, "Can't create session")
|
||||
|
||||
newSession, err := sessionRepository.GetByRoomID(session.RoomID)
|
||||
require.NoError(t, err, "Can't get session by RoomID")
|
||||
|
||||
require.NotNil(t, newSession)
|
||||
|
||||
assert.NotEmpty(t, newSession.ID)
|
||||
assert.NotEmpty(t, newSession.ContentHash)
|
||||
|
||||
assert.NotEqual(t, session.CreatedAt, newSession.CreatedAt)
|
||||
assert.NotEqual(t, session.UpdatedAt, newSession.UpdatedAt)
|
||||
|
||||
// Make sure the rest is the same
|
||||
session.CreatedAt = newSession.CreatedAt
|
||||
session.UpdatedAt = newSession.UpdatedAt
|
||||
assert.Equal(t, &session, newSession)
|
||||
|
||||
noSession, err := sessionRepository.GetByID("should_not_exists")
|
||||
require.NoError(t, err, "Can't get nil session")
|
||||
assert.Nil(t, noSession)
|
||||
}
|
||||
|
||||
func TestSessionRepositoryGetAll(t *testing.T) {
|
||||
sessionRepository := setupSessionRepository(t)
|
||||
session := testSession
|
||||
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
session.RoomID = 0
|
||||
err := sessionRepository.Create(&session)
|
||||
require.NoError(t, err, "Can't create session")
|
||||
|
||||
session.Username = "aladin"
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
session.RoomID = 0
|
||||
err = sessionRepository.Create(&session)
|
||||
require.NoError(t, err, "Can't create session")
|
||||
|
||||
session.Username = "invalid"
|
||||
session.UpdatedAt = time.Now().Add(-2 * time.Minute)
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
session.RoomID = 0
|
||||
err = sessionRepository.Create(&session)
|
||||
require.NoError(t, err, "Can't create session")
|
||||
|
||||
deadline := time.Now().Add(-1 * time.Minute)
|
||||
sessions, err := sessionRepository.GetAll(deadline)
|
||||
require.NoError(t, err, "Can't get all sessions with deadline")
|
||||
|
||||
require.NotNil(t, sessions)
|
||||
require.Equal(t, 2, len(sessions), "Query seems to include non valid entries.")
|
||||
assert.Less(t, sessions[0].Username, sessions[1].Username, "Sessions are not ordered by username")
|
||||
|
||||
sessions, err = sessionRepository.GetAll(time.Time{})
|
||||
require.NoError(t, err, "Can't get all sessions without deadline")
|
||||
|
||||
require.NotNil(t, sessions)
|
||||
require.Equal(t, 3, len(sessions), "Query seems to not include invalid entries.")
|
||||
assert.Less(t, sessions[0].Username, sessions[1].Username, "Sessions are not ordered by username")
|
||||
assert.Less(t, sessions[1].Username, sessions[2].Username, "Sessions are not ordered by username")
|
||||
}
|
||||
|
||||
func TestSessionRepositoryUpdate(t *testing.T) {
|
||||
sessionRepository := setupSessionRepository(t)
|
||||
session := testSession
|
||||
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
err := sessionRepository.Create(&session)
|
||||
require.NoError(t, err, "Can't create session")
|
||||
|
||||
newIP := "83.12.41.222"
|
||||
session.MitmAddress = newIP
|
||||
|
||||
session.CalculateContentHash()
|
||||
err = sessionRepository.Update(&session)
|
||||
require.NoError(t, err, "Can't update session")
|
||||
|
||||
newSession, err := sessionRepository.GetByID(session.ID)
|
||||
require.NoError(t, err, "Can't get session by ID")
|
||||
|
||||
require.NotNil(t, newSession)
|
||||
assert.Equal(t, newSession.MitmAddress, newIP)
|
||||
}
|
||||
|
||||
func TestSessionRepositoryTouch(t *testing.T) {
|
||||
sessionRepository := setupSessionRepository(t)
|
||||
session := testSession
|
||||
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
err := sessionRepository.Create(&session)
|
||||
require.NoError(t, err, "Can't create session")
|
||||
|
||||
oldSession, err := sessionRepository.GetByID(session.ID)
|
||||
require.NoError(t, err, "Can't get session by ID")
|
||||
|
||||
oldTimestamp := oldSession.UpdatedAt
|
||||
|
||||
err = sessionRepository.Touch(oldSession.ID)
|
||||
require.NoError(t, err, "Can't touch session")
|
||||
|
||||
newSession, err := sessionRepository.GetByID(session.ID)
|
||||
require.NoError(t, err, "Can't get session by ID")
|
||||
|
||||
require.NotNil(t, newSession)
|
||||
assert.False(t, newSession.UpdatedAt.Equal(oldTimestamp), "New timestamp did not change after touch")
|
||||
assert.True(t, newSession.UpdatedAt.After(oldTimestamp), "New timestamp is not older after touch")
|
||||
|
||||
assert.Equal(t, oldSession.ContentHash, newSession.ContentHash)
|
||||
}
|
||||
|
||||
func TestSessionRepositoryPurgeOld(t *testing.T) {
|
||||
sessionRepository := setupSessionRepository(t)
|
||||
session := testSession
|
||||
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
session.RoomID = 0
|
||||
err := sessionRepository.Create(&session)
|
||||
require.NoError(t, err, "Can't create session")
|
||||
|
||||
session.Username = "aladin"
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
session.RoomID = 0
|
||||
err = sessionRepository.Create(&session)
|
||||
require.NoError(t, err, "Can't create session")
|
||||
|
||||
session.Username = "invalid"
|
||||
session.UpdatedAt = time.Now().Add(-2 * time.Minute)
|
||||
session.CalculateID()
|
||||
session.CalculateContentHash()
|
||||
session.RoomID = 0
|
||||
err = sessionRepository.Create(&session)
|
||||
require.NoError(t, err, "Can't create session")
|
||||
|
||||
deadline := time.Now().Add(-1 * time.Minute)
|
||||
err = sessionRepository.PurgeOld(deadline)
|
||||
require.NoError(t, err, "Can't purge old sessions")
|
||||
|
||||
sessions, err := sessionRepository.GetAll(time.Time{})
|
||||
require.NoError(t, err, "Can't get all sessions")
|
||||
|
||||
require.NotNil(t, sessions)
|
||||
require.Equal(t, len(sessions), 2, "Query seems to include non valid entries.")
|
||||
}
|
12
model/sqlite.go
Normal file
12
model/sqlite.go
Normal file
@ -0,0 +1,12 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"github.com/jinzhu/gorm"
|
||||
_ "github.com/jinzhu/gorm/dialects/sqlite"
|
||||
)
|
||||
|
||||
// GetSqliteDB returns a sqlite3 interface using GORM.
|
||||
// A filepath of ":memory:" provides a in memory database.
|
||||
func GetSqliteDB(connection string) (*gorm.DB, error) {
|
||||
return gorm.Open("sqlite3", connection)
|
||||
}
|
BIN
netplay-lobby-server-go
Normal file
BIN
netplay-lobby-server-go
Normal file
Binary file not shown.
BIN
netplay-lobby-server-go.exe
Normal file
BIN
netplay-lobby-server-go.exe
Normal file
Binary file not shown.
15
netplay-lobby-server-go.service
Normal file
15
netplay-lobby-server-go.service
Normal file
@ -0,0 +1,15 @@
|
||||
[Unit]
|
||||
Description=RetroArch lobby server
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
ExecStart=/home/lobby/netplay-lobby-server-go/netplay-lobby-server-go -v
|
||||
KillMode=process
|
||||
Restart=always
|
||||
RestartSec=5
|
||||
Type=simple
|
||||
User=lobby
|
||||
Group=lobby
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
59
web/templates/index.html
Normal file
59
web/templates/index.html
Normal file
@ -0,0 +1,59 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>RetroArch 大厅</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
|
||||
<link rel="icon" href="https://www.libretro.com/wp-content/uploads/2016/01/ic_launcher.png" sizes="32x32"/>
|
||||
<link rel="icon" href="https://www.libretro.com/wp-content/uploads/2016/01/ic_launcher.png" sizes="192x192"/>
|
||||
<link rel="apple-touch-icon-precomposed" href="https://www.libretro.com/wp-content/uploads/2016/01/ic_launcher.png"/>
|
||||
</head>
|
||||
<body>
|
||||
<div class="container">
|
||||
<div>
|
||||
<h1>RetroArch 大厅</h1>
|
||||
<p>当前在 <a href="http://libretro.com">RetroArch</a> 中可用的联网游戏房间。</p>
|
||||
<hr class="my-4">
|
||||
<p class="lead">
|
||||
<a class="btn btn-primary btn-lg"
|
||||
href="https://www.libretro.com/" role="button">RetroArch</a>
|
||||
<a class="btn btn-info btn-lg"
|
||||
href="https://www.youtube.com/watch?v=oh7hhoOBg54" role="button">如何加入</a>
|
||||
<a class="btn btn-info btn-lg"
|
||||
href="https://www.youtube.com/watch?v=n6aF0wNcm7E" role="button">如何做主机</a>
|
||||
</p>
|
||||
</div>
|
||||
{{ if . }}
|
||||
<table class="table"><thead><tr>
|
||||
<th></th><th>别名</th><th>游戏</th><th>积分</th><th>是否公开</th><th>版本</th><th>创建时间</th>
|
||||
</tr></thead><tbody>
|
||||
{{ range $key, $session := . }}
|
||||
<tr>
|
||||
{{ if $session.Country }}<td><img height="25" title="{{ $session.Country }}" alt="{{ $session.Country }}" src="https://cdnjs.cloudflare.com/ajax/libs/flag-icon-css/3.4.3/flags/1x1/{{ $session.Country }}.svg"></td>{{ else }}<td></td>{{ end }}
|
||||
<th>{{ $session.Username }}</th>
|
||||
<td>{{ $session.GameName }}</td>
|
||||
<td>{{ $session.CoreName }} {{ $session.CoreVersion }}</td>
|
||||
<td>{{ prettyBool $session.HasPassword }}</td>
|
||||
{{ if $session.RetroArchVersion }}
|
||||
<td>{{ $session.RetroArchVersion }}</td>
|
||||
{{ else }}
|
||||
<td>n/a</td>
|
||||
{{ end }}
|
||||
<td>{{ prettyDate $session.CreatedAt }}</td>
|
||||
</tr>
|
||||
{{ end }}
|
||||
</tbody></table>
|
||||
{{ else }}
|
||||
<div class="alert alert-info" role="alert">当前没有开放的大厅。</div>
|
||||
{{ end }}
|
||||
<div class="alert alert-dark" role="alert">
|
||||
此服务器根据 AGPLv3 许可证授权。源代码可以在 <a href="https://github.com/libretro/netplay-lobby-server-go">github</a> 上找到。</br>
|
||||
本产品包含由 <a href="https://www.maxmind.com">MaxMind</a> 创建的 GeoLite2 数据。
|
||||
</div>
|
||||
</div>
|
||||
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
|
||||
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
|
||||
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
|
||||
</body>
|
||||
</html>
|
Loading…
Reference in New Issue
Block a user