Compare commits

...

65 Commits

Author SHA1 Message Date
junleea 80352e8601 修改权限部分实现 2025-10-18 22:50:05 +08:00
junleea 99dda61a84 修改权限部分实现 2025-10-18 22:45:13 +08:00
junleea 08c0752803 修改权限部分实现 2025-10-18 22:40:02 +08:00
junleea ed2b936bf2 修改权限部分实现 2025-10-18 22:35:02 +08:00
junleea 6d7e6c26fc get cid list时间排序 2025-10-14 21:28:19 +08:00
junleea 3d0253523b dbm的死锁问题 2025-10-14 19:40:22 +08:00
junleea 76b6ec7d74 Merge branch 'refs/heads/feat-cid-run-list' into release 2025-10-03 21:13:08 +08:00
junleea 4bc256aba4 修复数据库连接指针问题 2025-10-03 21:13:02 +08:00
junleea 6481b18fcd Merge branch 'refs/heads/feat-cid-run-list' into release 2025-10-02 21:39:51 +08:00
junleea 63ea13bbde 修改获取sql db连接逻辑 2025-10-02 21:39:45 +08:00
junleea dda5035c7c Merge branch 'refs/heads/feat-cid-run-list' into release 2025-10-02 21:34:10 +08:00
junleea 7be4aeb90e 修改获取sql db连接逻辑 2025-10-02 21:33:59 +08:00
junleea 00aa3b5b7b Merge branch 'refs/heads/feat-cid-run-list' into release 2025-10-02 21:33:04 +08:00
junleea dae8a96478 修改获取sql db连接逻辑 2025-10-02 21:32:57 +08:00
junleea fc0218e754 Merge branch 'refs/heads/feat-cid-run-list' into release 2025-10-02 21:30:16 +08:00
junleea 770cde41bd 修改获取sql db连接逻辑 2025-10-02 21:30:08 +08:00
junleea da70405ab3 Merge branch 'refs/heads/feat-cid-run-list' into release 2025-10-02 21:25:19 +08:00
junleea c75dd8b95e 对cid运行添加上次成功失败信息 2025-10-02 21:25:11 +08:00
junleea 1a2661bf41 Merge branch 'refs/heads/feat-cid-run-list' into release 2025-09-28 20:41:24 +08:00
junleea 106e27f457 对cid运行添加上次成功失败信息 2025-09-28 20:41:15 +08:00
junleea 345d120460 Merge remote-tracking branch 'origin/release' into release 2025-09-20 14:22:51 +08:00
junleea 0edba050c3 修改cid回调接口 2025-09-20 14:21:32 +08:00
junleea d02cceb775 修改cid回调接口 2025-09-20 14:20:19 +08:00
junleea f334668e4b 添加cid正在运行及获取正在运行接口 2025-09-20 14:10:04 +08:00
junleea b4f721060f 添加自定义memorycache 2025-09-16 20:02:41 +08:00
junleea c0b8c7ba63 添加自定义memorycache 2025-09-13 13:49:20 +08:00
junleea 2f8d80184b
update pipeline-20250906-release.yml 2025-09-09 13:51:17 +00:00
junleea ff3e032d6d Merge branch 'refs/heads/feat-db-manager' into release 2025-09-09 20:45:19 +08:00
junleea defbafd9d6 添加dbm的缓存及清理机制 2025-09-09 20:45:04 +08:00
junleea 27c5b3cd3c Merge branch 'refs/heads/feat-db-manager' into release 2025-09-08 20:10:53 +08:00
junleea 5e184badca 修复获取db执行历史,添加sqlite数据库支持 2025-09-08 20:10:42 +08:00
junleea b3492e6826 Merge branch 'release' of https://gitee.com/junleea/videoplayer into release 2025-09-06 14:44:25 +08:00
junleea 44b74e468b 修改配置写入 2025-09-06 14:42:49 +08:00
junleea 4e2f319229
update pipeline-20250906-release.yml 2025-09-06 06:31:13 +00:00
junleea 94e5c784c0
create pipeline-20250906-release.yml 2025-09-06 06:28:10 +00:00
junleea b1bb1cb734 添加下载代理接口 2025-09-06 14:01:34 +08:00
junleea e2ebdc0621 添加下载代理接口 2025-09-06 13:54:12 +08:00
junleea f0e025bec5 设备监控状态异常邮箱修改成配置文件读取 2025-09-03 20:44:43 +08:00
junleea 6e5ee4f0e2 设备监控状态异常邮箱修改成配置文件读取 2025-09-03 20:38:06 +08:00
junleea 4592681978 设备监控状态异常邮箱修改成配置文件读取 2025-09-03 20:37:12 +08:00
junleea 80ab607432 添加备注信息添加修改 2025-08-22 22:08:35 +08:00
junleea 1ff1347187 添加删除接口,修改运行sql返回数据结构 2025-08-22 20:43:25 +08:00
junleea 1244feb7de 添加删除接口,修改运行sql返回数据结构 2025-08-21 21:47:51 +08:00
junleea 6c835e371a 添加删除接口,修改运行sql返回数据结构 2025-08-21 21:46:52 +08:00
junleea 1cfb517fc9 添加删除接口,修改运行sql返回数据结构 2025-08-21 21:46:29 +08:00
junleea 29c05b0af7 支持保存顺序 2025-08-20 22:28:36 +08:00
junleea 96e1a96f2e 修复数据库接口问题 2025-08-20 20:59:34 +08:00
junleea 7844e5b121 添加数据库管理接口 2025-08-19 22:43:31 +08:00
junleea c3170ddcb2 Merge branch 'refs/heads/feat-sync-secret' into release 2025-08-10 14:05:37 +08:00
junleea 1d698dd28a 设置密钥无效返回 2025-08-10 14:01:45 +08:00
junleea 11255c71a6 设置密钥无效返回 2025-08-10 13:59:43 +08:00
junleea 8a48a54c3a Merge branch 'refs/heads/feat-shell-runtime' into release 2025-08-07 20:28:43 +08:00
junleea f3c1ee923a 修复日志输出 2025-08-07 20:28:32 +08:00
junleea 0c6143086d Merge branch 'refs/heads/feat-sync-secret' into release 2025-08-07 20:22:13 +08:00
junleea 95539fbd35 修复日志输出 2025-08-07 20:21:58 +08:00
junleea 790d6b75a6 Merge branch 'refs/heads/feat-shell-runtime' into release 2025-08-07 20:01:12 +08:00
junleea 4dacd672b7 修改shell运行时间 2025-08-07 20:01:01 +08:00
junleea 2e807710bc 修改初始无配置默认配置写入问题 2025-08-04 21:06:44 +08:00
junleea 7991fd2960 Merge remote-tracking branch 'origin/release' into release 2025-08-03 17:15:36 +08:00
junleea fb1752b9d7 修改shell运行时间及部分bug修复 2025-08-03 17:14:51 +08:00
junleea 3651c31a15
add LICENSE.
Signed-off-by: junleea <354425203@qq.com>
2025-08-02 08:21:28 +00:00
junleea 301817c353 修改配置读取 2025-08-02 15:49:35 +08:00
junleea e1e7e53590 修复密钥同步问题 2025-08-02 15:39:32 +08:00
junleea 68e0ee27f2 添加APP_ID生成 2025-08-01 20:41:22 +08:00
junleea a9a9ecc3bd 添加密钥同步 2025-07-31 21:03:49 +08:00
27 changed files with 2479 additions and 138 deletions

View File

@ -0,0 +1,35 @@
version: '1.0'
name: pipeline-20250906-release
displayName: pipeline-20250906-release
triggers:
trigger: auto
push:
branches:
precise:
- release
stages:
- name: stage-4863fcf5
displayName: 未命名
strategy: naturally
trigger: auto
executor: []
steps:
- step: build@golang
name: build_golang
displayName: Golang 构建
golangVersion: '1.24'
commands:
- '# 默认使用goproxy.cn'
- export GOPROXY=https://goproxy.cn
- '# 输入你的构建命令'
- go get
- go build
artifacts:
- name: BUILD_ARTIFACT
path:
- ./
caches:
- /go/pkg/mod
notify: []
strategy:
retry: '0'

661
LICENSE Normal file
View 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/>.

View File

@ -3,16 +3,19 @@ package dao
import (
"fmt"
"gorm.io/gorm"
"time"
)
type CID struct {
gorm.Model
Auth_id int `gorm:"column:auth_id"`
Name string `gorm:"column:name"`
Url string `gorm:"column:url"`
Time int `gorm:"column:time"` // 定时任务单位秒大于0表示定时任务
Script string `gorm:"column:script"`
Token string `gorm:"column:token"` // 用于外部回调
Auth_id int `gorm:"column:auth_id"`
Name string `gorm:"column:name"`
Url string `gorm:"column:url"`
Time int `gorm:"column:time"` // 定时任务单位秒大于0表示定时任务
LastSuccess time.Time `gorm:"column:last_success" json:"last_success"`
LastFail time.Time `gorm:"column:last_fail" json:"last_fail"`
Script string `gorm:"column:script"`
Token string `gorm:"column:token"` // 用于外部回调
}
type CIDRunLog struct {
@ -54,7 +57,7 @@ func FindCIDByID(id, auth_id int) CID {
// FindCIDByAuthID 查找持续集成、部署
func FindCIDByAuthID(auth_id int) []CID {
var cids []CID
DB.Where("auth_id = ?", auth_id).Find(&cids)
DB.Where("auth_id = ?", auth_id).Order("created_at").Find(&cids)
return cids
}
@ -121,3 +124,13 @@ func FindCIDByCID(id uint) CID {
DB.Where("id = ? ", id).First(&cid)
return cid
}
func UpdateLastSuccessByID(id int, time time.Time) error {
res := DB.Where("id = ?", id).Update("last_success", time)
return res.Error
}
func UpdateLastFailByID(id int, time time.Time) error {
res := DB.Where("id = ?", id).Update("last_fail", time)
return res.Error
}

View File

@ -4,12 +4,18 @@ import (
"fmt"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"log"
"sync"
"videoplayer/proto"
)
var DB *gorm.DB
var DBMMap = map[uint]*proto.DBValue{}
var DBMMapRWMutex = &sync.RWMutex{} //dbm日志
func Init() error {
var db *gorm.DB
var err error
@ -20,17 +26,20 @@ func Init() error {
} else if proto.Config.DB == 1 {
dsn = proto.Config.PG_DSN
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
} else if proto.Config.DB == 2 { //sqlite
dsn = proto.Config.SQLITE_FILE
db, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{})
}
if err != nil {
panic("failed to connect database")
return err
}
err = db.AutoMigrate(&User{})
if err != nil {
fmt.Println("user table:", err)
return err
} // 自动迁移,创建表,如果表已经存在,会自动更新表结构,不会删除表,只会创建不存在的表
//err = db.AutoMigrate(&User{})
//if err != nil {
// fmt.Println("user table:", err)
// return err
//}
err = db.AutoMigrate(&Video{})
if err != nil {
fmt.Println("video table:", err)
@ -104,6 +113,15 @@ func Init() error {
fmt.Println("shell table:", err)
}
err = db.AutoMigrate(&proto.DBManage{})
if err != nil {
log.Println("dbmanage table:", err)
}
err = db.AutoMigrate(&proto.SQLRunHistory{})
if err != nil {
log.Println("sqlrunhistory table:", err)
}
DB = db
return err
}

261
dao/dbm.go Normal file
View File

@ -0,0 +1,261 @@
package dao
import (
"gorm.io/gorm"
"videoplayer/proto"
)
func CreateDBManage(db_info proto.DBManage) (uint, error) {
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Create(&db_info)
if res.Error != nil {
return 0, res.Error
}
return db_info.ID, nil
}
func CreateDBRunHistory(history *proto.SQLRunHistory) (uint, error) {
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Create(history)
if res.Error != nil {
return 0, res.Error
}
return history.ID, nil
}
func RunSQL(sql string, db_ *gorm.DB) (res []map[string]interface{}, err error) {
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = db_.Debug()
} else {
db2 = db_
}
err = db2.Raw(sql).Scan(&res).Error
return res, err
}
func FindDBManageByID(id uint) (proto.DBManage, error) {
var db_info proto.DBManage
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Where("id = ?", id).First(&db_info)
if res.Error != nil {
return proto.DBManage{}, res.Error
}
return db_info, nil
}
func FindDBManageByAuthID(auth_id uint) ([]proto.DBManage, error) {
var db_infos []proto.DBManage
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Where("user_id = ?", auth_id).Find(&db_infos)
if res.Error != nil {
return nil, res.Error
}
return db_infos, nil
}
func FindAllDBManage() ([]proto.DBManage, error) {
var db_infos []proto.DBManage
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Find(&db_infos)
if res.Error != nil {
return nil, res.Error
}
return db_infos, nil
}
func UpdateDBManage(id uint, db_info *proto.DBManage) error {
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Model(&proto.DBManage{}).Where("id = ?", id).Updates(db_info)
return res.Error
}
func DeleteDBManageByID(id uint) error {
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Where("id = ?", id).Delete(&proto.DBManage{})
return res.Error
}
func DeleteDBManageByUserID(id uint) error {
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Where("user_id = ?", id).Delete(&proto.DBManage{})
return res.Error
}
func FindDBRunHistoryByID(id uint) (proto.SQLRunHistory, error) {
var history proto.SQLRunHistory
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Where("id = ?", id).First(&history)
if res.Error != nil {
return proto.SQLRunHistory{}, res.Error
}
return history, nil
}
func FindDBRunHistoryByAuthID(auth_id int) ([]proto.SQLRunHistory, error) {
var histories []proto.SQLRunHistory
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Where("user_id = ?", auth_id).Find(&histories)
if res.Error != nil {
return nil, res.Error
}
return histories, nil
}
func FindDBRunHistoryByAuthIDAndDbId(auth_id int, db_id uint) ([]proto.SQLRunHistory, error) {
var histories []proto.SQLRunHistory
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Where("user_id = ? and db_id = ?", auth_id, db_id).Find(&histories)
if res.Error != nil {
return nil, res.Error
}
return histories, nil
}
func DelSQLRunHistoryByID(id uint) error {
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Where("id = ?", id).Delete(&proto.SQLRunHistory{})
return res.Error
}
func DelSQLRunHistoryByAuthID(auth_id int) error {
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Where("user_id = ?", auth_id).Delete(&proto.SQLRunHistory{})
return res.Error
}
func FindAllSQLRunHistory() ([]proto.SQLRunHistory, error) {
var histories []proto.SQLRunHistory
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
db2 = DB.Debug()
} else {
db2 = DB
}
res := db2.Find(&histories)
if res.Error != nil {
return nil, res.Error
}
return histories, nil
}
func RunSQLWithOrder(sql string, db_ *gorm.DB) (result proto.SQLResult, err error) {
var db2 *gorm.DB
// 保留 Debug 模式
if proto.Config.SERVER_SQL_LOG {
db2 = db_.Debug()
} else {
db2 = db_
}
// 执行 SQL 并获取底层 Rows 对象
rows, err := db2.Raw(sql).Rows()
if err != nil {
return result, err
}
defer rows.Close() // 确保关闭 Rows
// 获取列名顺序(关键:这里的顺序与 SQL 查询的列顺序一致)
columns, err := rows.Columns()
if err != nil {
return result, err
}
for _, col := range columns {
result.Columns = append(result.Columns, proto.SQLResultColumnsValue{Prop: col, Label: col})
}
// 遍历每行数据
for rows.Next() {
// 准备接收每行数据的容器(按列顺序)
values := make([]interface{}, len(columns))
valuePtrs := make([]interface{}, len(columns)) // 用于 Scan 的指针切片
// 为每个列绑定指针Scan 要求传入指针)
for i := range values {
valuePtrs[i] = &values[i]
}
// 扫描当前行数据到指针切片
if err2 := rows.Scan(valuePtrs...); err2 != nil {
return result, err2
}
// 将当前行数据存入 map便于按列名访问
rowMap := make(map[string]interface{})
for i, col := range columns {
rowMap[col] = values[i]
}
result.Rows = append(result.Rows, rowMap)
}
// 检查遍历过程中是否有错误
if err = rows.Err(); err != nil {
return result, err
}
return result, nil
}

View File

@ -8,12 +8,14 @@ import (
type Shell struct {
gorm.Model
AuthID uint `gorm:"column:auth_id"`
Server string `gorm:"column:server"`
ShellName string `gorm:"column:shell_name"`
ShellContent string `gorm:"column:shell_content"`
Status int `gorm:"column:status"` // 0 未执行 1 执行中 2 执行完成
ShellResult string `gorm:"column:shell_result"`
AuthID uint `gorm:"column:auth_id"`
Server string `gorm:"column:server"`
ShellName string `gorm:"column:shell_name"`
ShellContent string `gorm:"column:shell_content"`
Status int `gorm:"column:status"` // 0 未执行 1 执行中 2 执行完成 3 执行出错
ShellRuntime float64 `gorm:"column:shell_runtime"` // 执行时间,单位秒
ShellDuration float64 `gorm:"column:shell_duration"` // 执行时长,单位秒
ShellResult string `gorm:"column:shell_result"`
}
func CreateShell(shellName, shellContent, server string, uid uint) uint {
@ -57,17 +59,16 @@ func FindShellByAuthID(auth_id int) []Shell {
return shells
}
func UpdateShellByID(id, authId uint, shellName, shellContent string, status int, shellResult string) bool {
pd := FindShellByID(id, authId)
if pd[0].ID == 0 {
return false
}
func UpdateShellByID(id, authId uint, shellName, shellContent string, status int, shellResult string, shellRuntime, shellDuration float64) bool {
var result *gorm.DB
shell := Shell{ShellName: shellName, ShellContent: shellContent, Status: status, ShellResult: shellResult, ShellRuntime: shellRuntime, ShellDuration: shellDuration}
var db2 *gorm.DB
if proto.Config.SERVER_SQL_LOG {
result = DB.Debug().Model(&Shell{}).Where("id = ? and auth_id = ?", id, authId).Updates(Shell{ShellName: shellName, ShellContent: shellContent, Status: status, ShellResult: shellResult})
db2 = DB.Debug()
} else {
result = DB.Model(&Shell{}).Where("id = ? and auth_id = ?", id, authId).Updates(Shell{ShellName: shellName, ShellContent: shellContent, Status: status, ShellResult: shellResult})
db2 = DB
}
result = db2.Model(&Shell{}).Where("id = ? and auth_id = ?", id, authId).Updates(shell)
if result.Error != nil {
return false
}

View File

@ -8,21 +8,25 @@ import (
type User struct {
gorm.Model
Name string `gorm:"column:name"`
Age int `gorm:"column:age"`
Email string `gorm:"column:email"`
Password string `gorm:"column:password"`
Gender string `gorm:"column:gender"`
Role string `gorm:"column:role"`
Redis bool `gorm:"column:redis"`
Run bool `gorm:"column:run"`
Upload bool `gorm:"column:upload"`
VideoFunc bool `gorm:"column:video_func"` //视频功能
DeviceFunc bool `gorm:"column:device_func"` //设备功能
CIDFunc bool `gorm:"column:cid_func"` //持续集成功能
Avatar string `gorm:"column:avatar"`
CreateTime string `gorm:"column:create_time"`
UpdateTime string `gorm:"column:update_time"`
Name string `gorm:"column:name"`
Age int `gorm:"column:age"`
Email string `gorm:"column:email"`
Password string `gorm:"column:password"`
Gender string `gorm:"column:gender"`
Role string `gorm:"column:role"`
Redis int `gorm:"column:redis"`
Run int `gorm:"column:run"`
Upload int `gorm:"column:upload"`
VideoFunc int `gorm:"column:video_func"` //视频功能
DeviceFunc int `gorm:"column:device_func"` //设备功能
CIDFunc int `gorm:"column:cid_func"` //持续集成功能, 0为无效 -1为false, 1为true
Avatar string `gorm:"column:avatar"`
PasswordNeedSecondAuth int `gorm:"column:password_need_second_auth" json:"password_need_second_auth"`
ThirdPartyNeedSecondAuth int `gorm:"column:third_party_need_second_auth" json:"third_party_need_second_auth"`
CodeNeedSecondAuth int `gorm:"column:code_need_second_auth" json:"code_need_second_auth"`
AISecondAuth int `json:"ai_second_auth" column:"ai_second_auth"`
LoginAddressInfo string `gorm:"column:login_address_info" json:"login_address_info,omitempty"`
LoginDeviceInfo string `gorm:"column:login_device_info" json:"login_device_info,omitempty"`
}
func CreateUser(name, password, email, gender string, age int) uint {

8
go.mod
View File

@ -11,7 +11,7 @@ require (
github.com/robfig/cron/v3 v3.0.1
gorm.io/driver/mysql v1.5.6
gorm.io/driver/postgres v1.5.9
gorm.io/gorm v1.25.10
gorm.io/gorm v1.30.0
)
require (
@ -39,6 +39,7 @@ require (
github.com/kr/text v0.2.0 // indirect
github.com/leodido/go-urn v1.4.0 // indirect
github.com/mattn/go-isatty v0.0.20 // indirect
github.com/mattn/go-sqlite3 v1.14.22 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
@ -48,9 +49,10 @@ require (
golang.org/x/arch v0.8.0 // indirect
golang.org/x/crypto v0.23.0 // indirect
golang.org/x/net v0.25.0 // indirect
golang.org/x/sync v0.1.0 // indirect
golang.org/x/sync v0.9.0 // indirect
golang.org/x/sys v0.20.0 // indirect
golang.org/x/text v0.15.0 // indirect
golang.org/x/text v0.20.0 // indirect
google.golang.org/protobuf v1.34.1 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
gorm.io/driver/sqlite v1.6.0 // indirect
)

10
go.sum
View File

@ -71,6 +71,8 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
@ -115,12 +117,16 @@ golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ=
golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
@ -139,8 +145,12 @@ gorm.io/driver/mysql v1.5.6 h1:Ld4mkIickM+EliaQZQx3uOJDJHtrd70MxAUqWqlx3Y8=
gorm.io/driver/mysql v1.5.6/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
gorm.io/driver/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8=
gorm.io/driver/postgres v1.5.9/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s=
gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=

View File

@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"net/http"
"os/exec"
"strconv"
"strings"
@ -57,6 +58,27 @@ func SetUpCIDGroup(router *gin.Engine) {
cidGroup.POST("/log/detail", GetCIDLog) //获取执行日志详情
cidGroup.GET("/callback", CIDCallback)
cidGroup.POST("/callback", CIDCallback)
cidGroup.GET("/running", GetRunningCIDs)
}
func GetRunningCIDs(c *gin.Context) {
id, _ := c.Get("id")
user_id := int(id.(float64))
req_type := c.Query("type") //请求方式 0默认自己, 1为所有管理员可选
req_type_ := 0
if req_type != "" {
req_type_, _ = strconv.Atoi(req_type)
}
resp_data, err := service.GetCIDRunningList(user_id, req_type_)
var resp proto.GeneralResp
if err != nil {
resp.Code = proto.InternalServerError
resp.Message = err.Error()
} else {
resp.Code, resp.Message = 0, ""
resp.Data = resp_data
}
c.JSON(http.StatusOK, resp)
}
func RunCID(c *gin.Context) {
var req CIDRunReq
@ -65,20 +87,19 @@ func RunCID(c *gin.Context) {
//获取权限
//user := dao.FindUserByUserID(authID)
user := service.GetUserByIDFromUserCenter(authID)
if user.Run == false {
if user.Run <= 0 {
c.JSON(200, gin.H{"error": "no run Permissions", "code": proto.NoRunPermissions, "message": "no run Permissions"})
return
}
if err := c.ShouldBind(&req); err == nil {
// 获取用户ID
username, _ := c.Get("username")
cid := dao.FindCIDByID(req.ID, authID)
if cid.ID == 0 {
c.JSON(200, gin.H{"error": "CID not found", "code": proto.OperationFailed, "message": "failed"})
return
} else {
go RunShell(username.(string), cid.Url, cid.Script, req.ID, authID)
go RunShellCID(cid.Name, cid.Url, cid.Script, req.ID, authID)
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success", "data": "success"})
}
} else {
@ -185,32 +206,43 @@ func CIDCallback(c *gin.Context) {
// 获取用户ID
token := c.Query("token")
cid_id := c.Query("id")
//fmt.Println("token:", token, "cid_id:", cid_id)
//将cid转换为int
cid, _ := strconv.Atoi(cid_id)
if token == "" || cid == 0 {
c.JSON(200, gin.H{"error": "parameter error", "code": proto.ParameterError, "message": "failed"})
var req proto.CIDCallBackReq
var resp proto.GeneralResp
if err := c.ShouldBindQuery(&req); err != nil {
resp.Code, resp.Message = proto.ParameterError, err.Error()
c.JSON(http.StatusOK, resp)
return
}
if req.ID == 0 || req.Token == "" {
resp.Code, resp.Message = proto.ParameterError, "token or id is empty"
c.JSON(http.StatusOK, resp)
return
}
res := dao.FindCIDByIDAndToken(cid, token)
if res.ID == 0 {
c.JSON(200, gin.H{"error": "CID not found by id and token", "code": proto.OperationFailed, "message": "failed"})
resp.Code, resp.Message = proto.ParameterError, "CID not found by id and token:"+req.Token+", id:"+strconv.Itoa(int(res.ID))
c.JSON(http.StatusOK, resp)
return
}
//user := dao.FindUserByUserID(res.Auth_id)
user := service.GetUserByIDFromUserCenter(res.Auth_id)
if user.Run == false {
c.JSON(200, gin.H{"error": "no run Permissions", "code": proto.NoRunPermissions, "message": "the user has no run Permissions"})
if user.Run <= 0 {
resp.Code, resp.Message = proto.NoRunPermissions, "the user has no run Permissions"
c.JSON(http.StatusOK, resp)
return
}
if res.ID != 0 {
user := dao.FindUserByID(res.Auth_id)
go RunShell(user[0].Name, res.Url, res.Script, int(res.ID), res.Auth_id)
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success", "data": "success"})
go RunShellCID(res.Name, res.Url, res.Script, int(res.ID), res.Auth_id)
resp.Code, resp.Message, resp.Data = proto.SuccessCode, "success", res.Name
c.JSON(http.StatusOK, resp)
return
} else {
c.JSON(200, gin.H{"error": "CID not found by id and token", "code": proto.OperationFailed, "message": "failed"})
resp.Code, resp.Message = proto.OperationFailed, "CID not found by id and token"
c.JSON(http.StatusOK, resp)
return
}
}
@ -220,6 +252,44 @@ func RunShell(username, url, script string, id, authID int) {
name := strs[len(strs)-1]
names := strings.Split(name, ".")
name = names[0]
//脚本内容,不同用户的持续集成、部署目录不同
scriptContent := `
echo "start"
` + script + `
echo "end"`
start := time.Now()
//执行脚本
cmd := exec.Command("/bin/bash", "-c", scriptContent)
// 使用bytes.Buffer捕获输出
var out bytes.Buffer
cmd.Stdout = &out
err3 := cmd.Run()
err3_info := ""
if err3 != nil {
err3_info = err3.Error()
}
elapsed := time.Since(start)
//fmt.Println("bash content:", scriptContent)
dao.CreateRunLog(id, authID, scriptContent, out.String(), err3_info, elapsed.Seconds()) //添加执行日志
}
func RunShellCID(cid_name, url, script string, id, authID int) {
strs := strings.Split(url, "/")
name := strs[len(strs)-1]
names := strings.Split(name, ".")
name = names[0]
now := time.Now()
var cid_running proto.CIDRunning
cid_running.ID = id
cid_running.AuthID = authID
cid_running.StartTime = now
cid_running.CID = cid_name
//加入正在运行
proto.CID_RunningMutex.Lock()
user_running_list := proto.CID_Running_Map[authID]
user_running_list = append(user_running_list, cid_running)
proto.CID_Running_Map[authID] = user_running_list
proto.CID_RunningMutex.Unlock()
//脚本内容,不同用户的持续集成、部署目录不同
scriptContent := `
@ -240,6 +310,23 @@ echo "end"`
elapsed := time.Since(start)
//fmt.Println("bash content:", scriptContent)
dao.CreateRunLog(id, authID, scriptContent, out.String(), err3_info, elapsed.Seconds()) //添加执行日志
if err3 != nil {
dao.UpdateLastFailByID(id, time.Now())
} else {
dao.UpdateLastSuccessByID(id, time.Now())
}
//移除正在运行
proto.CID_RunningMutex.Lock()
user_running_list = proto.CID_Running_Map[authID]
for i, v := range user_running_list {
if v.StartTime.Equal(now) == true {
//删除
user_running_list = append(user_running_list[:i], user_running_list[i+1:]...)
break
}
}
proto.CID_Running_Map[authID] = user_running_list
proto.CID_RunningMutex.Unlock()
}
// 定时任务处理逻辑

208
handler/dbm.go Normal file
View File

@ -0,0 +1,208 @@
package handler
import (
"github.com/gin-gonic/gin"
"log"
"net/http"
"videoplayer/proto"
"videoplayer/service"
)
func SetDBManageGroup(router *gin.Engine) {
dbm := router.Group("/dbm")
dbm.POST("/run_sql", RunSQLHandler) // 运行SQL语句
dbm.POST("/create_db_manage", CreateDBManageHandler) // 创建数据库管理
dbm.POST("/get_db_manage", GetDBManageHandler) // 获取数据库管理信息
dbm.POST("/get_sql_history", GetSQLRunHistoryHandler) // 获取SQL运行历史
dbm.POST("/update_db_manage", UpdateDBManageHandler) // 更新数据库管理信息
dbm.POST("/del_db_manage", DeleteDBManageHandler) // 删除数据库管理信息
dbm.POST("/del_dbm_sql_history", DeleteSQLRunHistoryHandler) // 删除SQL运行历史
dbm.POST("/get_db_table_desc", GetDBTableDescHandler) // 获取数据库表描述
}
func DeleteSQLRunHistoryHandler(c *gin.Context) {
id, _ := c.Get("id")
userID := int(id.(float64))
var req proto.DeleteDBManageSQLHistoryReq
var resp proto.GeneralResp
if err := c.ShouldBind(&req); err != nil {
resp.Code = proto.ParameterError
resp.Message = "请求参数解析错误"
} else {
err2 := service.DeleteSQLRunHistory(&req, userID)
if err2 != nil {
resp.Code = proto.DBMRunSQLHistoryDeleteFailed
resp.Message = "删除SQL运行历史失败: " + err2.Error()
} else {
resp.Code = proto.SuccessCode
resp.Message = "删除SQL运行历史成功"
}
}
c.JSON(http.StatusOK, resp)
}
func DeleteDBManageHandler(c *gin.Context) {
id, _ := c.Get("id")
userID := int(id.(float64))
var req proto.DeleteDBManageReq
var resp proto.GeneralResp
if err := c.ShouldBind(&req); err != nil {
resp.Code = proto.ParameterError
resp.Message = "请求参数解析错误"
} else {
err2 := service.DeleteDBManage(&req, userID)
if err2 != nil {
resp.Code = proto.DBMDeleteFailed
resp.Message = "删除数据库管理失败: " + err2.Error()
} else {
resp.Code = proto.SuccessCode
resp.Message = "删除数据库管理成功"
}
}
c.JSON(http.StatusOK, resp)
}
func UpdateDBManageHandler(c *gin.Context) {
id, _ := c.Get("id")
userID := int(id.(float64))
var req proto.UpdateDBManageReq
var resp proto.GeneralResp
if err := c.ShouldBind(&req); err != nil {
resp.Code = proto.ParameterError
resp.Message = "请求参数解析错误"
} else {
dbManage, err2 := service.UpdateDBManage(&req, userID)
if err2 != nil {
resp.Code = proto.DBMUpdateFailed
resp.Message = "更新数据库管理失败: " + err2.Error()
} else {
resp.Code = proto.SuccessCode
resp.Message = "更新数据库管理成功"
resp.Data = dbManage
}
}
c.JSON(http.StatusOK, resp)
}
func GetSQLRunHistoryHandler(c *gin.Context) {
id, _ := c.Get("id")
userID := int(id.(float64))
var req proto.GetSQLRunHistoryReq
var resp proto.GeneralResp
if err := c.ShouldBind(&req); err != nil {
resp.Code = proto.ParameterError
resp.Message = "请求参数解析错误"
} else {
history, err2 := service.GetSQLRunHistory(&req, userID)
if err2 != nil {
resp.Code = proto.DBMGetFailed
resp.Message = "获取SQL运行历史失败: " + err2.Error()
} else {
resp.Code = proto.SuccessCode
resp.Message = "获取SQL运行历史成功"
resp.Data = history
}
}
c.JSON(http.StatusOK, resp)
}
func GetDBManageHandler(c *gin.Context) {
id, _ := c.Get("id")
userID := uint(id.(float64))
var req proto.GetDBManageReq
var resp proto.GeneralResp
if err := c.ShouldBind(&req); err != nil {
resp.Code = proto.ParameterError
resp.Message = "请求参数解析错误"
} else {
dbManage, err2 := service.GetDBManageList(&req, userID)
if err2 != nil {
resp.Code = proto.DBMGetFailed
resp.Message = "获取数据库管理信息失败: " + err2.Error()
} else {
resp.Code = proto.SuccessCode
resp.Message = "获取数据库管理信息成功"
resp.Data = dbManage
}
}
c.JSON(http.StatusOK, resp)
}
func CreateDBManageHandler(c *gin.Context) {
id, _ := c.Get("id")
userID := uint(id.(float64))
var req proto.CreateDBManageReq
var resp proto.GeneralResp
if err := c.ShouldBind(&req); err != nil {
resp.Code = proto.ParameterError
resp.Message = "请求参数解析错误"
} else {
dbManage, err2 := service.CreateDBManage(&req, userID)
if err2 != nil {
resp.Code = proto.DBMCreateFailed
resp.Message = "创建数据库管理失败: " + err.Error()
} else {
resp.Code = proto.SuccessCode
resp.Message = "创建数据库管理成功"
resp.Data = dbManage
}
}
c.JSON(http.StatusOK, resp)
}
func RunSQLHandler(c *gin.Context) {
id, _ := c.Get("id")
userID := uint(id.(float64))
// 处理运行SQL请求
var req proto.RunSQLRequest
var resp proto.GeneralResp
if err := c.ShouldBind(&req); err != nil {
resp.Code = proto.ParameterError
resp.Message = "请求参数解析错误"
} else {
log.Println("run sql request, sql is:", req.SQL)
req.UserID = userID
res, err2 := service.RunSQL(&req)
if err2 != nil {
resp.Code = proto.DBMRunSQLFailed
resp.Message = "运行SQL失败: " + err2.Error()
} else {
resp.Code = proto.SuccessCode
resp.Message = "运行SQL成功"
resp.Data = res
}
}
c.JSON(http.StatusOK, resp)
return
}
func GetDBTableDescHandler(c *gin.Context) {
id, _ := c.Get("id")
userID := int(id.(float64))
var req proto.GetDBTableDescReq
var resp proto.GeneralResp
if err := c.ShouldBind(&req); err != nil {
resp.Code = proto.ParameterError
resp.Message = "请求参数解析错误"
} else {
tableDesc, err2 := service.GetDBTableDesc(&req, userID)
if err2 != nil {
resp.Code = proto.DBMGetTableDescFailed
resp.Message = "获取数据库表描述失败: " + err2.Error()
} else {
resp.Code = proto.SuccessCode
resp.Message = "获取数据库表描述成功"
resp.Data = tableDesc
}
}
c.JSON(http.StatusOK, resp)
}

View File

@ -141,7 +141,7 @@ func UploadFileV2(c *gin.Context) {
}
user := dao.FindUserByUserID(id1)
if user.Upload == false {
if user.Upload <= 0 {
c.JSON(http.StatusOK, gin.H{"error": "no upload Permissions", "code": proto.NoUploadPermissions, "message": "failed"})
return
}

View File

@ -16,12 +16,14 @@ type CreateShellReq struct {
Server string `json:"server" form:"server" binding:"required"`
}
type UpdateShellReq struct {
ID uint `json:"id" form:"id" binding:"required"`
ShellName string `json:"shell_name" form:"shell_name"`
ShellContent string `json:"shell_content" form:"shell_content"`
Server string `json:"server" form:"server"`
Status int `json:"status" form:"status"`
ShellResult string `json:"shell_result" form:"shell_result"`
ID uint `json:"id" form:"id" binding:"required"`
ShellName string `json:"shell_name" form:"shell_name"`
ShellContent string `json:"shell_content" form:"shell_content"`
Server string `json:"server" form:"server"`
Status int `json:"status" form:"status"`
ShellResult string `json:"shell_result" form:"shell_result"`
ShellRuntime float64 `json:"shell_runtime" form:"shell_runtime"` // 执行时间,单位秒
ShellDuration float64 `json:"shell_duration" form:"shell_duration"` // 执行时长,单位秒
}
type UpdateShellReqV2 struct {
@ -83,7 +85,7 @@ func (s *ShellHandler) UpdateShell(c *gin.Context) {
var resp []UpdateShellResp
//log.Println("UpdateShellReqData:", req.Shells)
for _, v := range req.Shells {
if service.UpdateShellByID(v.ID, uint(id), v.ShellName, v.ShellContent, v.Server, v.Status, v.ShellResult) {
if service.UpdateShellByIDV2(v.ID, uint(id), v.ShellName, v.ShellContent, v.Server, v.Status, v.ShellResult, v.ShellRuntime) {
resp = append(resp, UpdateShellResp{ID: v.ID, Status: v.Status})
} else {
resp = append(resp, UpdateShellResp{ID: v.ID, Status: -1})

View File

@ -6,7 +6,9 @@ import (
"io"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"time"
"videoplayer/dao"
@ -57,6 +59,8 @@ func SetUpToolGroup(router *gin.Engine) {
toolGroup.POST("/del_monitor", DelMonitor) //删除设备监控
//发送邮件
toolGroup.POST("/send_mail", SendMailTool)
//下载代理
toolGroup.GET("/dlp", DownloadProxyHandle)
}
func GetMonitorList(c *gin.Context) {
@ -254,7 +258,7 @@ func UploadFile(c *gin.Context) {
}
user := dao.FindUserByUserID(id1)
if user.Upload == false {
if user.Upload <= 0 {
c.JSON(http.StatusOK, gin.H{"error": "no upload Permissions", "code": proto.NoUploadPermissions, "message": "failed"})
return
}
@ -347,7 +351,7 @@ func SetRedis(c *gin.Context) {
id, _ := c.Get("id")
id1 := int(id.(float64))
user := dao.FindUserByUserID(id1)
if user.Redis == false {
if user.Redis <= 0 {
c.JSON(http.StatusOK, gin.H{"error": "no redis Permissions", "code": proto.NoRedisPermissions, "message": "failed"})
return
}
@ -375,7 +379,7 @@ func GetRedis(c *gin.Context) {
id, _ := c.Get("id")
id1 := int(id.(float64))
user := dao.FindUserByUserID(id1)
if user.Redis == false {
if user.Redis <= 0 {
c.JSON(http.StatusOK, gin.H{"error": "no redis Permissions", "code": proto.NoRedisPermissions, "message": "failed"})
return
}
@ -440,7 +444,14 @@ func SendMail(title, content string) {
em.SmtpUserName = "354425203@qq.com"
em.SmtpPort = 587
em.ImapPort = 993
err := em.Send(title, content, []string{"3236990479@qq.com", "lijun@ljsea.top"})
var targetMails []string
for _, v := range proto.Config.MONITOR_MAIL {
targetMails = append(targetMails, v.Value)
}
if targetMails == nil || len(targetMails) == 0 {
return
}
err := em.Send(title, content, targetMails)
if err != nil {
fmt.Println(err)
}
@ -478,3 +489,71 @@ func SendMailTool(c *gin.Context) {
}
}
// DownloadProxyHandle 处理下载代理请求
func DownloadProxyHandle(c *gin.Context) {
key := c.Query("key")
if key == "" || key != proto.Config.DOWNLOAD_PROXY_KEY {
c.JSON(http.StatusOK, gin.H{"code": proto.ParameterError, "message": "failed, key is null or error"})
}
// 获取URL参数
encodedURL := c.Query("url")
if encodedURL == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "URL参数不能为空", "code": proto.ParameterError, "message": "failed"})
return
}
// URL解码
decodedURL, err := url.QueryUnescape(encodedURL)
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "URL解码失败: " + err.Error(), "code": proto.ParameterError, "message": "failed"})
return
}
// 验证URL格式
parsedURL, err := url.Parse(decodedURL)
if err != nil || parsedURL.Scheme == "" || parsedURL.Host == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的URL格式", "code": proto.ParameterError, "message": "failed"})
return
}
// 发起请求获取目标资源
resp, err := http.Get(decodedURL)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取资源失败: " + err.Error(), "code": proto.InternalServerError})
return
}
defer resp.Body.Close()
// 检查响应状态
if resp.StatusCode != http.StatusOK {
c.JSON(http.StatusBadGateway, gin.H{"error": "目标资源请求失败,状态码: " + resp.Status, "code": proto.InternalServerError})
return
}
// 获取文件名
filename := getFilenameFromURL(parsedURL)
// 设置响应头,告诉浏览器这是一个文件下载
c.Header("Content-Disposition", "attachment; filename="+url.QueryEscape(filename))
c.Header("Content-Type", resp.Header.Get("Content-Type"))
c.Header("Content-Length", resp.Header.Get("Content-Length"))
// 将响应体流式传输到客户端
_, err = io.Copy(c.Writer, resp.Body)
if err != nil {
// 已经开始传输数据后发生错误无法返回JSON只能记录日志
log.Println("tool download proxy handle error:", err)
}
}
// 从URL中提取文件名
func getFilenameFromURL(u *url.URL) string {
// 从路径中提取文件名
filename := filepath.Base(u.Path)
// 如果路径中没有文件名,尝试从查询参数中获取
if filename == "" || filename == "/" {
filename = "download_file"
}
return filename
}

77
main.go
View File

@ -20,15 +20,23 @@ import (
)
func main() {
// 输入参数
if len(os.Args) > 1 {
initConfig(os.Args[1]) //第一个参数是配置文件路径
} else {
initConfig("") //没有输入参数,则使用默认配置文件路径
}
gin.SetMode(gin.ReleaseMode)
r := gin.Default()
err := dao.Init()
if err != nil {
panic("failed to connect database:" + err.Error())
}
err = worker.InitRedis()
if err != nil {
panic("failed to connect redis:" + err.Error())
if proto.Config.MEMORY_CACHE == false { //不开启内存缓存才使用redis
err = worker.InitRedis()
if err != nil {
panic("failed to connect redis:" + err.Error())
}
}
r.Use(handler.CrosHandler())
r.Use(JWTAuthMiddleware()) // 使用 JWT 认证中间件
@ -40,6 +48,7 @@ func main() {
handler.SetUpToolGroup(r) // Tool
handler.SetUpFileGroup(r) // File
handler.SetUpShellGroup(r) // Shell
handler.SetDBManageGroup(r) // DBM
defer dao.Close()
defer worker.CloseRedis()
//定时任务
@ -54,14 +63,42 @@ func main() {
ReadConfigToSetSystem()
r.Run(":" + proto.Config.SERVER_PORT) // listen and serve on 0.0.0.0:8083
}
func init() {
// 不使用
//
// func init() {
// // 创建cid的目录
// os.MkdirAll(proto.CID_BASE_DIR, os.ModePerm)
// os.MkdirAll(proto.CID_BASE_DIR+"script", os.ModePerm)
// os.MkdirAll(proto.CID_BASE_DIR+"workspace", os.ModePerm)
// //读取配置文件
// //文件地址/home/videoplayer/vp.conf
// configPath := "/home/videoplayer/vp.conf"
// //读取配置文件
// err := proto.ReadConfig(configPath)
// if err != nil {
// panic("failed to read config file:" + err.Error())
// }
// }
func initConfig(configPath string) {
//if proto.Config.TOKEN_SECRET != "" {
// return
//}
// 创建cid的目录
os.MkdirAll(proto.CID_BASE_DIR, os.ModePerm)
os.MkdirAll(proto.CID_BASE_DIR+"script", os.ModePerm)
os.MkdirAll(proto.CID_BASE_DIR+"workspace", os.ModePerm)
//读取配置文件
//文件地址/home/videoplayer/vp.conf
configPath := "/home/videoplayer/vp.conf"
//系统是linux、macos还是windows
if configPath == "" {
if os.Getenv("OS") == "Windows_NT" {
configPath = "C:/Users/Administrator/vp.conf"
} else if os.Getenv("OS") == "linux" {
//文件地址/home/saw-ai/saw-ai.conf
configPath = "/etc/vp.conf"
} else {
configPath = "/etc/vp.conf"
}
}
//读取配置文件
err := proto.ReadConfig(configPath)
if err != nil {
@ -116,13 +153,13 @@ func JWTAuthMiddleware() gin.HandlerFunc {
c.Next()
return
}
if proto.SigningKeyIsValid == false {
c.AbortWithStatusJSON(http.StatusOK, gin.H{"message": "server error", "error": "token secret is invalid", "code": proto.SigningKeyIsValid})
return
}
if tokenString == "" {
//c.AbortWithStatus(200)
c.JSON(200, gin.H{
"message": "Unauthorized",
"error": "token is empty",
"code": proto.TokenIsNull,
})
c.JSON(http.StatusOK, gin.H{"message": "Unauthorized", "error": "token is empty", "code": proto.TokenIsNull})
return
}
if proto.Config.TOKEN_USE_REDIS {
@ -151,10 +188,12 @@ func JWTAuthMiddleware() gin.HandlerFunc {
return
}
proto.SigningKeyRWLock.RLock() //加读锁
// 使用加密secret 解析 JWT 令牌
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return proto.SigningKey, nil
})
proto.SigningKeyRWLock.RUnlock()
// 验证令牌
if err != nil || !token.Valid {
@ -194,7 +233,13 @@ func myTask() {
//其它定时任务-通用
RunGeneralCron()
service.ShellWillRunFromServer()
service.SyncTokenSecretFromUserCenter()
service.DelDBMMap() //定时处理DBMMap中的数据
if proto.Config.MEMORY_CACHE {
worker.DeleteMemoryCacheCron()
// 清理后持久化
worker.WriteMemoryCacheToFile()
}
}
func ReadConfigToSetSystem() {
@ -347,13 +392,13 @@ func UserFuncIntercept(id int, url string) bool {
//如果用户有权限,则不拦截
for k, v := range proto.Per_menu_map {
if strings.Contains(url, k) {
if v == 1 && user.VideoFunc == false {
if v == 1 && user.VideoFunc <= 0 {
return true
}
if v == 2 && user.DeviceFunc == false {
if v == 2 && user.DeviceFunc <= 0 {
return true
}
if v == 3 && user.CIDFunc == false {
if v == 3 && user.CIDFunc <= 0 {
return true
}
}

View File

@ -4,24 +4,38 @@ import (
"encoding/json"
"fmt"
"gorm.io/gorm"
"log"
mrand "math/rand"
"os"
"sync"
)
var Config ConfigStruct
var SigningKey = []byte{}
var Url_map = map[string]bool{"/login": true, "/register": true, "/uuid": true, "/gqr": true, "/cid/callback": true, "/tool/monitor": true, "/user/sync": true, "/tool/file/": true, "/user/reset": true} // 不需要token验证的url
var Url_map = map[string]bool{"/login": true, "/register": true, "/uuid": true, "/gqr": true, "/cid/callback": true, "/tool/monitor": true, "/user/sync": true, "/tool/file/": true, "/user/reset": true, "/tool/dlp": true} // 不需要token验证的url
var Per_menu_map = map[string]int{"/video/": 1, "/device/": 2, "/cid/": 3}
var File_Type = map[string]int{"im": 1, "avatar": 2, "file": 3, "config": 4} // 文件类型
var CID_Running_Map = map[int][]CIDRunning{} //正在运行的cid
// 配置读写锁
var CID_RunningMutex = sync.RWMutex{}
var ConfigRWLock = &sync.RWMutex{}
var SigningKeyRWLock = &sync.RWMutex{}
var SyncSecretReqLog int64
var CurrentConfigPath string
var SigningKeyIsValid = true // 是否有效的签名密钥
const (
MYSQL_USER = "video_t2"
MYSQL_DB = "video_t2"
MYSQL_PASSWORD = "2t2SKHmWEYj2xFKF"
MYSQL_PASSWORD = "2fdreYj2xFKF"
MYSQL_PORT = "3306"
MYSQL_HOST = "127.0.0.1"
MYSQL_DSN = MYSQL_USER + ":" + MYSQL_PASSWORD + "@tcp(" + MYSQL_HOST + ":" + MYSQL_PORT + ")/" + MYSQL_DB + "?charset=utf8mb4&parseTime=True&loc=Local"
REDIS_ADDR = "127.0.0.1:6379"
REDIS_PASSWORD = "lj502138"
REDIS_PASSWORD = "lgybvueiogvter"
REIDS_DB = 2
TOKEN_SECRET = "mfjurnc_32ndj9dfhj"
@ -31,6 +45,8 @@ const (
// 以下是文件上传的配置
FILE_BASE_DIR = "/home/lijun/file/"
DBMMap_Max_Keep_Time = 10 * 60 //DBMap中的数据最大保持时间10min
)
const (
@ -61,51 +77,62 @@ type User struct {
Email string `gorm:"column:email"`
Gender string `gorm:"column:gender"`
}
type StructValue struct {
Value string `json:"value" form:"value"`
}
type ConfigStruct struct {
DB int `json:"db"` // 0: mysql, 1: pg
MYSQL_DSN string `json:"mysql_dsn"`
PG_DSN string `json:"pg_dsn"`
REDIS_ADDR string `json:"redis_addr"`
TOKEN_USE_REDIS bool `json:"token_use_redis"`
REDIS_User_PW bool `json:"redis_user_pw"` // 是否使用密码
REDIS_PASSWORD string `json:"redis_password"`
REDIS_DB int `json:"redis_db"`
TOKEN_SECRET string `json:"token_secret"`
CID_BASE_DIR string `json:"cid_base_dir"`
FILE_BASE_DIR string `json:"file_base_dir"`
MONITOR bool `json:"monitor"` // 状态监控及邮件通知
SERVER_SQL_LOG bool `json:"server_sql_log"` // 服务器sql日志
SERVER_PORT string `json:"server_port"` // 服务端口
LOG_SAVE_DAYS int `json:"log_save_days"` // 日志保存天数,-1表示不保存0表示永久保存
SERVER_USER_TYPE string `json:"user_type"` // 服务器用户类型master: 主服务器slave: 从服务器,从服务器会定时同步数据
MASTER_SERVER_DOMAIN string `json:"master_server_domain"` // 主服务器域名
USER_SYNC_TIME int `json:"user_sync_time"` // 用户数据同步时间,单位秒
SERVER_NAME string `json:"server_name"` // 服务器名称,用于区分不同服务器
MONITOR_SERVER_TOKEN string `json:"monitor_server_token"` // 监控服务器token,用于状态监控及邮件通知
DB int `json:"db"` // 0: mysql, 1: pg, 2:sqlite
MYSQL_DSN string `json:"mysql_dsn"`
PG_DSN string `json:"pg_dsn"`
SQLITE_FILE string `json:"sqlite_file"`
REDIS_ADDR string `json:"redis_addr"`
TOKEN_USE_REDIS bool `json:"token_use_redis"`
REDIS_User_PW bool `json:"redis_user_pw"` // 是否使用密码
REDIS_PASSWORD string `json:"redis_password"`
MEMORY_CACHE bool `json:"memory_cache"` //使用程序内缓存开启这个redis将不生效
REDIS_DB int `json:"redis_db"`
TOKEN_SECRET string `json:"token_secret"`
CID_BASE_DIR string `json:"cid_base_dir"`
FILE_BASE_DIR string `json:"file_base_dir"`
MONITOR bool `json:"monitor"` // 状态监控及邮件通知
SERVER_SQL_LOG bool `json:"server_sql_log"` // 服务器sql日志
SERVER_PORT string `json:"server_port"` // 服务端口
LOG_SAVE_DAYS int `json:"log_save_days"` // 日志保存天数,-1表示不保存0表示永久保存
SERVER_USER_TYPE string `json:"user_type"` // 服务器用户类型master: 主服务器slave: 从服务器,从服务器会定时同步数据
MASTER_SERVER_DOMAIN string `json:"master_server_domain"` // 主服务器域名
USER_SYNC_TIME int `json:"user_sync_time"` // 用户数据同步时间,单位秒
SERVER_NAME string `json:"server_name"` // 服务器名称,用于区分不同服务器
MONITOR_SERVER_TOKEN string `json:"monitor_server_token"` // 监控服务器token,用于状态监控及邮件通知
APP_ID string `json:"app_id"` // 应用ID,用于标识不同应用
MONITOR_MAIL []StructValue `json:"monitor_mail"` // 设备监控邮件通知配置
DOWNLOAD_PROXY_KEY string `json:"download_proxy_key"` // 下载代理key
}
func WriteConfigToFile() {
configData, err := json.MarshalIndent(Config, "", " ")
if err != nil {
log.Println("WriteConfigToFile json marshal error:", err)
return
}
err = os.WriteFile(CurrentConfigPath, configData, 0644)
if err != nil {
log.Println("WriteConfigToFile write file error:", err)
return
}
log.Println("WriteConfigToFile write config to file success")
}
// 读取配置文件
func ReadConfig(path string) error {
//查看配置文件是否存在,不存在则创建
CurrentConfigPath = path
_, err := os.Stat(path)
if err != nil {
fmt.Println("Config file not found!")
//创建默认配置
DefaultConfig()
//写入json文件
file, err := os.Create(path)
if err != nil {
fmt.Println("Error creating config file")
return err
}
defer file.Close()
encoder := json.NewEncoder(file)
err = encoder.Encode(&Config)
if err != nil {
fmt.Println("Error encoding config")
}
return err
WriteConfigToFile()
}
//读json文件
@ -125,8 +152,22 @@ func ReadConfig(path string) error {
}
}
SigningKey = []byte(Config.TOKEN_SECRET)
if Config.APP_ID == "" {
Config.APP_ID = GetRandomString(8)
log.Println("ReadConfig generated APP_ID:", Config.APP_ID)
go WriteConfigToFile()
}
return err
}
func GetRandomString(l int) string {
str := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
bytes := []byte(str)
var result []byte
for i := 0; i < l; i++ {
result = append(result, bytes[mrand.Intn(len(bytes))])
}
return string(result)
}
// 默认配置
func DefaultConfig() {
@ -134,6 +175,7 @@ func DefaultConfig() {
Config.MYSQL_DSN = MYSQL_DSN
Config.PG_DSN = ""
Config.REDIS_ADDR = REDIS_ADDR
Config.SQLITE_FILE = ""
Config.TOKEN_USE_REDIS = false
Config.REDIS_User_PW = false
Config.REDIS_PASSWORD = REDIS_PASSWORD

118
proto/dbm.go Normal file
View File

@ -0,0 +1,118 @@
package proto
import (
"gorm.io/gorm"
)
const (
DB_TYPE_MYSQL = 0 // DBTypeMySQL MySQL数据库
DB_TYPE_POSTGRES = 1 // DBTypePostgres PostgreSQL数据库
DB_TYPE_SQLITE = 2 // DBTypeSQLite SQLite数据库
DB_TYPE_SQLSERVER = 3 // DBTypeSQLServer SQL Server数据库
DB_TYPE_ORACLE = 4 // DBTypeOracle Oracle数据库
DB_TYPE_MONGODB = 5 // DBTypeMongoDB MongoDB数据库
DB_TYPE_REDIS = 6 // DBTypeRedis Redis数据库
)
type RunSQLRequest struct {
SQL string `json:"sql" form:"sql"` // SQL语句
DB_ID uint `json:"db_id" form:"db_id"` // 数据库ID
UserID uint `json:"user_id" form:"user_id"` // 用户ID
}
type DBManage struct {
gorm.Model
UserID uint `gorm:"column:user_id"` // 用户ID
DB_IP string `gorm:"column:db_ip;type:varchar(255)"` // 数据库IP
DB_Port uint `gorm:"column:db_port"` // 数据库端口
DB_NAME string `gorm:"column:db_name;type:varchar(255);uniqueIndex:idx_db_name"` // 数据库名称
DB_User string `gorm:"column:db_user;type:varchar(255);uniqueIndex:idx_db_user"` // 数据库用户名
DB_Password string `gorm:"column:db_password;type:varchar(255);uniqueIndex:idx_db_password"` // 数据库密码
DB_Type uint `gorm:"column:db_type"` // 数据库类型: 0为mysql,1为postgres,2为sqlite,3为sqlserver,4为oracle,5为mongodb,6为redis
DB_Desc string `gorm:"column:db_desc;type:varchar(255)"` // 数据库描述
DB_STATUS uint `gorm:"column:db_status"` // 数据库状态: 0为未连接,1为已连接,2为连接失败
}
type SQLRunHistory struct {
gorm.Model
UserID uint `gorm:"column:user_id"` // 用户ID
SQL string `gorm:"column:sql;type:text"` // 执行的SQL语句
DB_ID uint `gorm:"column:db_id"` // 数据库ID
Status uint `gorm:"column:status"` // 执行状态: 0为成功,1为失败
}
type CreateDBManageReq struct {
DB_IP string `json:"db_ip" form:"db_ip"` // 数据库IP
DB_Port uint `json:"db_port" form:"db_port"` // 数据库端口
DB_NAME string `json:"db_name" form:"db_name"` // 数据库名称
DB_User string `json:"db_user" form:"db_user"` // 数据库用户名
DB_Password string `json:"db_password" form:"db_password"` // 数据库密码
DB_Type uint `json:"db_type" form:"db_type"` // 数据库类型: 0为mysql,1为postgres,2为sqlite,3为sqlserver,4为oracle,5为mongodb,6为redis
DB_Desc string `json:"db_desc" form:"db_desc"` // 数据库描述备注
}
type UpdateDBManageReq struct {
DB_ID uint `json:"db_id" form:"db_id"` // 数据库ID
DB_IP string `json:"db_ip" form:"db_ip"` // 数据库IP
DB_Port uint `json:"db_port" form:"db_port"` // 数据库端口
DB_NAME string `json:"db_name" form:"db_name"` // 数据库名称
DB_User string `json:"db_user" form:"db_user"` // 数据库用户名
DB_Password string `json:"db_password" form:"db_password"` // 数据库密码
DB_Type uint `json:"db_type" form:"db_type"` // 数据库类型: 0为mysql,1为postgres,2为sqlite,3为sqlserver,4为oracle,5为mongodb,6为redis
DB_Desc string `json:"db_desc" form:"db_desc"` // 数据库描述备注
}
type GetDBManageReq struct {
DB_ID uint `json:"db_id" form:"db_id"` // 数据库ID
GET_TYPE int `json:"get_type" form:"get_type"` // 获取类型: 0获取自己1为获取全部管理员权限
}
type GetSQLRunHistoryReq struct {
DB_ID uint `json:"db_id" form:"db_id"` // 数据库ID
GET_TYPE int `json:"get_type" form:"get_type"` // 获取类型: 0获取自己1为获取全部管理员权限
}
// SQLResult 包含查询结果的列名顺序和对应数据
type SQLResult struct {
Columns []SQLResultColumnsValue // 列名顺序(与 SQL 查询的列顺序一致)
Rows []map[string]interface{} // 每行数据map 便于按列名访问)
}
type SQLResultColumnsValue struct {
Prop string `json:"prop"`
Label string `json:"label"`
Attr string `json:"attr"`
}
type DeleteDBManageReq struct {
DB_ID uint `json:"db_id" form:"db_id"` // 数据库ID
Del_Type uint `json:"del_type" form:"del_type"` // 删除类型: 0为删除单条1为所有
UserID uint `json:"user_id" form:"user_id"` // 用户ID
}
type DeleteDBManageSQLHistoryReq struct {
DB_ID uint `json:"db_id" form:"db_id"` // 数据库ID
Del_Type uint `json:"del_type" form:"del_type"` // 删除类型: 0为删除单条1为所有
History_ID uint `json:"history_id" form:"history_id"` // SQL执行历史ID,如果为0则删除所有
UserID uint `json:"user_id" form:"user_id"` // 用户ID
}
type GetDBTableDescReq struct {
DB_ID uint `json:"db_id" form:"db_id"` // 数据库ID
Table string `json:"table" form:"table"` // 数据库表名
GetType int `json:"get_type" form:"get_type"` // 获取类型: 0获取全部,1获取1个
}
type GetDBTableDescResp struct {
TableName string `json:"table_name"` // 表名
}
type DBTableAttribute struct {
ColumnName string `json:"column_name"` // 列名
ColumnType string `json:"column_type"` // 列类型
}
type DBValue struct {
LastUserTime int64 `json:"last_user_time"`
Value *gorm.DB `json:"value"`
}

View File

@ -1,5 +1,7 @@
package proto
import "time"
type ImKeyReq struct {
To_user_id int `json:"to_user_id" form:"to_user_id" binding:"required"`
}
@ -12,3 +14,11 @@ type Message struct {
From_user_id int `json:"from_user_id"`
Session string `json:"session"`
}
// cid正在运行结构
type CIDRunning struct {
ID int `json:"id" form:"id"` //cid的id
CID string `json:"cid" form:"cid"` //cid名称
AuthID int `json:"auth_id" form:"auth_id"` //所属用户
StartTime time.Time `json:"start_time" form:"start_time"` //开始时间
}

View File

@ -5,3 +5,8 @@ type GeneralResp struct {
Message string `json:"message"`
Data any `json:"data"`
}
type CIDCallBackReq struct {
Token string `json:"token" form:"token"`
ID int `json:"id" form:"id"`
}

View File

@ -78,4 +78,14 @@ const (
MonitorServerIDIsNull = 110 // 监控服务器ID为空
MonitorServerIDNotFound = 111 // 监控服务器ID不存在
SigningKeyVersionIsTooOld = 200
//下面是数据库管理工具-错误状态码 100x
DBMRunSQLFailed = 1001 // 执行SQL失败
DBMCreateFailed = 1002 // 创建数据库管理失败
DBMGetFailed = 1003 // 获取数据库管理信息失败`
DBMUpdateFailed = 1004 // 更新数据库管理信息失败
DBMDeleteFailed = 1005 // 删除数据库管理信息失败
DBMRunSQLHistoryDeleteFailed = 1006 // 删除SQL运行历史失败
DBMGetTableDescFailed = 1007 // 获取表描述信息失败
)

View File

@ -92,12 +92,13 @@ type SyncUserShellReq struct {
}
type UpdateShellReq struct {
ID uint `json:"id"`
ShellName string `json:"shell_name"`
ShellContent string `json:"shell_content"`
Server string `json:"server"`
Status int `json:"status"`
ShellResult string `json:"shell_result"`
ID uint `json:"id"`
ShellName string `json:"shell_name"`
ShellContent string `json:"shell_content"`
Server string `json:"server"`
Status int `json:"status"`
ShellResult string `json:"shell_result"`
ShellRuntime float64 `json:"shell_runtime" form:"shell_runtime"` // 执行时间,单位秒
}
// shell 执行结果返回
@ -117,3 +118,29 @@ type ResponseOAuth struct {
Email string `json:"email" form:"email"`
Token string `json:"token" form:"token"`
}
type SecretSyncSettings struct {
Prev string `json:"prev"` // 前一个secret
Curr string `json:"curr"` // 当前的secret
Next string `json:"next"` // 下一个secret
CurrExpectedExpiration int64 `json:"curr_expected_expiration"` // 当前密钥的预期过期时间戳
PrevEndTimestamp int64 `json:"prev_end_timestamp"` // 前一个secret的结束时间戳
CurrStartTimestamp int64 `json:"curr_start_timestamp"` // 当前secret的开始时间戳
NextStartTimestamp int64 `json:"next_start_timestamp"` // 下一个secret的开始时间戳
}
type SyncSystemConfigRequest struct {
//时间戳
Timestamp int64 `json:"timestamp" form:"timestamp"` // 时间戳
//设备标识
DeviceApp string `json:"device_app" form:"device_app"` // 设备标识
//加密信息
Sign string `json:"sign" form:"sign"` // 加密信息,app的secret加密后的值
SecretKeyMd5 string `json:"secret_key_md5" form:"secret_key_md5"` // 密钥的MD5值,用于验证
}
type RequestSyncSecretResp struct {
Code int `json:"code"`
Message string `json:"message"`
Data string `json:"data"`
}

250
service/dbmService.go Normal file
View File

@ -0,0 +1,250 @@
package service
import (
"errors"
"gorm.io/driver/mysql"
"gorm.io/driver/postgres"
"gorm.io/gorm"
"strconv"
"videoplayer/dao"
"videoplayer/proto"
"videoplayer/worker"
)
func RunSQL(req *proto.RunSQLRequest) (*proto.SQLResult, error) {
dbmInfo, err := dao.FindDBManageByID(req.DB_ID)
if err != nil {
return nil, err
}
if dbmInfo.UserID != req.UserID {
return nil, errors.New("unauthorized access to the database management system")
}
db_, err := GetGORMDBObject(&dbmInfo)
if err != nil {
return nil, err
}
res, err := dao.RunSQLWithOrder(req.SQL, db_)
if err != nil {
return nil, err
}
// 记录执行历史
history := &proto.SQLRunHistory{UserID: req.UserID, DB_ID: req.DB_ID, SQL: req.SQL, Status: 0}
_, err = dao.CreateDBRunHistory(history)
if err != nil {
return nil, err
}
return &res, nil
}
func GetGORMDBObject(dbmInfo *proto.DBManage) (db_ *gorm.DB, err error) {
//dao.DBMMapRWMutex.RLock()
if dao.DBMMap != nil {
dbValue := dao.DBMMap[dbmInfo.ID]
if dbValue != nil {
dbValue.LastUserTime = worker.GetCurrentTimestamp()
return dbValue.Value, nil
}
}
//dao.DBMMapRWMutex.RUnlock()
switch dbmInfo.DB_Type {
case proto.DB_TYPE_MYSQL: // MySQL
dsn := dbmInfo.DB_User + ":" + dbmInfo.DB_Password + "@tcp(" + dbmInfo.DB_IP + ":" + strconv.Itoa(int(dbmInfo.DB_Port)) + ")/" + dbmInfo.DB_NAME + "?charset=utf8mb4&parseTime=True&loc=Local"
db_, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
return nil, err
}
case proto.DB_TYPE_POSTGRES: // PostgreSQL
dsn := "host=" + dbmInfo.DB_IP + " user=" + dbmInfo.DB_User + " password=" + dbmInfo.DB_Password + " dbname=" + dbmInfo.DB_NAME + " port=" + strconv.Itoa(int(dbmInfo.DB_Port)) + " sslmode=disable TimeZone=Asia/Shanghai"
db_, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
if err != nil {
return nil, err
}
default:
err = errors.New("unsupported database type")
}
dao.DBMMapRWMutex.Lock()
var dbValue proto.DBValue
dbValue.Value = db_
dbValue.LastUserTime = worker.GetCurrentTimestamp()
dao.DBMMap[dbmInfo.ID] = &dbValue
dao.DBMMapRWMutex.Unlock()
return db_, err
}
func CreateDBManage(req *proto.CreateDBManageReq, userID uint) (proto.DBManage, error) {
dbmInfo := proto.DBManage{
UserID: userID,
DB_IP: req.DB_IP,
DB_Port: req.DB_Port,
DB_NAME: req.DB_NAME,
DB_User: req.DB_User,
DB_Password: req.DB_Password,
DB_Type: req.DB_Type,
DB_Desc: req.DB_Desc,
DB_STATUS: 0, // 初始状态为未连接
}
id, err := dao.CreateDBManage(dbmInfo)
if err != nil {
return proto.DBManage{}, err
}
dbmInfo.ID = id
return dbmInfo, nil
}
func GetDBManageList(req *proto.GetDBManageReq, userID uint) ([]proto.DBManage, error) {
var dbmList []proto.DBManage
var err error
if req.GET_TYPE == 0 { // 获取自己的数据库管理
dbmList, err = dao.FindDBManageByAuthID(userID)
} else if req.GET_TYPE == 1 { // 管理员获取所有数据库管理
user := GetUserByIDFromUserCenter(int(userID))
if user.Role != "admin" {
return nil, errors.New("unauthorized access, only admin can get all database management")
}
dbmList, err = dao.FindAllDBManage()
} else {
return nil, errors.New("invalid get type")
}
if err != nil {
return nil, err
}
return dbmList, nil
}
func GetSQLRunHistory(req *proto.GetSQLRunHistoryReq, userID int) ([]proto.SQLRunHistory, error) {
var historyList []proto.SQLRunHistory
var err error
if req.GET_TYPE == 0 { // 获取自己的SQL执行历史
if req.DB_ID > 0 {
historyList, err = dao.FindDBRunHistoryByAuthIDAndDbId(userID, req.DB_ID)
} else {
historyList, err = dao.FindDBRunHistoryByAuthID(userID)
}
} else if req.GET_TYPE == 1 { // 管理员获取所有SQL执行历史
user := GetUserByIDFromUserCenter(userID)
if user.Role != "admin" {
return nil, errors.New("unauthorized access, only admin can get all SQL run history")
}
historyList, err = dao.FindAllSQLRunHistory()
} else {
return nil, errors.New("invalid get type")
}
if err != nil {
return nil, err
}
return historyList, nil
}
func UpdateDBManage(req *proto.UpdateDBManageReq, userID int) (proto.DBManage, error) {
dbmInfo, err := dao.FindDBManageByID(req.DB_ID)
if err != nil {
return proto.DBManage{}, err
}
if dbmInfo.UserID != uint(userID) && GetUserByIDFromUserCenter(userID).Role != "admin" {
return proto.DBManage{}, errors.New("unauthorized access to the database management system")
}
dbmInfo.DB_IP = req.DB_IP
dbmInfo.DB_Port = req.DB_Port
dbmInfo.DB_NAME = req.DB_NAME
dbmInfo.DB_User = req.DB_User
dbmInfo.DB_Password = req.DB_Password
dbmInfo.DB_Type = req.DB_Type
dbmInfo.DB_Desc = req.DB_Desc
err = dao.UpdateDBManage(dbmInfo.ID, &dbmInfo)
if err != nil {
return proto.DBManage{}, err
}
return dbmInfo, nil
}
func DeleteDBManage(req *proto.DeleteDBManageReq, userId int) error {
user := GetUserByIDFromUserCenter(userId)
if req.Del_Type == 0 && req.DB_ID > 0 {
dbmInfo, err := dao.FindDBManageByID(req.DB_ID)
if err != nil {
return err
}
if dbmInfo.UserID != uint(req.UserID) && user.Role != "admin" {
return errors.New("unauthorized access to the database management system")
}
err = dao.DeleteDBManageByID(req.DB_ID)
if err != nil {
return err
}
} else if req.Del_Type == 1 && req.UserID > 0 {
if req.UserID != uint(userId) && user.Role != "admin" {
return errors.New("unauthorized access to delete all database management systems")
}
err := dao.DeleteDBManageByUserID(req.UserID)
if err != nil {
return err
}
} else {
return errors.New("invalid delete type or parameters")
}
return nil
}
func DeleteSQLRunHistory(req *proto.DeleteDBManageSQLHistoryReq, userId int) error {
user := GetUserByIDFromUserCenter(userId)
if req.Del_Type == 0 && req.History_ID > 0 {
history, err := dao.FindDBRunHistoryByID(req.History_ID)
if err != nil {
return err
}
if history.UserID != uint(req.UserID) && user.Role != "admin" {
return errors.New("unauthorized access to the SQL run history")
}
err = dao.DelSQLRunHistoryByID(req.History_ID)
if err != nil {
return err
}
} else if req.Del_Type == 1 && req.UserID > 0 {
if req.UserID != uint(userId) && user.Role != "admin" {
return errors.New("unauthorized access to delete all SQL run history")
}
err := dao.DelSQLRunHistoryByAuthID(int(req.UserID))
return err
} else {
return errors.New("invalid delete type or parameters")
}
return nil
}
func GetDBTableDesc(req *proto.GetDBTableDescReq, userId int) (*proto.SQLResult, error) {
//dbmInfo, err := dao.FindDBManageByID(req.DB_ID)
//if err != nil {`
// return nil, err
//}
//if dbmInfo.UserID != uint(userId) && GetUserByIDFromUserCenter(userId).Role != "admin" {
// return nil, errors.New("unauthorized access to the database management system")
//}
//db_, err := GetGORMDBObject(&dbmInfo)
//if err != nil {
// return nil, err
//}
//res, err := dao.GetDBTableDesc(db_, req.Table, req.GetType)
//if err != nil {
// return nil, err
//}
return nil, nil
}
func DelDBMMap() {
dao.DBMMapRWMutex.Lock()
cur := worker.GetCurrentTimestamp()
for k, v := range dao.DBMMap {
if (cur - v.LastUserTime) > proto.DBMMap_Max_Keep_Time {
delete(dao.DBMMap, k) //删除
}
}
dao.DBMMapRWMutex.Unlock()
}

View File

@ -6,6 +6,7 @@ import (
"log"
"os/exec"
"strings"
"time"
"videoplayer/dao"
"videoplayer/proto"
"videoplayer/worker"
@ -29,7 +30,26 @@ func DeleteShellByID(id, authId uint) bool {
}
func UpdateShellByID(id, authId uint, shellName, shellContent, server string, status int, shellResult string) bool {
return dao.UpdateShellByID(id, authId, shellName, shellContent, status, shellResult)
return dao.UpdateShellByID(id, authId, shellName, shellContent, status, shellResult, 0, 0)
}
func UpdateShellByIDV2(id, authId uint, shellName, shellContent, server string, status int, shellResult string, shellRuntime float64) bool {
//查看shell是否存在
pd := dao.FindShellByID(id, authId)
if len(pd) < 1 && pd[0].ID == 0 {
return false
}
shell := pd[0]
//如果状态为2,3转为0,1是不允许的为了防止出现1确认包阻塞问题
if (shell.Status == 2 || shell.Status == 3) && (status == 0 || status == 1) {
log.Println("UpdateShellByIDV2: status change from 2/3 to 0/1 is not allowed, shell id:", id)
return false
}
var elapsed float64 //持续时间
if (shell.Status == 0 || shell.Status == 1) && (status == 2 || status == 3) { //如果状态为执行中且新更新时间状态为2或3则获取持续时间
elapsed = time.Since(shell.CreatedAt).Seconds()
}
return dao.UpdateShellByID(id, authId, shellName, shellContent, status, shellResult, shellRuntime, elapsed)
}
func FindShellWillRunByServer(server string, uid int) ([]dao.Shell, error) {
@ -43,7 +63,7 @@ func FindShellWillRunByServer(server string, uid int) ([]dao.Shell, error) {
shells = dao.FindShellWillRunByServer(server, uint(uid))
//设置状态为执行中
for _, v := range shells {
dao.UpdateShellByID(v.ID, uint(uid), v.ShellName, v.ShellContent, v.Status+1, v.ShellResult)
dao.UpdateShellByID(v.ID, uint(uid), v.ShellName, v.ShellContent, v.Status+1, v.ShellResult, 0, 0) //将状态设置为执行中
}
return shells, err
}
@ -58,11 +78,14 @@ func ShellWillRunFromServer() {
for _, v := range shells {
//执行shell脚本,go执行命令
start := time.Now()
res, err2 := RunShell(v.ShellContent)
//执行时间,转成秒
shellRuntime := time.Since(start).Seconds()
if err2 != "" {
resp = append(resp, proto.UpdateShellReq{ID: v.ID, Server: v.Server, Status: 2, ShellResult: err2})
resp = append(resp, proto.UpdateShellReq{ID: v.ID, Server: v.Server, Status: 3, ShellResult: "err:" + err2 + "\nresult:" + res, ShellRuntime: shellRuntime}) //执行出错
} else {
resp = append(resp, proto.UpdateShellReq{ID: v.ID, Server: v.Server, Status: 2, ShellResult: res})
resp = append(resp, proto.UpdateShellReq{ID: v.ID, Server: v.Server, Status: 2, ShellResult: res, ShellRuntime: shellRuntime}) //执行成功
}
}
if len(resp) == 0 {

View File

@ -1,9 +1,12 @@
package service
import (
"encoding/json"
"errors"
"fmt"
"log"
"regexp"
"strconv"
"time"
"videoplayer/proto"
"videoplayer/worker"
@ -184,3 +187,166 @@ func DelMonitorDeviceListWithStatus(userId int, deviceReq []proto.GetMonitorDevi
}
return delDevices, err
}
// 更新token密钥
func SyncTokenSecretFromUserCenter() {
secretSettings, err := GetTokenSecretFromUserCenter()
if err != nil {
log.Println("SyncTokenSecretFromUserCenter error:", err)
return
}
//写入redis
secretSettingsBytes, err2 := json.Marshal(secretSettings)
if err2 != nil {
log.Println("SyncTokenSecretFromUserCenter json marshal error:", err2)
return
}
if proto.SyncSecretReqLog%100 == 0 {
log.Println("SyncTokenSecretFromUserCenter req data:", string(secretSettingsBytes))
}
worker.SetRedis("secret_sync_settings", string(secretSettingsBytes)) //将密钥信息存入redis
if secretSettings.Curr != "" && secretSettings.Curr != proto.Config.TOKEN_SECRET && secretSettings.Next == "" { //如果当前密钥不为空且不等于配置文件中的密钥,并且下一个密钥为空,则需要更新配置文件中的密钥
log.Printf("SyncTokenSecretFromUserCenter current secret is not equal to config secret, current: %s, config: %s\n", secretSettings.Curr, proto.Config.TOKEN_SECRET)
//如果当前密钥与配置文件中的密钥不一致,则需要更新配置文件中的密钥
proto.SigningKeyRWLock.Lock()
proto.SigningKey = []byte(secretSettings.Curr)
proto.Config.TOKEN_SECRET = secretSettings.Curr
proto.SigningKeyRWLock.Unlock()
proto.SigningKeyIsValid = true
//配置写回文件
go proto.WriteConfigToFile()
log.Println("SyncTokenSecretFromUserCenter current secret updated successfully")
}
if secretSettings.Next == "" {
log.Println("SyncTokenSecretFromUserCenter secret is empty")
} else if proto.SyncSecretReqLog%100 == 0 {
go SetNextSecretToCurrent(*secretSettings) //异步设置下一个密钥为当前密钥
}
proto.SyncSecretReqLog++ //记录同步密钥请求次数
}
func SetNextSecretToCurrent(secret_copy proto.SecretSyncSettings) {
var secret_sync_settings proto.SecretSyncSettings
redisKey := "secret_sync_settings"
settingsStr := worker.GetRedis(redisKey)
err := json.Unmarshal([]byte(settingsStr), &secret_sync_settings)
if err != nil {
log.Println("Error decoding secret sync settings:", err)
} else {
//如果当前密钥的下一个密钥与传入的密钥不一致,则不进行设置
if secret_copy.Next != secret_sync_settings.Next {
return
}
//获取需要等待时间
waitTime := secret_sync_settings.NextStartTimestamp - worker.GetCurrentTimestamp()
if waitTime > 0 {
log.Printf("Waiting for %d seconds before setting the next secret as current secret\n", waitTime)
time.Sleep(time.Duration(waitTime) * time.Second) //等待时间
} else {
log.Println("No need to wait, setting the next secret as current secret immediately")
}
//设置下一个密钥为当前密钥
secret_sync_settings.Prev = secret_sync_settings.Curr
secret_sync_settings.PrevEndTimestamp = worker.GetCurrentTimestamp()
secret_sync_settings.Curr = secret_sync_settings.Next
secret_sync_settings.Next = ""
secret_sync_settings.CurrStartTimestamp = secret_sync_settings.PrevEndTimestamp
proto.SigningKeyIsValid = true
//设置当前程序的密钥
//获取写锁
proto.SigningKeyRWLock.Lock()
defer proto.SigningKeyRWLock.Unlock()
proto.SigningKey = []byte(secret_sync_settings.Curr)
proto.Config.TOKEN_SECRET = secret_sync_settings.Curr
//配置写回文件
go proto.WriteConfigToFile()
}
settinsStr, err2 := json.Marshal(secret_sync_settings)
if err2 != nil {
log.Println("Error encoding set secret sync settings:", err2)
return
}
worker.SetRedis(redisKey, string(settinsStr)) //将当前的密钥信息存入redis
}
// 获取token密钥请求
func GetTokenSecretFromUserCenter() (*proto.SecretSyncSettings, error) {
url := "https://uc.ljsea.top/tool/sync_system_config"
var req proto.SyncSystemConfigRequest
proto.SigningKeyRWLock.Lock()
defer proto.SigningKeyRWLock.Unlock()
req.SecretKeyMd5 = worker.GenerateMD5(string(proto.SigningKey))
req.DeviceApp = proto.Config.APP_ID
req.Timestamp = worker.GetCurrentTimestamp()
req.Sign = worker.GenerateMD5(req.SecretKeyMd5 + req.DeviceApp + strconv.FormatInt(req.Timestamp, 10))
reqBytes, err2 := json.Marshal(req)
if err2 != nil {
log.Println("GetTokenSecretFromUserCenter json marshal error:", err2)
return nil, err2
}
err, resp := worker.DoPostRequestJSON(url, reqBytes, nil)
if err != nil {
log.Println("GetTokenSecretFromUserCenter post request error:", err)
return nil, err
}
var respObject proto.RequestSyncSecretResp
err = json.Unmarshal(resp, &respObject)
if err != nil {
log.Println("GetTokenSecretFromUserCenter json unmarshal error:", err)
return nil, err
}
if respObject.Code != 0 {
if respObject.Code == proto.SigningKeyVersionIsTooOld {
proto.SigningKeyIsValid = false //设置当前密钥无效
}
log.Println("GetTokenSecretFromUserCenter error code:", respObject.Code, "\t, message:", respObject.Message)
return nil, fmt.Errorf("GetTokenSecretFromUserCenter error code: %d, message: %s", respObject.Code, respObject.Message)
}
//对称加密密钥。通过密钥加 secret_key 取md5
secretKeyMd5 := worker.GenerateMD5(proto.Config.TOKEN_SECRET + "_sync_secret")
//解密返回数据
dataContent, err2 := worker.AESDecrypt(respObject.Data, []byte(secretKeyMd5))
if err2 != nil {
log.Println("GetTokenSecretFromUserCenter aes decrypt error:", err2, "\t, secret:", proto.Config.TOKEN_SECRET, "\t, secretKey:", secretKeyMd5, "\t, data:", respObject.Data)
return nil, err2
}
var secretResp proto.SecretSyncSettings
err = json.Unmarshal(dataContent, &secretResp)
if err != nil {
log.Println("GetTokenSecretFromUserCenter json unmarshal error:", err)
return nil, err
}
return &secretResp, nil
}
// 获取cid正在运行
func GetCIDRunningList(user_id int, req_type int) ([]proto.CIDRunning, error) {
var err error
var resp []proto.CIDRunning
if req_type == 0 {
proto.CID_RunningMutex.RLock()
resp = proto.CID_Running_Map[user_id]
proto.CID_RunningMutex.RUnlock()
} else if req_type == 1 {
user := GetUserByIDFromUserCenter(user_id)
if user.Role != "admin" {
err = errors.New("no permission")
} else {
proto.CID_RunningMutex.RLock()
for _, v := range proto.CID_Running_Map {
resp = append(resp, v...)
}
proto.CID_RunningMutex.RUnlock()
}
} else {
err = errors.New("request type is error")
}
return resp, err
}

186
worker/memorycache.go Normal file
View File

@ -0,0 +1,186 @@
package worker
import (
"encoding/json"
"log"
"math"
"os"
"sync"
"time"
)
// MemoryCacheValue 缓存值结构,包含值和过期时间
type MemoryCacheValue struct {
Value string `json:"value"`
ExpireAt int64 `json:"expireAt"` // 过期时间戳,秒级
}
var (
memoryCacheData = NewMemoryCache()
)
// MemoryCache 线程安全的内存缓存
type MemoryCache struct {
data map[string]MemoryCacheValue
mu sync.RWMutex
}
// NewMemoryCache 创建新的内存缓存实例
func NewMemoryCache() *MemoryCache {
return &MemoryCache{
data: make(map[string]MemoryCacheValue),
}
}
// InitStaticMemoryCache 初始化全局缓存实例
func InitStaticMemoryCache() {
// 先尝试从文件加载
ReadMemoryCacheFromJsonFile()
}
// SetWithExp 设置带过期时间的键值对
func (mc *MemoryCache) SetWithExp(key string, value string, expireAt int64) {
mc.mu.Lock()
defer mc.mu.Unlock()
mc.data[key] = MemoryCacheValue{value, expireAt}
}
// Get 获取键值,如果已过期则返回空并删除
func (mc *MemoryCache) Get(key string) string {
// 先加读锁检查
mc.mu.RLock()
value, ok := mc.data[key]
mc.mu.RUnlock()
if !ok {
return ""
}
// 检查是否过期
now := time.Now().Unix()
if value.ExpireAt > now {
return value.Value
}
// 已过期,删除该键
mc.mu.Lock()
// 二次检查,防止并发情况下已被删除
if v, exists := mc.data[key]; exists && v.ExpireAt <= now {
delete(mc.data, key)
}
mc.mu.Unlock()
return ""
}
// Set 设置永不过期的键值对
func (mc *MemoryCache) Set(key string, value string) {
mc.SetWithExp(key, value, math.MaxInt64)
}
// Del 删除指定键
func (mc *MemoryCache) Del(key string) {
mc.mu.Lock()
defer mc.mu.Unlock()
delete(mc.data, key)
}
// Clear 清空所有缓存
func (mc *MemoryCache) Clear() {
mc.mu.Lock()
defer mc.mu.Unlock()
mc.data = make(map[string]MemoryCacheValue)
}
const CRON_MAX_DEL_NUMBER = 100 // 每次清理的最大数量
// DeleteMemoryCacheCron 定时清理过期键
func DeleteMemoryCacheCron() {
memoryCacheData.mu.Lock()
defer memoryCacheData.mu.Unlock()
now := time.Now().Unix()
i := 0
for key, value := range memoryCacheData.data {
if i >= CRON_MAX_DEL_NUMBER {
break
}
if value.ExpireAt < now {
delete(memoryCacheData.data, key)
i++
}
}
}
// GetMemoryCacheFilePath 获取缓存持久化文件路径
func GetMemoryCacheFilePath() string {
if os.Getenv("OS") == "Windows_NT" {
return "C:/Users/Administrator/vp_mc.json"
}
return "/etc/vp_mc.json"
}
// WriteMemoryCacheToFile 将缓存写入文件持久化
func WriteMemoryCacheToFile() {
memoryCacheData.mu.RLock()
defer memoryCacheData.mu.RUnlock()
path := GetMemoryCacheFilePath()
data, err := json.MarshalIndent(memoryCacheData.data, "", " ")
if err != nil {
log.Println("mc write file json err:", err)
return
}
// 先写入临时文件,再原子替换,防止文件损坏
tempPath := path + ".tmp"
if err := os.WriteFile(tempPath, data, 0644); err != nil {
log.Println("mc write temp file err:", err)
return
}
if err := os.Rename(tempPath, path); err != nil {
log.Println("mc rename file err:", err)
os.Remove(tempPath) // 清理临时文件
}
}
// ReadMemoryCacheFromJsonFile 从文件加载缓存
func ReadMemoryCacheFromJsonFile() {
path := GetMemoryCacheFilePath()
_, err := os.Stat(path)
if err != nil {
log.Println("mc file not exists:", err)
return
}
file, err := os.Open(path)
if err != nil {
log.Println("mc open file err:", err)
return
}
defer file.Close()
var data map[string]MemoryCacheValue
decoder := json.NewDecoder(file)
if err := decoder.Decode(&data); err != nil {
log.Println("mc decode file err:", err)
return
}
// 过滤已过期的数据
now := time.Now().Unix()
memoryCacheData.mu.Lock()
for k, v := range data {
if v.ExpireAt > now || v.ExpireAt == math.MaxInt64 {
memoryCacheData.data[k] = v
}
}
memoryCacheData.mu.Unlock()
}
// 提供全局缓存的访问方法
func GetGlobalCache() *MemoryCache {
return memoryCacheData
}

View File

@ -1,16 +1,14 @@
package worker
import (
"context"
"encoding/json"
"fmt"
"github.com/go-redis/redis/v8"
"strconv"
"time"
"videoplayer/proto"
)
import (
"context"
"encoding/json"
"github.com/go-redis/redis/v8"
)
var RedisClient *redis.Client // Redis 客户端, 用于连接 Redis 服务器
func InitRedis() error {

View File

@ -1,13 +1,93 @@
package worker
import "math/rand"
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"fmt"
"io"
mrand "math/rand"
"time"
)
func GetRandomString(l int) string {
str := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
bytes := []byte(str)
var result []byte
for i := 0; i < l; i++ {
result = append(result, bytes[rand.Intn(len(bytes))])
result = append(result, bytes[mrand.Intn(len(bytes))])
}
return string(result)
}
func GetCurrentTimestamp() int64 {
// 获取当前时间戳
return time.Now().Unix()
}
// AESEncrypt 函数使用AES-GCM算法对明文进行加密
func AESEncrypt(plaintext []byte, key []byte) (string, error) {
// 创建AES加密块
block, err := aes.NewCipher(key)
if err != nil {
return "", err
}
// 创建GCM模式的加密器
gcm, err := cipher.NewGCM(block)
if err != nil {
return "", err
}
// 生成随机的nonce
nonce := make([]byte, gcm.NonceSize())
if _, err = io.ReadFull(rand.Reader, nonce); err != nil {
return "", err
}
// 执行加密操作
ciphertext := gcm.Seal(nonce, nonce, plaintext, nil)
// 将加密结果转换为Base64编码字符串
return base64.StdEncoding.EncodeToString(ciphertext), nil
}
// AESDecrypt 函数使用AES-GCM算法对密文进行解密
func AESDecrypt(ciphertext string, key []byte) ([]byte, error) {
// 将Base64编码的密文转换为字节切片
data, err := base64.StdEncoding.DecodeString(ciphertext)
if err != nil {
return nil, err
}
// 创建AES加密块
block, err := aes.NewCipher(key)
if err != nil {
return nil, err
}
// 创建GCM模式的解密器
gcm, err := cipher.NewGCM(block)
if err != nil {
return nil, err
}
// 提取nonce和真正的密文
nonceSize := gcm.NonceSize()
if len(data) < nonceSize {
return nil, fmt.Errorf("密文长度过短")
}
nonce, ciphertextBytes := data[:nonceSize], data[nonceSize:]
// 执行解密操作
return gcm.Open(nil, nonce, ciphertextBytes, nil)
}
func GenerateMD5(secretKey string) string {
hasher := md5.New()
hasher.Write([]byte(secretKey))
return hex.EncodeToString(hasher.Sum(nil)) // 将二进制数据转换为十六进制字符串
}