mirror of
https://github.com/cloudreve/Cloudreve.git
synced 2024-04-21 12:31:40 +00:00
Compare commits
91
Commits
3.0.0-beta2
...
3.1.0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
14f5982b47 | ||
|
|
e607311268 | ||
|
|
acc5d53bab | ||
|
|
aa3e8913ab | ||
|
|
ee0f8e964d | ||
|
|
60745ac8ba | ||
|
|
bfb5b34edc | ||
|
|
a5000c0621 | ||
|
|
e038350cf0 | ||
|
|
5af3c4e244 | ||
|
|
7ed14c4d81 | ||
|
|
869c0006c5 | ||
|
|
4c458df666 | ||
|
|
ed684420a2 | ||
|
|
2076d56f0f | ||
|
|
280308bc05 | ||
|
|
1172765c58 | ||
|
|
58856612e2 | ||
|
|
ee0f224cbb | ||
|
|
e8a6df9a86 | ||
|
|
b02d27ca0a | ||
|
|
51f66eb06b | ||
|
|
0df8a9ba65 | ||
|
|
79daf92896 | ||
|
|
8a2be58ef3 | ||
|
|
ce7784090f | ||
|
|
dfb663a6e0 | ||
|
|
cfaf20926f | ||
|
|
305497e7cb | ||
|
|
52c2422be9 | ||
|
|
1afc750dae | ||
|
|
960c886496 | ||
|
|
5d579cdadc | ||
|
|
d5fc5745b4 | ||
|
|
a732025d5a | ||
|
|
030fd4ac57 | ||
|
|
9eeb4b6d19 | ||
|
|
36e5b31f73 | ||
|
|
26d4d34837 | ||
|
|
8c547a05fd | ||
|
|
f7311f906b | ||
|
|
6006ff4d22 | ||
|
|
034ed956a3 | ||
|
|
700c5795f5 | ||
|
|
8c3287d380 | ||
|
|
304e7b502c | ||
|
|
514e069113 | ||
|
|
7b571499a7 | ||
|
|
8b68d46bdf | ||
|
|
ab3b59e63d | ||
|
|
9910f8d732 | ||
|
|
99033d61c6 | ||
|
|
e9f3a55eb8 | ||
|
|
3cc9940924 | ||
|
|
bcdf94fd93 | ||
|
|
3c09ad7c02 | ||
|
|
7be0366b1f | ||
|
|
0575b0aa92 | ||
|
|
2e342806b6 | ||
|
|
cf9dc1c24f | ||
|
|
e58fb82463 | ||
|
|
fa900b166a | ||
|
|
2e43f8ed5b | ||
|
|
554493dea4 | ||
|
|
816b537787 | ||
|
|
e07b09186d | ||
|
|
8c7d075484 | ||
|
|
46743f3c1e | ||
|
|
1a1543f190 | ||
|
|
4aef12bf7e | ||
|
|
691c9aeb7d | ||
|
|
6285e45e34 | ||
|
|
f594d0ab83 | ||
|
|
25d1735c1d | ||
|
|
c4c174f560 | ||
|
|
175c4d781f | ||
|
|
87fde687eb | ||
|
|
65cf0f57aa | ||
|
|
0eb04ed0ea | ||
|
|
96983ddc70 | ||
|
|
b98e5efb83 | ||
|
|
ff2dae80f0 | ||
|
|
32c0232105 | ||
|
|
a05a3de0e1 | ||
|
|
79f898e0a9 | ||
|
|
d1ca65461c | ||
|
|
15074015b3 | ||
|
|
e1aced0f01 | ||
|
|
75da09c339 | ||
|
|
7636e59dfe | ||
|
|
e34e67648f |
@@ -0,0 +1 @@
|
||||
custom: ["https://cloudreve.org/buy.php"]
|
||||
@@ -0,0 +1,88 @@
|
||||
name: Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
|
||||
jobs:
|
||||
|
||||
test:
|
||||
name: Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Set up Go 1.13
|
||||
uses: actions/setup-go@v1
|
||||
with:
|
||||
go-version: 1.13
|
||||
id: go
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
submodules: 'recursive'
|
||||
|
||||
- name: Get dependencies
|
||||
run: |
|
||||
go get github.com/rakyll/statik
|
||||
export PATH=$PATH:~/go/bin/
|
||||
statik -src=models -f
|
||||
|
||||
- name: Test
|
||||
run: go test -coverprofile=coverage.txt -covermode=atomic ./...
|
||||
|
||||
build:
|
||||
name: Build
|
||||
needs: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
|
||||
- name: Set up Go 1.13
|
||||
uses: actions/setup-go@v1
|
||||
with:
|
||||
go-version: 1.13
|
||||
id: go
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
clean: false
|
||||
submodules: 'recursive'
|
||||
- run: |
|
||||
git fetch --prune --unshallow --tags
|
||||
|
||||
- name: Get dependencies and build
|
||||
run: |
|
||||
go get github.com/rakyll/statik
|
||||
export PATH=$PATH:~/go/bin/
|
||||
statik -src=models -f
|
||||
sudo apt-get update
|
||||
sudo apt-get -y install gcc-mingw-w64-x86-64
|
||||
sudo apt-get -y install gcc-arm-linux-gnueabihf libc6-dev-armhf-cross
|
||||
sudo apt-get -y install gcc-aarch64-linux-gnu libc6-dev-arm64-cross
|
||||
chmod +x ./build.sh
|
||||
./build.sh -r b
|
||||
|
||||
- name: Upload binary files (windows_amd64)
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: cloudreve_windows_amd64
|
||||
path: release/cloudreve*windows_amd64.*
|
||||
|
||||
- name: Upload binary files (linux_amd64)
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: cloudreve_linux_amd64
|
||||
path: release/cloudreve*linux_amd64.*
|
||||
|
||||
- name: Upload binary files (linux_arm)
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: cloudreve_linux_arm
|
||||
path: release/cloudreve*linux_arm.*
|
||||
|
||||
- name: Upload binary files (linux_arm64)
|
||||
uses: actions/upload-artifact@v2
|
||||
with:
|
||||
name: cloudreve_linux_arm64
|
||||
path: release/cloudreve*linux_arm64.*
|
||||
@@ -1,4 +1,5 @@
|
||||
# Binaries for programs and plugins
|
||||
cloudreve
|
||||
*.exe
|
||||
*.exe~
|
||||
*.dll
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
language: go
|
||||
go:
|
||||
- 1.13.x
|
||||
node_js:
|
||||
- 12.16.3
|
||||
git:
|
||||
depth: 1
|
||||
install:
|
||||
@@ -15,6 +17,7 @@ before_deploy:
|
||||
- sudo apt-get update
|
||||
- sudo apt-get -y install gcc-mingw-w64-x86-64
|
||||
- sudo apt-get -y install gcc-arm-linux-gnueabihf libc6-dev-armhf-cross
|
||||
- sudo apt-get -y install gcc-aarch64-linux-gnu libc6-dev-arm64-cross
|
||||
- chmod +x ./build.sh
|
||||
- ./build.sh -r b
|
||||
deploy:
|
||||
|
||||
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
||||
@@ -1,2 +1,135 @@
|
||||
# Backend-V3 [](https://travis-ci.com/HFO4/Backend-V3) [](https://codecov.io/gh/HFO4/Backend-V3)
|
||||
Still in devepolment
|
||||
<h1 align="center">
|
||||
<br>
|
||||
<a href="https://cloudreve.org/" alt="logo" ><img src="https://raw.githubusercontent.com/cloudreve/frontend/master/public/static/img/logo192.png" width="150"/></a>
|
||||
<br>
|
||||
Cloudreve
|
||||
<br>
|
||||
</h1>
|
||||
|
||||
<h4 align="center">支持多家云存储驱动的公有云文件系统.</h4>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://travis-ci.com/github/cloudreve/Cloudreve/">
|
||||
<img src="https://img.shields.io/travis/com/cloudreve/Cloudreve?style=flat-square"
|
||||
alt="travis">
|
||||
</a>
|
||||
<a href="https://codecov.io/gh/cloudreve/Cloudreve"><img src="https://img.shields.io/codecov/c/github/cloudreve/Cloudreve?style=flat-square"></a>
|
||||
<a href="https://goreportcard.com/report/github.com/cloudreve/Cloudreve">
|
||||
<img src="https://goreportcard.com/badge/github.com/cloudreve/Cloudreve?style=flat-square">
|
||||
</a>
|
||||
<a href="https://github.com/cloudreve/Cloudreve/releases">
|
||||
<img src="https://img.shields.io/github/v/release/cloudreve/Cloudreve?include_prereleases&style=flat-square">
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<a href="https://demo.cloudreve.org">演示站</a> •
|
||||
<a href="https://forum.cloudreve.org/">讨论社区</a> •
|
||||
<a href="https://docs.cloudreve.org/">文档</a> •
|
||||
<a href="https://github.com/cloudreve/Cloudreve/releases">下载</a> •
|
||||
<a href="https://t.me/cloudreve_official">Telegram 群组</a> •
|
||||
<a href="#scroll-许可证">许可证</a>
|
||||
</p>
|
||||
|
||||

|
||||
|
||||
## :sparkles: 特性
|
||||
|
||||
* :cloud: 支持本机、从机、七牛、阿里云 OSS、腾讯云 COS、又拍云、OneDrive (包括世纪互联版) 作为存储端
|
||||
* :outbox_tray: 上传/下载 支持客户端直传,支持下载限速
|
||||
* 💾 可对接 Aria2 离线下载
|
||||
* 📚 在线 压缩/解压缩、多文件打包下载
|
||||
* 💻 覆盖全部存储策略的 WebDAV 协议支持
|
||||
* :zap: 拖拽上传、目录上传、流式上传处理
|
||||
* :card_file_box: 文件拖拽管理
|
||||
* :family_woman_girl_boy: 多用户、用户组
|
||||
* :link: 创建文件、目录的分享链接,可设定自动过期
|
||||
* :eye_speech_bubble: 视频、图像、音频、文本、Office 文档在线预览
|
||||
* :art: 自定义配色、黑暗模式、PWA 应用、全站单页应用
|
||||
* :rocket: All-In-One 打包,开箱即用
|
||||
* 🌈 ... ...
|
||||
|
||||
## :hammer_and_wrench: 部署
|
||||
|
||||
下载适用于您目标机器操作系统、CPU架构的主程序,直接运行即可。
|
||||
|
||||
```shell
|
||||
# 解压程序包
|
||||
tar -zxvf cloudreve_VERSION_OS_ARCH.tar.gz
|
||||
|
||||
# 赋予执行权限
|
||||
chmod +x ./cloudreve
|
||||
|
||||
# 启动 Cloudreve
|
||||
./cloudreve
|
||||
```
|
||||
|
||||
以上为最简单的部署示例,您可以参考 [文档 - 起步](https://docs.cloudreve.org/) 进行更为完善的部署。
|
||||
|
||||
## :gear: 构建
|
||||
|
||||
自行构建前需要拥有 `Go >= 1.13`、`yarn`等必要依赖。
|
||||
|
||||
#### 克隆代码
|
||||
|
||||
```shell
|
||||
git clone --recurse-submodules https://github.com/cloudreve/Cloudreve.git
|
||||
```
|
||||
|
||||
#### 构建静态资源
|
||||
|
||||
```shell
|
||||
# 进入前端子模块
|
||||
cd assets
|
||||
# 安装依赖
|
||||
yarn install
|
||||
# 开始构建
|
||||
yarn run build
|
||||
```
|
||||
|
||||
#### 嵌入静态资源
|
||||
|
||||
```shell
|
||||
# 回到项目主目录
|
||||
cd ../
|
||||
|
||||
# 安装 statik, 用于嵌入静态资源
|
||||
go get github.com/rakyll/statik
|
||||
|
||||
# 开始嵌入
|
||||
statik -src=assets/build/ -include=*.html,*.js,*.json,*.css,*.png,*.svg,*.ico -f
|
||||
```
|
||||
|
||||
#### 编译项目
|
||||
|
||||
```shell
|
||||
# 获得当前版本号、Commit
|
||||
export COMMIT_SHA=$(git rev-parse --short HEAD)
|
||||
export VERSION=$(git describe --tags)
|
||||
|
||||
# 开始编译
|
||||
go build -a -o cloudreve -ldflags " -X 'github.com/HFO4/cloudreve/pkg/conf.BackendVersion=$VERSION' -X 'github.com/HFO4/cloudreve/pkg/conf.LastCommit=$COMMIT_SHA'"
|
||||
```
|
||||
|
||||
你也可以使用项目根目录下的`build.sh`快速开始构建:
|
||||
|
||||
```shell
|
||||
./build.sh [-a] [-c] [-b] [-r]
|
||||
a - 构建静态资源
|
||||
c - 编译二进制文件
|
||||
b - 构建前端 + 编译二进制文件
|
||||
r - 交叉编译,构建用于release的版本
|
||||
```
|
||||
|
||||
## :alembic: 技术栈
|
||||
|
||||
* [Go ](https://golang.org/) + [Gin](https://github.com/gin-gonic/gin)
|
||||
* [React](https://github.com/facebook/react) + [Redux](https://github.com/reduxjs/redux) + [Material-UI](https://github.com/mui-org/material-ui)
|
||||
|
||||
## :scroll: 许可证
|
||||
|
||||
GPL V3
|
||||
|
||||
---
|
||||
> GitHub [@HFO4](https://github.com/HFO4) ·
|
||||
> Twitter [@abslant00](https://twitter.com/abslant00)
|
||||
|
||||
+1
-1
Submodule assets updated: 53aa9ace96...54f4e608bd
+37
-1
@@ -1,8 +1,12 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/HFO4/cloudreve/pkg/conf"
|
||||
"github.com/HFO4/cloudreve/pkg/request"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/hashicorp/go-version"
|
||||
)
|
||||
|
||||
// InitApplication 初始化应用常量
|
||||
@@ -14,8 +18,40 @@ func InitApplication() {
|
||||
/ /___| | (_) | |_| | (_| | | | __/\ V / __/
|
||||
\____/|_|\___/ \__,_|\__,_|_| \___| \_/ \___|
|
||||
|
||||
V` + conf.BackendVersion + ` Commit #` + conf.LastCommit + ` Pro=` + conf.IsPro + `
|
||||
V` + conf.BackendVersion + ` Commit #` + conf.LastCommit + ` Pro=` + conf.IsPro + `
|
||||
================================================
|
||||
|
||||
`)
|
||||
go CheckUpdate()
|
||||
}
|
||||
|
||||
type GitHubRelease struct {
|
||||
URL string `json:"html_url"`
|
||||
Name string `json:"name"`
|
||||
Tag string `json:"tag_name"`
|
||||
}
|
||||
|
||||
// CheckUpdate 检查更新
|
||||
func CheckUpdate() {
|
||||
client := request.HTTPClient{}
|
||||
res, err := client.Request("GET", "https://api.github.com/repos/cloudreve/cloudreve/releases", nil).GetResponse()
|
||||
if err != nil {
|
||||
util.Log().Warning("更新检查失败, %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
var list []GitHubRelease
|
||||
if err := json.Unmarshal([]byte(res), &list); err != nil {
|
||||
util.Log().Warning("更新检查失败, %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
if len(list) > 0 {
|
||||
present, err1 := version.NewVersion(conf.BackendVersion)
|
||||
latest, err2 := version.NewVersion(list[0].Tag)
|
||||
if err1 == nil && err2 == nil && latest.GreaterThan(present) {
|
||||
util.Log().Info("有新的版本 [%s] 可用,下载:%s", list[0].Name, list[0].URL)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+110
-1
@@ -1,17 +1,29 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"github.com/HFO4/cloudreve/pkg/conf"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
_ "github.com/HFO4/cloudreve/statik"
|
||||
"github.com/gin-contrib/static"
|
||||
"github.com/rakyll/statik/fs"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"path"
|
||||
)
|
||||
|
||||
const StaticFolder = "statics"
|
||||
|
||||
type GinFS struct {
|
||||
FS http.FileSystem
|
||||
}
|
||||
|
||||
type staticVersion struct {
|
||||
Name string `json:"name"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
|
||||
// StaticFS 内置静态文件资源
|
||||
var StaticFS static.ServeFileSystem
|
||||
|
||||
@@ -34,9 +46,44 @@ func (b *GinFS) Exists(prefix string, filepath string) bool {
|
||||
func InitStatic() {
|
||||
var err error
|
||||
|
||||
if util.Exists(util.RelativePath("statics")) {
|
||||
if util.Exists(util.RelativePath(StaticFolder)) {
|
||||
util.Log().Info("检测到 statics 目录存在,将使用此目录下的静态资源文件")
|
||||
StaticFS = static.LocalFile(util.RelativePath("statics"), false)
|
||||
|
||||
// 检查静态资源的版本
|
||||
f, err := StaticFS.Open("version.json")
|
||||
if err != nil {
|
||||
util.Log().Warning("静态资源版本标识文件不存在,请重新构建或删除 statics 目录")
|
||||
return
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(f)
|
||||
if err != nil {
|
||||
util.Log().Warning("无法读取静态资源文件版本,请重新构建或删除 statics 目录")
|
||||
return
|
||||
}
|
||||
|
||||
var v staticVersion
|
||||
if err := json.Unmarshal(b, &v); err != nil {
|
||||
util.Log().Warning("无法解析静态资源文件版本, %s", err)
|
||||
return
|
||||
}
|
||||
|
||||
staticName := "cloudreve-frontend"
|
||||
if conf.IsPro == "true" {
|
||||
staticName += "-pro"
|
||||
}
|
||||
|
||||
if v.Name != staticName {
|
||||
util.Log().Warning("静态资源版本不匹配,请重新构建或删除 statics 目录")
|
||||
return
|
||||
}
|
||||
|
||||
if v.Version != conf.RequiredStaticVersion {
|
||||
util.Log().Warning("静态资源版本不匹配 [当前 %s, 需要: %s],请重新构建或删除 statics 目录", v.Version, conf.RequiredStaticVersion)
|
||||
return
|
||||
}
|
||||
|
||||
} else {
|
||||
StaticFS = &GinFS{}
|
||||
StaticFS.(*GinFS).FS, err = fs.New()
|
||||
@@ -46,3 +93,65 @@ func InitStatic() {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Eject 抽离内置静态资源
|
||||
func Eject() {
|
||||
staticFS, err := fs.New()
|
||||
if err != nil {
|
||||
util.Log().Panic("无法初始化静态资源, %s", err)
|
||||
}
|
||||
|
||||
root, err := staticFS.Open("/")
|
||||
if err != nil {
|
||||
util.Log().Panic("根目录不存在, %s", err)
|
||||
}
|
||||
|
||||
var walk func(relPath string, object http.File)
|
||||
walk = func(relPath string, object http.File) {
|
||||
stat, err := object.Stat()
|
||||
if err != nil {
|
||||
util.Log().Error("无法获取[%s]的信息, %s, 跳过...", relPath, err)
|
||||
return
|
||||
}
|
||||
|
||||
if !stat.IsDir() {
|
||||
// 写入文件
|
||||
out, err := util.CreatNestedFile(util.RelativePath(StaticFolder + relPath))
|
||||
defer out.Close()
|
||||
|
||||
if err != nil {
|
||||
util.Log().Error("无法创建文件[%s], %s, 跳过...", relPath, err)
|
||||
return
|
||||
}
|
||||
|
||||
util.Log().Info("导出 [%s]...", relPath)
|
||||
if _, err := io.Copy(out, object); err != nil {
|
||||
util.Log().Error("无法写入文件[%s], %s, 跳过...", relPath, err)
|
||||
return
|
||||
}
|
||||
} else {
|
||||
// 列出目录
|
||||
objects, err := object.Readdir(0)
|
||||
if err != nil {
|
||||
util.Log().Error("无法步入子目录[%s], %s, 跳过...", relPath, err)
|
||||
return
|
||||
}
|
||||
|
||||
// 递归遍历子目录
|
||||
for _, newObject := range objects {
|
||||
newPath := path.Join(relPath, newObject.Name())
|
||||
newRoot, err := staticFS.Open(newPath)
|
||||
if err != nil {
|
||||
util.Log().Error("无法打开对象[%s], %s, 跳过...", newPath, err)
|
||||
continue
|
||||
}
|
||||
walk(newPath, newRoot)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
util.Log().Info("开始导出内置静态资源...")
|
||||
walk("/", root)
|
||||
util.Log().Info("内置静态资源导出完成")
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ buildAssets () {
|
||||
fi
|
||||
|
||||
cd $REPO
|
||||
statik -src=assets/build/ -include=*.html,*.js,*.json,*.css,*.png,*.svg,*.ico -f
|
||||
statik -src=assets/build/ -include=*.html,*.js,*.json,*.css,*.png,*.svg,*.ico,*.ttf -f
|
||||
}
|
||||
|
||||
buildBinary () {
|
||||
@@ -55,7 +55,12 @@ _build() {
|
||||
export CC=$gcc
|
||||
export CGO_ENABLED=1
|
||||
|
||||
out="release/cloudreve_${VERSION}_${os}_${arch}"
|
||||
if [ -n "$VERSION" ]; then
|
||||
out="release/cloudreve_${VERSION}_${os}_${arch}"
|
||||
else
|
||||
out="release/cloudreve_${COMMIT_SHA}_${os}_${arch}"
|
||||
fi
|
||||
|
||||
go build -a -o "${out}" -ldflags " -X 'github.com/HFO4/cloudreve/pkg/conf.BackendVersion=$VERSION' -X 'github.com/HFO4/cloudreve/pkg/conf.LastCommit=$COMMIT_SHA'"
|
||||
|
||||
if [ "$os" = "windows" ]; then
|
||||
@@ -72,7 +77,7 @@ _build() {
|
||||
release(){
|
||||
cd $REPO
|
||||
## List of architectures and OS to test coss compilation.
|
||||
SUPPORTED_OSARCH="linux/amd64/gcc linux/arm/arm-linux-gnueabihf-gcc windows/amd64/x86_64-w64-mingw32-gcc"
|
||||
SUPPORTED_OSARCH="linux/amd64/gcc linux/arm/arm-linux-gnueabihf-gcc windows/amd64/x86_64-w64-mingw32-gcc linux/arm64/aarch64-linux-gnu-gcc"
|
||||
|
||||
echo "Release builds for OS/Arch/CC: ${SUPPORTED_OSARCH}"
|
||||
for each_osarch in ${SUPPORTED_OSARCH}; do
|
||||
|
||||
@@ -9,6 +9,7 @@ require (
|
||||
github.com/duo-labs/webauthn v0.0.0-20191119193225-4bf9a0f776d4
|
||||
github.com/fatih/color v1.7.0
|
||||
github.com/gin-contrib/cors v1.3.0
|
||||
github.com/gin-contrib/gzip v0.0.2-0.20200226035851-25bef2ef21e8
|
||||
github.com/gin-contrib/sessions v0.0.1
|
||||
github.com/gin-contrib/static v0.0.0-20191128031702-f81c604d8ac2
|
||||
github.com/gin-gonic/gin v1.5.0
|
||||
@@ -18,6 +19,7 @@ require (
|
||||
github.com/gomodule/redigo v2.0.0+incompatible
|
||||
github.com/google/go-querystring v1.0.0
|
||||
github.com/gorilla/websocket v1.4.1
|
||||
github.com/hashicorp/go-version v1.2.0
|
||||
github.com/jinzhu/gorm v1.9.11
|
||||
github.com/juju/ratelimit v1.0.1
|
||||
github.com/mattn/go-colorable v0.1.4 // indirect
|
||||
|
||||
@@ -48,6 +48,8 @@ github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5Kwzbycv
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/gin-contrib/cors v1.3.0 h1:PolezCc89peu+NgkIWt9OB01Kbzt6IP0J/JvkG6xxlg=
|
||||
github.com/gin-contrib/cors v1.3.0/go.mod h1:artPvLlhkF7oG06nK8v3U8TNz6IeX+w1uzCSEId5/Vc=
|
||||
github.com/gin-contrib/gzip v0.0.2-0.20200226035851-25bef2ef21e8 h1:/DnKeA2+K83hkii3nqMJ5koknI+/qlojjxgcSyiAyJw=
|
||||
github.com/gin-contrib/gzip v0.0.2-0.20200226035851-25bef2ef21e8/go.mod h1:M+xPw/lXk+uAU4iYVnwPZs0iIpR/KwSQSXcJabN+gPs=
|
||||
github.com/gin-contrib/sessions v0.0.1 h1:xr9V/u3ERQnkugKSY/u36cNnC4US4bHJpdxcB6eIZLk=
|
||||
github.com/gin-contrib/sessions v0.0.1/go.mod h1:iziXm/6pvTtf7og1uxT499sel4h3S9DfwsrhNZ+REXM=
|
||||
github.com/gin-contrib/sse v0.0.0-20190301062529-5545eab6dad3 h1:t8FVkw33L+wilf2QiWkw0UV77qRpcH/JHPKGpKa2E8g=
|
||||
@@ -116,6 +118,8 @@ github.com/gorilla/sessions v1.1.3 h1:uXoZdcdA5XdXF3QzuSlheVRUvjl+1rKY7zBXL68L9R
|
||||
github.com/gorilla/sessions v1.1.3/go.mod h1:8KCfur6+4Mqcc6S0FEfKuN15Vl5MgXW92AE8ovaJD0w=
|
||||
github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM=
|
||||
github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/hashicorp/go-version v1.2.0 h1:3vNe/fWF5CBgRIguda1meWhsZHy3m8gCJ5wx+dIzX/E=
|
||||
github.com/hashicorp/go-version v1.2.0/go.mod h1:fltr4n8CU8Ke44wwGCBoEymUuxUHl09ZGVZPK5anwXA=
|
||||
github.com/hashicorp/golang-lru v0.5.0/go.mod h1:/m3WP610KZHVQ1SGc6re/UDhFvYD7pJ4Ao+sR/qLZy8=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/jinzhu/gorm v1.9.11 h1:gaHGvE+UnWGlbWG4Y3FUwY1EcZ5n6S9WtqBA/uySMLE=
|
||||
|
||||
@@ -8,16 +8,38 @@ import (
|
||||
"github.com/HFO4/cloudreve/routers"
|
||||
)
|
||||
|
||||
var confPath string
|
||||
var (
|
||||
isEject bool
|
||||
confPath string
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.StringVar(&confPath, "c", util.RelativePath("conf.ini"), "配置文件路径")
|
||||
flag.BoolVar(&isEject, "eject", false, "导出内置静态资源")
|
||||
flag.Parse()
|
||||
bootstrap.Init(confPath)
|
||||
}
|
||||
|
||||
func main() {
|
||||
if isEject {
|
||||
// 开始导出内置静态资源文件
|
||||
bootstrap.Eject()
|
||||
return
|
||||
}
|
||||
|
||||
api := routers.InitRouter()
|
||||
|
||||
// 如果启用了SSL
|
||||
if conf.SSLConfig.CertPath != "" {
|
||||
go func() {
|
||||
util.Log().Info("开始监听 %s", conf.SSLConfig.Listen)
|
||||
if err := api.RunTLS(conf.SSLConfig.Listen,
|
||||
conf.SSLConfig.CertPath, conf.SSLConfig.KeyPath); err != nil {
|
||||
util.Log().Error("无法监听[%s],%s", conf.SSLConfig.Listen, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
util.Log().Info("开始监听 %s", conf.SystemConfig.Listen)
|
||||
if err := api.Run(conf.SystemConfig.Listen); err != nil {
|
||||
util.Log().Error("无法监听[%s],%s", conf.SystemConfig.Listen, err)
|
||||
|
||||
@@ -654,7 +654,7 @@ func TestOneDriveCallbackAuth(t *testing.T) {
|
||||
mock.ExpectQuery("SELECT(.+)users(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "group_id"}).AddRow(1, 1))
|
||||
mock.ExpectQuery("SELECT(.+)groups(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "policies"}).AddRow(1, "[522]"))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "policies"}).AddRow(1, "[657]"))
|
||||
mock.ExpectQuery("SELECT(.+)policies(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "access_key", "secret_key"}).AddRow(2, "123", "123"))
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
@@ -699,7 +699,7 @@ func TestCOSCallbackAuth(t *testing.T) {
|
||||
mock.ExpectQuery("SELECT(.+)users(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "group_id"}).AddRow(1, 1))
|
||||
mock.ExpectQuery("SELECT(.+)groups(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "policies"}).AddRow(1, "[522]"))
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "policies"}).AddRow(1, "[702]"))
|
||||
mock.ExpectQuery("SELECT(.+)policies(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "access_key", "secret_key"}).AddRow(2, "123", "123"))
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"github.com/HFO4/cloudreve/bootstrap"
|
||||
model "github.com/HFO4/cloudreve/models"
|
||||
"github.com/HFO4/cloudreve/pkg/hashid"
|
||||
"github.com/HFO4/cloudreve/pkg/serializer"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/gin-gonic/gin"
|
||||
"io/ioutil"
|
||||
)
|
||||
|
||||
// HashID 将给定对象的HashID转换为真实ID
|
||||
@@ -38,3 +41,47 @@ func IsFunctionEnabled(key string) gin.HandlerFunc {
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// InjectSiteInfo 向首页html中插入站点信息
|
||||
func InjectSiteInfo() gin.HandlerFunc {
|
||||
ignoreFunc := func(c *gin.Context) {
|
||||
c.Next()
|
||||
}
|
||||
if bootstrap.StaticFS == nil {
|
||||
return ignoreFunc
|
||||
}
|
||||
|
||||
// 读取index.html
|
||||
file, err := bootstrap.StaticFS.Open("/index.html")
|
||||
if err != nil {
|
||||
util.Log().Warning("静态文件[index.html]不存在,可能会影响首页展示")
|
||||
return ignoreFunc
|
||||
}
|
||||
|
||||
fileContentBytes, err := ioutil.ReadAll(file)
|
||||
if err != nil {
|
||||
util.Log().Warning("静态文件[index.html]读取失败,可能会影响首页展示")
|
||||
return ignoreFunc
|
||||
}
|
||||
fileContent := string(fileContentBytes)
|
||||
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.URL.Path == "/" || c.Request.URL.Path == "/index.html" {
|
||||
// 读取、替换站点设置
|
||||
options := model.GetSettingByNames("siteName", "siteKeywords", "siteScript",
|
||||
"pwa_small_icon")
|
||||
finalHTML := util.Replace(map[string]string{
|
||||
"{siteName}": options["siteName"],
|
||||
"{siteDes}": options["siteDes"],
|
||||
"{siteScript}": options["siteScript"],
|
||||
"{pwa_small_icon}": options["pwa_small_icon"],
|
||||
}, fileContent)
|
||||
|
||||
c.Header("Content-Type", "text/html")
|
||||
c.String(200, finalHTML)
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
+109
-2
@@ -1,12 +1,17 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/HFO4/cloudreve/bootstrap"
|
||||
"github.com/HFO4/cloudreve/pkg/cache"
|
||||
"github.com/HFO4/cloudreve/pkg/hashid"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
testMock "github.com/stretchr/testify/mock"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -62,7 +67,6 @@ func TestIsFunctionEnabled(t *testing.T) {
|
||||
c.Params = []gin.Param{}
|
||||
c.Request, _ = http.NewRequest("POST", "/api/v3/file/dellete/1", nil)
|
||||
TestFunc(c)
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.True(c.IsAborted())
|
||||
}
|
||||
// 开启
|
||||
@@ -72,7 +76,110 @@ func TestIsFunctionEnabled(t *testing.T) {
|
||||
c.Params = []gin.Param{}
|
||||
c.Request, _ = http.NewRequest("POST", "/api/v3/file/dellete/1", nil)
|
||||
TestFunc(c)
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.False(c.IsAborted())
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
type StaticMock struct {
|
||||
testMock.Mock
|
||||
}
|
||||
|
||||
func (m StaticMock) Open(name string) (http.File, error) {
|
||||
args := m.Called(name)
|
||||
return args.Get(0).(http.File), args.Error(1)
|
||||
}
|
||||
|
||||
func (m StaticMock) Exists(prefix string, filepath string) bool {
|
||||
args := m.Called(prefix, filepath)
|
||||
return args.Bool(0)
|
||||
}
|
||||
|
||||
func TestInjectSiteInfo(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
// 静态资源未加载
|
||||
{
|
||||
TestFunc := InjectSiteInfo()
|
||||
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Params = []gin.Param{}
|
||||
c.Request, _ = http.NewRequest("GET", "/", nil)
|
||||
TestFunc(c)
|
||||
asserts.False(c.IsAborted())
|
||||
}
|
||||
|
||||
// index.html 不存在
|
||||
{
|
||||
testStatic := &StaticMock{}
|
||||
bootstrap.StaticFS = testStatic
|
||||
testStatic.On("Open", "/index.html").
|
||||
Return(&os.File{}, errors.New("error"))
|
||||
TestFunc := InjectSiteInfo()
|
||||
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Params = []gin.Param{}
|
||||
c.Request, _ = http.NewRequest("GET", "/", nil)
|
||||
TestFunc(c)
|
||||
asserts.False(c.IsAborted())
|
||||
}
|
||||
|
||||
// index.html 读取失败
|
||||
{
|
||||
file, _ := util.CreatNestedFile("tests/index.html")
|
||||
file.Close()
|
||||
testStatic := &StaticMock{}
|
||||
bootstrap.StaticFS = testStatic
|
||||
testStatic.On("Open", "/index.html").
|
||||
Return(file, nil)
|
||||
TestFunc := InjectSiteInfo()
|
||||
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Params = []gin.Param{}
|
||||
c.Request, _ = http.NewRequest("GET", "/", nil)
|
||||
TestFunc(c)
|
||||
asserts.False(c.IsAborted())
|
||||
}
|
||||
|
||||
// 成功且命中
|
||||
{
|
||||
file, _ := util.CreatNestedFile("tests/index.html")
|
||||
defer file.Close()
|
||||
testStatic := &StaticMock{}
|
||||
bootstrap.StaticFS = testStatic
|
||||
testStatic.On("Open", "/index.html").
|
||||
Return(file, nil)
|
||||
TestFunc := InjectSiteInfo()
|
||||
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Params = []gin.Param{}
|
||||
c.Request, _ = http.NewRequest("GET", "/", nil)
|
||||
|
||||
cache.Set("setting_siteName", "cloudreve", 0)
|
||||
cache.Set("setting_siteKeywords", "cloudreve", 0)
|
||||
cache.Set("setting_siteScript", "cloudreve", 0)
|
||||
cache.Set("setting_pwa_small_icon", "cloudreve", 0)
|
||||
|
||||
TestFunc(c)
|
||||
asserts.True(c.IsAborted())
|
||||
}
|
||||
|
||||
// 成功且未命中
|
||||
{
|
||||
file, _ := util.CreatNestedFile("tests/index.html")
|
||||
defer file.Close()
|
||||
testStatic := &StaticMock{}
|
||||
bootstrap.StaticFS = testStatic
|
||||
testStatic.On("Open", "/index.html").
|
||||
Return(file, nil)
|
||||
TestFunc := InjectSiteInfo()
|
||||
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Params = []gin.Param{}
|
||||
c.Request, _ = http.NewRequest("GET", "/2", nil)
|
||||
|
||||
TestFunc(c)
|
||||
asserts.False(c.IsAborted())
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ package middleware
|
||||
|
||||
import (
|
||||
"github.com/HFO4/cloudreve/pkg/conf"
|
||||
"github.com/HFO4/cloudreve/pkg/serializer"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-contrib/sessions/memstore"
|
||||
@@ -32,3 +33,24 @@ func Session(secret string) gin.HandlerFunc {
|
||||
Store.Options(sessions.Options{HttpOnly: true, MaxAge: 7 * 86400, Path: "/"})
|
||||
return sessions.Sessions("cloudreve-session", Store)
|
||||
}
|
||||
|
||||
// CSRFInit 初始化CSRF标记
|
||||
func CSRFInit() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
util.SetSession(c, map[string]interface{}{"CSRF": true})
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// CSRFCheck 检查CSRF标记
|
||||
func CSRFCheck() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if check, ok := util.GetSession(c, "CSRF").(bool); ok && check {
|
||||
c.Next()
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, serializer.Err(serializer.CodeNoPermissionErr, "来源非法", nil))
|
||||
c.Abort()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,8 +2,11 @@ package middleware
|
||||
|
||||
import (
|
||||
"github.com/HFO4/cloudreve/pkg/conf"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -21,6 +24,7 @@ func TestSession(t *testing.T) {
|
||||
asserts.Panics(func() {
|
||||
Session("2333")
|
||||
})
|
||||
conf.RedisConfig.Server = ""
|
||||
}
|
||||
|
||||
}
|
||||
@@ -28,3 +32,41 @@ func TestSession(t *testing.T) {
|
||||
func emptyFunc() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {}
|
||||
}
|
||||
|
||||
func TestCSRFInit(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
rec := httptest.NewRecorder()
|
||||
sessionFunc := Session("233")
|
||||
{
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request, _ = http.NewRequest("GET", "/test", nil)
|
||||
sessionFunc(c)
|
||||
CSRFInit()(c)
|
||||
asserts.True(util.GetSession(c, "CSRF").(bool))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCSRFCheck(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
rec := httptest.NewRecorder()
|
||||
sessionFunc := Session("233")
|
||||
|
||||
// 通过检查
|
||||
{
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request, _ = http.NewRequest("GET", "/test", nil)
|
||||
sessionFunc(c)
|
||||
CSRFInit()(c)
|
||||
CSRFCheck()(c)
|
||||
asserts.False(c.IsAborted())
|
||||
}
|
||||
|
||||
// 未通过检查
|
||||
{
|
||||
c, _ := gin.CreateTestContext(rec)
|
||||
c.Request, _ = http.NewRequest("GET", "/test", nil)
|
||||
sessionFunc(c)
|
||||
CSRFCheck()(c)
|
||||
asserts.True(c.IsAborted())
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -89,7 +89,7 @@ func GetFilesByKeywords(uid uint, keywords ...interface{}) ([]File, error) {
|
||||
|
||||
// 生成查询条件
|
||||
for i := 0; i < len(keywords); i++ {
|
||||
conditions += "LOWER(name) like ?"
|
||||
conditions += "name like ?"
|
||||
if i != len(keywords)-1 {
|
||||
conditions += " or "
|
||||
}
|
||||
|
||||
+3
-2
@@ -30,12 +30,13 @@ func Init() {
|
||||
} else {
|
||||
if conf.DatabaseConfig.Type == "UNSET" {
|
||||
// 未指定数据库时,使用SQLite
|
||||
db, err = gorm.Open("sqlite3", util.RelativePath("cloudreve.db"))
|
||||
db, err = gorm.Open("sqlite3", util.RelativePath(conf.DatabaseConfig.DBFile))
|
||||
} else {
|
||||
db, err = gorm.Open(conf.DatabaseConfig.Type, fmt.Sprintf("%s:%s@(%s)/%s?charset=utf8&parseTime=True&loc=Local",
|
||||
db, err = gorm.Open(conf.DatabaseConfig.Type, fmt.Sprintf("%s:%s@(%s:%d)/%s?charset=utf8&parseTime=True&loc=Local",
|
||||
conf.DatabaseConfig.User,
|
||||
conf.DatabaseConfig.Password,
|
||||
conf.DatabaseConfig.Host,
|
||||
conf.DatabaseConfig.Port,
|
||||
conf.DatabaseConfig.Name))
|
||||
}
|
||||
}
|
||||
|
||||
+9
-3
@@ -11,8 +11,7 @@ import (
|
||||
// 是否需要迁移
|
||||
func needMigration() bool {
|
||||
var setting Setting
|
||||
DB.Where("name = ?", "database_version").First(&setting)
|
||||
return setting.Value != conf.RequiredDBVersion
|
||||
return DB.Where("name = ?", "db_version_"+conf.RequiredDBVersion).First(&setting).Error != nil
|
||||
}
|
||||
|
||||
//执行数据迁移
|
||||
@@ -77,11 +76,13 @@ func addDefaultSettings() {
|
||||
defaultSettings := []Setting{
|
||||
{Name: "siteURL", Value: `http://localhost`, Type: "basic"},
|
||||
{Name: "siteName", Value: `Cloudreve`, Type: "basic"},
|
||||
{Name: "siteICPId", Value: ``, Type: "basic"},
|
||||
{Name: "register_enabled", Value: `1`, Type: "register"},
|
||||
{Name: "default_group", Value: `2`, Type: "register"},
|
||||
{Name: "siteKeywords", Value: `网盘,网盘`, Type: "basic"},
|
||||
{Name: "siteDes", Value: `Cloudreve`, Type: "basic"},
|
||||
{Name: "siteTitle", Value: `平步云端`, Type: "basic"},
|
||||
{Name: "siteScript", Value: ``, Type: "basic"},
|
||||
{Name: "fromName", Value: `Cloudreve`, Type: "mail"},
|
||||
{Name: "mail_keepalive", Value: `30`, Type: "mail"},
|
||||
{Name: "fromAdress", Value: `no-reply@acg.blue`, Type: "mail"},
|
||||
@@ -90,6 +91,7 @@ func addDefaultSettings() {
|
||||
{Name: "replyTo", Value: `abslant@126.com`, Type: "mail"},
|
||||
{Name: "smtpUser", Value: `no-reply@acg.blue`, Type: "mail"},
|
||||
{Name: "smtpPass", Value: ``, Type: "mail"},
|
||||
{Name: "smtpEncryption", Value: `0`, Type: "mail"},
|
||||
{Name: "maxEditSize", Value: `4194304`, Type: "file_edit"},
|
||||
{Name: "archive_timeout", Value: `60`, Type: "timeout"},
|
||||
{Name: "download_timeout", Value: `60`, Type: "timeout"},
|
||||
@@ -103,6 +105,7 @@ func addDefaultSettings() {
|
||||
{Name: "onedrive_callback_check", Value: `20`, Type: "timeout"},
|
||||
{Name: "aria2_call_timeout", Value: `5`, Type: "timeout"},
|
||||
{Name: "onedrive_chunk_retries", Value: `1`, Type: "retry"},
|
||||
{Name: "onedrive_source_timeout", Value: `1800`, Type: "timeout"},
|
||||
{Name: "reset_after_upload_failed", Value: `0`, Type: "upload"},
|
||||
{Name: "login_captcha", Value: `0`, Type: "login"},
|
||||
{Name: "reg_captcha", Value: `0`, Type: "login"},
|
||||
@@ -122,7 +125,7 @@ box-sizing: border-box; font-size: 14px; margin: 0;"><td style="font-family: 'He
|
||||
solid #e9e9e9;"bgcolor="#fff"><tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size:
|
||||
14px; margin: 0;"><td class="alert alert-warning"style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 16px; vertical-align: top; color: #fff; font-weight: 500; text-align: center; border-radius: 3px 3px 0 0; background-color: #2196F3; margin: 0; padding: 20px;"align="center"bgcolor="#FF9F00"valign="top">重设{siteTitle}密码</td></tr><tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;"><td class="content-wrap"style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 20px;"valign="top"><table width="100%"cellpadding="0"cellspacing="0"style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;"><tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;"><td class="content-block"style="font-family: 'Helvetica
|
||||
Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;"valign="top">亲爱的<strong style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;">{userName}</strong>:</td></tr><tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;"><td class="content-block"style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;"valign="top">请点击下方按钮完成密码重设。如果非你本人操作,请忽略此邮件。</td></tr><tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;"><td class="content-block"style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;"valign="top"><a href="{resetUrl}"class="btn-primary"style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; color: #FFF; text-decoration: none; line-height: 2em; font-weight: bold; text-align: center; cursor: pointer; display: inline-block; border-radius: 5px; text-transform: capitalize; background-color: #2196F3; margin: 0; border-color: #2196F3; border-style: solid; border-width: 10px 20px;">重设密码</a></td></tr><tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;"><td class="content-block"style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0; padding: 0 0 20px;"valign="top">感谢您选择{siteTitle}。</td></tr></table></td></tr></table><div class="footer"style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; width: 100%; clear: both; color: #999; margin: 0; padding: 20px;"><table width="100%"style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;"><tr style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; margin: 0;"><td class="aligncenter content-block"style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 12px; vertical-align: top; color: #999; text-align: center; margin: 0; padding: 0 0 20px;"align="center"valign="top">此邮件由系统自动发送,请不要直接回复。</td></tr></table></div></div></td><td style="font-family: 'Helvetica Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; vertical-align: top; margin: 0;"valign="top"></td></tr></table></body></html>`, Type: "mail_template"},
|
||||
{Name: "database_version", Value: `3.0.0-alpha1`, Type: "version"},
|
||||
{Name: "db_version_" + conf.RequiredDBVersion, Value: `installed`, Type: "version"},
|
||||
{Name: "hot_share_num", Value: `10`, Type: "share"},
|
||||
{Name: "gravatar_server", Value: `https://www.gravatar.com/`, Type: "avatar"},
|
||||
{Name: "defaultTheme", Value: `#3f51b5`, Type: "basic"},
|
||||
@@ -156,6 +159,9 @@ Neue',Helvetica,Arial,sans-serif; box-sizing: border-box; font-size: 14px; verti
|
||||
{Name: "captcha_IsShowSlimeLine", Value: "1", Type: "captcha"},
|
||||
{Name: "captcha_IsShowSineLine", Value: "0", Type: "captcha"},
|
||||
{Name: "captcha_CaptchaLen", Value: "6", Type: "captcha"},
|
||||
{Name: "captcha_IsUseReCaptcha", Value: "0", Type: "captcha"},
|
||||
{Name: "captcha_ReCaptchaKey", Value: "defaultKey", Type: "captcha"},
|
||||
{Name: "captcha_ReCaptchaSecret", Value: "defaultSecret", Type: "captcha"},
|
||||
{Name: "thumb_width", Value: "400", Type: "thumb"},
|
||||
{Name: "thumb_height", Value: "300", Type: "thumb"},
|
||||
{Name: "pwa_small_icon", Value: "/static/img/favicon.ico", Type: "pwa"},
|
||||
|
||||
+26
-3
@@ -8,7 +8,9 @@ import (
|
||||
"github.com/jinzhu/gorm"
|
||||
"net/url"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -48,6 +50,16 @@ type PolicyOption struct {
|
||||
OdRedirect string `json:"od_redirect,omitempty"`
|
||||
}
|
||||
|
||||
var thumbSuffix = map[string][]string{
|
||||
"local": {},
|
||||
"qiniu": {".psd", ".jpg", ".jpeg", ".png", ".gif", ".webp", ".tiff", ".bmp"},
|
||||
"oss": {".jpg", ".jpeg", ".png", ".gif", ".webp", ".tiff", ".bmp"},
|
||||
"cos": {".jpg", ".jpeg", ".png", ".gif", ".webp", ".tiff", ".bmp"},
|
||||
"upyun": {".svg", ".jpg", ".jpeg", ".png", ".gif", ".webp", ".tiff", ".bmp"},
|
||||
"remote": {},
|
||||
"onedrive": {"*"},
|
||||
}
|
||||
|
||||
func init() {
|
||||
// 注册缓存用到的复杂结构
|
||||
gob.Register(Policy{})
|
||||
@@ -178,6 +190,17 @@ func (policy *Policy) IsDirectlyPreview() bool {
|
||||
return policy.Type == "local"
|
||||
}
|
||||
|
||||
// IsThumbExist 给定文件名,返回此存储策略下是否可能存在缩略图
|
||||
func (policy *Policy) IsThumbExist(name string) bool {
|
||||
if list, ok := thumbSuffix[policy.Type]; ok {
|
||||
if len(list) == 1 && list[0] == "*" {
|
||||
return true
|
||||
}
|
||||
return util.ContainsString(list, strings.ToLower(filepath.Ext(name)))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// IsTransitUpload 返回此策略上传给定size文件时是否需要服务端中转
|
||||
func (policy *Policy) IsTransitUpload(size uint64) bool {
|
||||
if policy.Type == "local" {
|
||||
@@ -199,9 +222,9 @@ func (policy *Policy) IsThumbGenerateNeeded() bool {
|
||||
return policy.Type == "local"
|
||||
}
|
||||
|
||||
// IsMockThumbNeeded 返回此策略是否需要在上传后默认当图像文件
|
||||
func (policy *Policy) IsMockThumbNeeded() bool {
|
||||
return policy.Type == "onedrive"
|
||||
// CanStructureBeListed 返回存储策略是否能被前台列物理目录
|
||||
func (policy *Policy) CanStructureBeListed() bool {
|
||||
return policy.Type != "local" && policy.Type != "remote"
|
||||
}
|
||||
|
||||
// GetUploadURL 获取文件上传服务API地址
|
||||
|
||||
+53
-2
@@ -242,13 +242,64 @@ func TestPolicy_UpdateAccessKey(t *testing.T) {
|
||||
func TestPolicy_Props(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
policy := Policy{Type: "onedrive"}
|
||||
asserts.True(policy.IsMockThumbNeeded())
|
||||
asserts.False(policy.IsThumbGenerateNeeded())
|
||||
asserts.True(policy.IsPathGenerateNeeded())
|
||||
asserts.True(policy.IsTransitUpload(4))
|
||||
asserts.False(policy.IsTransitUpload(5 * 1024 * 1024))
|
||||
asserts.True(policy.CanStructureBeListed())
|
||||
policy.Type = "local"
|
||||
asserts.False(policy.IsMockThumbNeeded())
|
||||
asserts.True(policy.IsThumbGenerateNeeded())
|
||||
asserts.True(policy.IsPathGenerateNeeded())
|
||||
asserts.False(policy.CanStructureBeListed())
|
||||
}
|
||||
|
||||
func TestPolicy_IsThumbExist(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
expect bool
|
||||
policy string
|
||||
}{
|
||||
{
|
||||
"1.png",
|
||||
false,
|
||||
"unknown",
|
||||
},
|
||||
{
|
||||
"1.png",
|
||||
false,
|
||||
"local",
|
||||
},
|
||||
{
|
||||
"1.png",
|
||||
true,
|
||||
"cos",
|
||||
},
|
||||
{
|
||||
"1",
|
||||
false,
|
||||
"cos",
|
||||
},
|
||||
{
|
||||
"1.txt.png",
|
||||
true,
|
||||
"cos",
|
||||
},
|
||||
{
|
||||
"1.png.txt",
|
||||
false,
|
||||
"cos",
|
||||
},
|
||||
{
|
||||
"1",
|
||||
true,
|
||||
"onedrive",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
policy := Policy{Type: testCase.policy}
|
||||
asserts.Equal(testCase.expect, policy.IsThumbExist(testCase.name))
|
||||
}
|
||||
}
|
||||
|
||||
+16
-2
@@ -1,6 +1,7 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
@@ -191,11 +192,24 @@ func (user *User) CheckPassword(password string) (bool, error) {
|
||||
|
||||
// 根据存储密码拆分为 Salt 和 Digest
|
||||
passwordStore := strings.Split(user.Password, ":")
|
||||
if len(passwordStore) != 2 {
|
||||
if len(passwordStore) != 2 && len(passwordStore) != 3 {
|
||||
return false, errors.New("Unknown password type")
|
||||
}
|
||||
|
||||
// todo 兼容V2/V1密码
|
||||
// 兼容V2密码,升级后存储格式为: md5:$HASH:$SALT
|
||||
if len(passwordStore) == 3 {
|
||||
if passwordStore[0] != "md5" {
|
||||
return false, errors.New("Unknown password type")
|
||||
}
|
||||
hash := md5.New()
|
||||
_, err := hash.Write([]byte(passwordStore[2] + password))
|
||||
bs := hex.EncodeToString(hash.Sum(nil))
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return bs == passwordStore[1], nil
|
||||
}
|
||||
|
||||
//计算 Salt 和密码组合的SHA1摘要
|
||||
hash := sha1.New()
|
||||
_, err := hash.Write([]byte(password + passwordStore[0]))
|
||||
|
||||
@@ -144,6 +144,27 @@ func TestUser_CheckPassword(t *testing.T) {
|
||||
asserts.Error(err)
|
||||
asserts.False(res)
|
||||
|
||||
// 未知密码类型
|
||||
user = User{}
|
||||
user.Password = "1:2:3"
|
||||
res, err = user.CheckPassword("Cause Sega does what nintendon't")
|
||||
asserts.Error(err)
|
||||
asserts.False(res)
|
||||
|
||||
// V2密码,错误
|
||||
user = User{}
|
||||
user.Password = "md5:2:3"
|
||||
res, err = user.CheckPassword("Cause Sega does what nintendon't")
|
||||
asserts.NoError(err)
|
||||
asserts.False(res)
|
||||
|
||||
// V2密码,正确
|
||||
user = User{}
|
||||
user.Password = "md5:d8446059f8846a2c111a7f53515665fb:sdshare"
|
||||
res, err = user.CheckPassword("admin")
|
||||
asserts.NoError(err)
|
||||
asserts.True(res)
|
||||
|
||||
}
|
||||
|
||||
func TestNewUser(t *testing.T) {
|
||||
|
||||
@@ -14,6 +14,8 @@ type database struct {
|
||||
Host string
|
||||
Name string
|
||||
TablePrefix string
|
||||
DBFile string
|
||||
Port int
|
||||
}
|
||||
|
||||
// system 系统通用配置
|
||||
@@ -25,6 +27,12 @@ type system struct {
|
||||
HashIDSalt string
|
||||
}
|
||||
|
||||
type ssl struct {
|
||||
CertPath string `validate:"omitempty,required"`
|
||||
KeyPath string `validate:"omitempty,required"`
|
||||
Listen string `validate:"required"`
|
||||
}
|
||||
|
||||
// slave 作为slave存储端配置
|
||||
type slave struct {
|
||||
Secret string `validate:"omitempty,gte=64"`
|
||||
@@ -111,6 +119,7 @@ func Init(path string) {
|
||||
sections := map[string]interface{}{
|
||||
"Database": DatabaseConfig,
|
||||
"System": SystemConfig,
|
||||
"SSL": SSLConfig,
|
||||
"Captcha": CaptchaConfig,
|
||||
"Redis": RedisConfig,
|
||||
"Thumbnail": ThumbConfig,
|
||||
|
||||
@@ -11,7 +11,9 @@ var RedisConfig = &redis{
|
||||
|
||||
// DatabaseConfig 数据库配置
|
||||
var DatabaseConfig = &database{
|
||||
Type: "UNSET",
|
||||
Type: "UNSET",
|
||||
DBFile: "cloudreve.db",
|
||||
Port: 3306,
|
||||
}
|
||||
|
||||
// SystemConfig 系统公用配置
|
||||
@@ -57,3 +59,9 @@ var SlaveConfig = &slave{
|
||||
CallbackTimeout: 20,
|
||||
SignatureTTL: 60,
|
||||
}
|
||||
|
||||
var SSLConfig = &ssl{
|
||||
Listen: ":443",
|
||||
CertPath: "",
|
||||
KeyPath: "",
|
||||
}
|
||||
|
||||
+5
-2
@@ -1,10 +1,13 @@
|
||||
package conf
|
||||
|
||||
// BackendVersion 当前后端版本号
|
||||
var BackendVersion = "3.0.0-beta1"
|
||||
var BackendVersion = "3.1.0"
|
||||
|
||||
// RequiredDBVersion 与当前版本匹配的数据库版本
|
||||
var RequiredDBVersion = "3.0.0-alpha1"
|
||||
var RequiredDBVersion = "3.1.0"
|
||||
|
||||
// RequiredStaticVersion 与当前版本匹配的静态资源版本
|
||||
var RequiredStaticVersion = "3.1.0"
|
||||
|
||||
// IsPro 是否为Pro版本
|
||||
var IsPro = "false"
|
||||
|
||||
+10
-8
@@ -30,19 +30,21 @@ func Init() {
|
||||
"replyTo",
|
||||
"smtpUser",
|
||||
"smtpPass",
|
||||
"smtpEncryption",
|
||||
)
|
||||
port := model.GetIntSetting("smtpPort", 25)
|
||||
keepAlive := model.GetIntSetting("mail_keepalive", 30)
|
||||
|
||||
client := NewSMTPClient(SMTPConfig{
|
||||
Name: options["fromName"],
|
||||
Address: options["fromAdress"],
|
||||
ReplyTo: options["replyTo"],
|
||||
Host: options["smtpHost"],
|
||||
Port: port,
|
||||
User: options["smtpUser"],
|
||||
Password: options["smtpPass"],
|
||||
Keepalive: keepAlive,
|
||||
Name: options["fromName"],
|
||||
Address: options["fromAdress"],
|
||||
ReplyTo: options["replyTo"],
|
||||
Host: options["smtpHost"],
|
||||
Port: port,
|
||||
User: options["smtpUser"],
|
||||
Password: options["smtpPass"],
|
||||
Keepalive: keepAlive,
|
||||
Encryption: model.IsTrueVal(options["smtpEncryption"]),
|
||||
})
|
||||
|
||||
Client = client
|
||||
|
||||
+6
-1
@@ -22,7 +22,7 @@ type SMTPConfig struct {
|
||||
Port int // 服务器端口
|
||||
User string // 用户名
|
||||
Password string // 密码
|
||||
Encryption string // 是否启用加密
|
||||
Encryption bool // 是否启用加密
|
||||
Keepalive int // SMTP 连接保留时长
|
||||
}
|
||||
|
||||
@@ -77,6 +77,11 @@ func (client *SMTP) Init() {
|
||||
d.Timeout = time.Duration(client.Config.Keepalive+5) * time.Second
|
||||
client.chOpen = true
|
||||
|
||||
// 是否启用 SSL
|
||||
if client.Config.Encryption {
|
||||
d.SSL = true
|
||||
}
|
||||
|
||||
var s mail.SendCloser
|
||||
var err error
|
||||
open := false
|
||||
|
||||
@@ -18,6 +18,9 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -46,6 +49,80 @@ type Driver struct {
|
||||
HTTPClient request.Client
|
||||
}
|
||||
|
||||
// List 列出COS文件
|
||||
func (handler Driver) List(ctx context.Context, base string, recursive bool) ([]response.Object, error) {
|
||||
// 初始化列目录参数
|
||||
opt := &cossdk.BucketGetOptions{
|
||||
Prefix: strings.TrimPrefix(base, "/"),
|
||||
EncodingType: "",
|
||||
MaxKeys: 1000,
|
||||
}
|
||||
// 是否为递归列出
|
||||
if !recursive {
|
||||
opt.Delimiter = "/"
|
||||
}
|
||||
// 手动补齐结尾的slash
|
||||
if opt.Prefix != "" {
|
||||
opt.Prefix += "/"
|
||||
}
|
||||
|
||||
var (
|
||||
marker string
|
||||
objects []cossdk.Object
|
||||
commons []string
|
||||
)
|
||||
|
||||
for {
|
||||
res, _, err := handler.Client.Bucket.Get(ctx, opt)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
objects = append(objects, res.Contents...)
|
||||
commons = append(commons, res.CommonPrefixes...)
|
||||
// 如果本次未列取完,则继续使用marker获取结果
|
||||
marker = res.NextMarker
|
||||
// marker 为空时结果列取完毕,跳出
|
||||
if marker == "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 处理列取结果
|
||||
res := make([]response.Object, 0, len(objects)+len(commons))
|
||||
// 处理目录
|
||||
for _, object := range commons {
|
||||
rel, err := filepath.Rel(opt.Prefix, object)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
res = append(res, response.Object{
|
||||
Name: path.Base(object),
|
||||
RelativePath: filepath.ToSlash(rel),
|
||||
Size: 0,
|
||||
IsDir: true,
|
||||
LastModify: time.Now(),
|
||||
})
|
||||
}
|
||||
// 处理文件
|
||||
for _, object := range objects {
|
||||
rel, err := filepath.Rel(opt.Prefix, object.Key)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
res = append(res, response.Object{
|
||||
Name: path.Base(object.Key),
|
||||
Source: object.Key,
|
||||
RelativePath: filepath.ToSlash(rel),
|
||||
Size: uint64(object.Size),
|
||||
IsDir: false,
|
||||
LastModify: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
return res, nil
|
||||
|
||||
}
|
||||
|
||||
// CORS 创建跨域策略
|
||||
func (handler Driver) CORS() error {
|
||||
_, err := handler.Client.Bucket.PutCORS(context.Background(), &cossdk.BucketPutCORSOptions{
|
||||
@@ -143,7 +220,34 @@ func (handler Driver) Delete(ctx context.Context, files []string) ([]string, err
|
||||
|
||||
// Thumb 获取文件缩略图
|
||||
func (handler Driver) Thumb(ctx context.Context, path string) (*response.ContentResponse, error) {
|
||||
return nil, errors.New("未实现")
|
||||
var (
|
||||
thumbSize = [2]uint{400, 300}
|
||||
ok = false
|
||||
)
|
||||
if thumbSize, ok = ctx.Value(fsctx.ThumbSizeCtx).([2]uint); !ok {
|
||||
return nil, errors.New("无法获取缩略图尺寸设置")
|
||||
}
|
||||
thumbParam := fmt.Sprintf("imageMogr2/thumbnail/%dx%d", thumbSize[0], thumbSize[1])
|
||||
|
||||
source, err := handler.signSourceURL(
|
||||
ctx,
|
||||
path,
|
||||
int64(model.GetIntSetting("preview_timeout", 60)),
|
||||
&urlOption{},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
thumbURL, _ := url.Parse(source)
|
||||
thumbQuery := thumbURL.Query()
|
||||
thumbQuery.Add(thumbParam, "")
|
||||
thumbURL.RawQuery = thumbQuery.Encode()
|
||||
|
||||
return &response.ContentResponse{
|
||||
Redirect: true,
|
||||
URL: thumbURL.String(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Source 获取外链URL
|
||||
@@ -23,6 +23,52 @@ type Driver struct {
|
||||
Policy *model.Policy
|
||||
}
|
||||
|
||||
// List 递归列取给定物理路径下所有文件
|
||||
func (handler Driver) List(ctx context.Context, path string, recursive bool) ([]response.Object, error) {
|
||||
var res []response.Object
|
||||
|
||||
// 取得起始路径
|
||||
root := util.RelativePath(filepath.FromSlash(path))
|
||||
|
||||
// 开始遍历路径下的文件、目录
|
||||
err := filepath.Walk(root,
|
||||
func(path string, info os.FileInfo, err error) error {
|
||||
// 跳过根目录
|
||||
if path == root {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
util.Log().Warning("无法遍历目录 %s, %s", path, err)
|
||||
return filepath.SkipDir
|
||||
}
|
||||
|
||||
// 将遍历对象的绝对路径转换为相对路径
|
||||
rel, err := filepath.Rel(root, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
res = append(res, response.Object{
|
||||
Name: info.Name(),
|
||||
RelativePath: filepath.ToSlash(rel),
|
||||
Source: path,
|
||||
Size: uint64(info.Size()),
|
||||
IsDir: info.IsDir(),
|
||||
LastModify: info.ModTime(),
|
||||
})
|
||||
|
||||
// 如果非递归,则不步入目录
|
||||
if !recursive && info.IsDir() {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
return res, err
|
||||
}
|
||||
|
||||
// Get 获取文件内容
|
||||
func (handler Driver) Get(ctx context.Context, path string) (response.RSCloser, error) {
|
||||
// 打开文件
|
||||
@@ -56,7 +102,7 @@ func (handler Driver) Put(ctx context.Context, file io.ReadCloser, dst string, s
|
||||
// 如果目标目录不存在,创建
|
||||
basePath := filepath.Dir(dst)
|
||||
if !util.Exists(basePath) {
|
||||
err := os.MkdirAll(basePath, 0700)
|
||||
err := os.MkdirAll(basePath, 0744)
|
||||
if err != nil {
|
||||
util.Log().Warning("无法创建目录,%s", err)
|
||||
return err
|
||||
@@ -91,7 +137,7 @@ func (handler Driver) Delete(ctx context.Context, files []string) ([]string, err
|
||||
}
|
||||
|
||||
// 尝试删除文件的缩略图(如果有)
|
||||
_ = os.Remove(value + conf.ThumbConfig.FileSuffix)
|
||||
_ = os.Remove(util.RelativePath(value + conf.ThumbConfig.FileSuffix))
|
||||
}
|
||||
|
||||
return deleteFailed, retErr
|
||||
|
||||
+31
@@ -230,3 +230,34 @@ func TestHandler_Token(t *testing.T) {
|
||||
_, err := handler.Token(ctx, 10, "123")
|
||||
asserts.NoError(err)
|
||||
}
|
||||
|
||||
func TestDriver_List(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
handler := Driver{}
|
||||
ctx := context.Background()
|
||||
|
||||
// 创建测试目录结构
|
||||
for _, path := range []string{
|
||||
"test/TestDriver_List/parent.txt",
|
||||
"test/TestDriver_List/parent_folder2/sub2.txt",
|
||||
"test/TestDriver_List/parent_folder1/sub_folder/sub1.txt",
|
||||
"test/TestDriver_List/parent_folder1/sub_folder/sub2.txt",
|
||||
} {
|
||||
f, _ := util.CreatNestedFile(util.RelativePath(path))
|
||||
f.Close()
|
||||
}
|
||||
|
||||
// 非递归列出
|
||||
{
|
||||
res, err := handler.List(ctx, "test/TestDriver_List", false)
|
||||
asserts.NoError(err)
|
||||
asserts.Len(res, 3)
|
||||
}
|
||||
|
||||
// 递归列出
|
||||
{
|
||||
res, err := handler.List(ctx, "test/TestDriver_List", true)
|
||||
asserts.NoError(err)
|
||||
asserts.Len(res, 7)
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,10 @@ import (
|
||||
const (
|
||||
// SmallFileSize 单文件上传接口最大尺寸
|
||||
SmallFileSize uint64 = 4 * 1024 * 1024
|
||||
// ChunkSize 分片上传分片大小
|
||||
// ChunkSize 服务端中转分片上传分片大小
|
||||
ChunkSize uint64 = 10 * 1024 * 1024
|
||||
// ListRetry 列取请求重试次数
|
||||
ListRetry = 1
|
||||
)
|
||||
|
||||
// GetSourcePath 获取文件的绝对路径
|
||||
@@ -59,6 +61,43 @@ func (client *Client) getRequestURL(api string) string {
|
||||
return base.String()
|
||||
}
|
||||
|
||||
// ListChildren 根据路径列取子对象
|
||||
func (client *Client) ListChildren(ctx context.Context, path string) ([]FileInfo, error) {
|
||||
var requestURL string
|
||||
dst := strings.TrimPrefix(path, "/")
|
||||
if dst == "" {
|
||||
requestURL = client.getRequestURL("me/drive/root/children")
|
||||
} else {
|
||||
requestURL = client.getRequestURL("me/drive/root:/" + dst + ":/children")
|
||||
}
|
||||
|
||||
res, err := client.requestWithStr(ctx, "GET", requestURL+"?$top=999999999", "", 200)
|
||||
if err != nil {
|
||||
retried := 0
|
||||
if v, ok := ctx.Value(fsctx.RetryCtx).(int); ok {
|
||||
retried = v
|
||||
}
|
||||
if retried < ListRetry {
|
||||
retried++
|
||||
util.Log().Debug("路径[%s]列取请求失败[%s],5秒钟后重试", path, err)
|
||||
time.Sleep(time.Duration(5) * time.Second)
|
||||
return client.ListChildren(context.WithValue(ctx, fsctx.RetryCtx, retried), path)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var (
|
||||
decodeErr error
|
||||
fileInfo ListResponse
|
||||
)
|
||||
decodeErr = json.Unmarshal([]byte(res), &fileInfo)
|
||||
if decodeErr != nil {
|
||||
return nil, decodeErr
|
||||
}
|
||||
|
||||
return fileInfo.Value, nil
|
||||
}
|
||||
|
||||
// Meta 根据资源ID或文件路径获取文件元信息
|
||||
func (client *Client) Meta(ctx context.Context, id string, path string) (*FileInfo, error) {
|
||||
var requestURL string
|
||||
@@ -216,9 +255,6 @@ func (client *Client) Upload(ctx context.Context, dst string, size int, file io.
|
||||
// 因为后面需要错误重试,这里要把分片内容读到内存中
|
||||
chunkContent := chunkData[:chunkSize]
|
||||
_, err := io.ReadFull(file, chunkContent)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
chunk := Chunk{
|
||||
Offset: offset,
|
||||
@@ -347,10 +383,12 @@ func (client *Client) makeBatchDeleteRequestsBody(files []string) string {
|
||||
}
|
||||
for i, v := range files {
|
||||
v = strings.TrimPrefix(v, "/")
|
||||
filePath, _ := url.Parse("/me/drive/root:/")
|
||||
filePath.Path = path.Join(filePath.Path, v)
|
||||
req.Requests[i] = BatchRequest{
|
||||
ID: v,
|
||||
Method: "DELETE",
|
||||
URL: "me/drive/root:/" + v,
|
||||
URL: filePath.EscapedPath(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -506,81 +506,6 @@ func TestClient_Upload(t *testing.T) {
|
||||
asserts.Error(err)
|
||||
}
|
||||
|
||||
// 大文件 分两个分片 成功
|
||||
{
|
||||
client.Credential.ExpiresIn = time.Now().Add(time.Duration(100) * time.Hour).Unix()
|
||||
clientMock := ClientMock{}
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"POST",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`{"uploadUrl":"123321"}`)),
|
||||
},
|
||||
})
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"PUT",
|
||||
"123321",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`{"uploadUrl":"http://dev.com/2"}`)),
|
||||
},
|
||||
})
|
||||
client.Request = clientMock
|
||||
|
||||
err := client.Upload(context.Background(), "123.jpg", 15*1024*1024, strings.NewReader("123"))
|
||||
clientMock.AssertExpectations(t)
|
||||
asserts.NoError(err)
|
||||
}
|
||||
|
||||
// 大文件 分两个分片 失败
|
||||
{
|
||||
cache.Set("setting_onedrive_chunk_retries", "0", 0)
|
||||
client.Credential.ExpiresIn = time.Now().Add(time.Duration(100) * time.Hour).Unix()
|
||||
clientMock := ClientMock{}
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"POST",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`{"uploadUrl":"123321"}`)),
|
||||
},
|
||||
})
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"PUT",
|
||||
"123321",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 400,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`{"uploadUrl":"http://dev.com/2"}`)),
|
||||
},
|
||||
})
|
||||
client.Request = clientMock
|
||||
|
||||
err := client.Upload(context.Background(), "123.jpg", 15*1024*1024, strings.NewReader("123"))
|
||||
clientMock.AssertExpectations(t)
|
||||
asserts.Error(err)
|
||||
}
|
||||
|
||||
// 上下文取消
|
||||
{
|
||||
client.Credential.ExpiresIn = time.Now().Add(time.Duration(100) * time.Hour).Unix()
|
||||
@@ -827,6 +752,66 @@ func TestClient_Delete(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_ListChildren(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
client, _ := NewClient(&model.Policy{})
|
||||
client.Credential.AccessToken = "AccessToken"
|
||||
|
||||
// 根目录,请求失败,重测试
|
||||
{
|
||||
client.Credential.ExpiresIn = 0
|
||||
res, err := client.ListChildren(context.Background(), "/")
|
||||
asserts.Error(err)
|
||||
asserts.Empty(res)
|
||||
}
|
||||
|
||||
// 非根目录,未知响应
|
||||
{
|
||||
client.Credential.ExpiresIn = time.Now().Add(time.Duration(100) * time.Hour).Unix()
|
||||
clientMock := ClientMock{}
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"GET",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`???`)),
|
||||
},
|
||||
})
|
||||
client.Request = clientMock
|
||||
res, err := client.ListChildren(context.Background(), "/uploads")
|
||||
asserts.Error(err)
|
||||
asserts.Empty(res)
|
||||
}
|
||||
|
||||
// 非根目录,成功
|
||||
{
|
||||
client.Credential.ExpiresIn = time.Now().Add(time.Duration(100) * time.Hour).Unix()
|
||||
clientMock := ClientMock{}
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"GET",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`{"value":[{}]}`)),
|
||||
},
|
||||
})
|
||||
client.Request = clientMock
|
||||
res, err := client.ListChildren(context.Background(), "/uploads")
|
||||
asserts.NoError(err)
|
||||
asserts.Len(res, 1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClient_GetThumbURL(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
client, _ := NewClient(&model.Policy{})
|
||||
|
||||
+62
@@ -3,13 +3,18 @@ package onedrive
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
model "github.com/HFO4/cloudreve/models"
|
||||
"github.com/HFO4/cloudreve/pkg/cache"
|
||||
"github.com/HFO4/cloudreve/pkg/filesystem/fsctx"
|
||||
"github.com/HFO4/cloudreve/pkg/filesystem/response"
|
||||
"github.com/HFO4/cloudreve/pkg/request"
|
||||
"github.com/HFO4/cloudreve/pkg/serializer"
|
||||
"io"
|
||||
"net/url"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -20,6 +25,51 @@ type Driver struct {
|
||||
HTTPClient request.Client
|
||||
}
|
||||
|
||||
// List 列取项目
|
||||
func (handler Driver) List(ctx context.Context, base string, recursive bool) ([]response.Object, error) {
|
||||
base = strings.TrimPrefix(base, "/")
|
||||
// 列取子项目
|
||||
objects, _ := handler.Client.ListChildren(ctx, base)
|
||||
|
||||
// 获取真实的列取起始根目录
|
||||
rootPath := base
|
||||
if realBase, ok := ctx.Value(fsctx.PathCtx).(string); ok {
|
||||
rootPath = realBase
|
||||
} else {
|
||||
ctx = context.WithValue(ctx, fsctx.PathCtx, base)
|
||||
}
|
||||
|
||||
// 整理结果
|
||||
res := make([]response.Object, 0, len(objects))
|
||||
for _, object := range objects {
|
||||
source := path.Join(base, object.Name)
|
||||
rel, err := filepath.Rel(rootPath, source)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
res = append(res, response.Object{
|
||||
Name: object.Name,
|
||||
RelativePath: filepath.ToSlash(rel),
|
||||
Source: source,
|
||||
Size: object.Size,
|
||||
IsDir: object.Folder != nil,
|
||||
LastModify: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
// 递归列取子目录
|
||||
if recursive {
|
||||
for _, object := range objects {
|
||||
if object.Folder != nil {
|
||||
sub, _ := handler.List(ctx, path.Join(base, object.Name), recursive)
|
||||
res = append(res, sub...)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// Get 获取文件
|
||||
func (handler Driver) Get(ctx context.Context, path string) (response.RSCloser, error) {
|
||||
// 获取文件源地址
|
||||
@@ -101,8 +151,20 @@ func (handler Driver) Source(
|
||||
isDownload bool,
|
||||
speed int,
|
||||
) (string, error) {
|
||||
// 尝试从缓存中查找
|
||||
if cachedURL, ok := cache.Get(fmt.Sprintf("onedrive_source_%d_%s", handler.Policy.ID, path)); ok {
|
||||
return cachedURL.(string), nil
|
||||
}
|
||||
|
||||
// 缓存不存在,重新获取
|
||||
res, err := handler.Client.Meta(ctx, "", path)
|
||||
if err == nil {
|
||||
// 写入新的缓存
|
||||
cache.Set(
|
||||
fmt.Sprintf("onedrive_source_%d_%s", handler.Policy.ID, path),
|
||||
res.DownloadURL,
|
||||
model.GetIntSetting("onedrive_source_timeout", 1800),
|
||||
)
|
||||
return res.DownloadURL, nil
|
||||
}
|
||||
return "", err
|
||||
@@ -129,6 +129,7 @@ func TestDriver_Source(t *testing.T) {
|
||||
}
|
||||
handler.Client, _ = NewClient(&model.Policy{})
|
||||
handler.Client.Credential.ExpiresIn = time.Now().Add(time.Duration(100) * time.Hour).Unix()
|
||||
cache.Set("setting_onedrive_source_timeout", "1800", 0)
|
||||
|
||||
// 失败
|
||||
{
|
||||
@@ -137,6 +138,17 @@ func TestDriver_Source(t *testing.T) {
|
||||
asserts.Empty(res)
|
||||
}
|
||||
|
||||
// 命中缓存 成功
|
||||
{
|
||||
handler.Client.Credential.ExpiresIn = time.Now().Add(time.Duration(100) * time.Hour).Unix()
|
||||
handler.Client.Credential.AccessToken = "1"
|
||||
cache.Set("onedrive_source_0_123.jpg", "res", 0)
|
||||
res, err := handler.Source(context.Background(), "123.jpg", url.URL{}, 0, true, 0)
|
||||
cache.Deletes([]string{"0_123.jpg"}, "onedrive_source_")
|
||||
asserts.NoError(err)
|
||||
asserts.Equal("res", res)
|
||||
}
|
||||
|
||||
// 成功
|
||||
{
|
||||
handler.Client.Credential.ExpiresIn = time.Now().Add(time.Duration(100) * time.Hour).Unix()
|
||||
@@ -162,6 +174,78 @@ func TestDriver_Source(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriver_List(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
handler := Driver{
|
||||
Policy: &model.Policy{
|
||||
AccessKey: "ak",
|
||||
SecretKey: "sk",
|
||||
BucketName: "test",
|
||||
Server: "test.com",
|
||||
},
|
||||
}
|
||||
handler.Client, _ = NewClient(&model.Policy{})
|
||||
handler.Client.Credential.AccessToken = "AccessToken"
|
||||
handler.Client.Credential.ExpiresIn = time.Now().Add(time.Duration(100) * time.Hour).Unix()
|
||||
|
||||
// 非递归
|
||||
{
|
||||
clientMock := ClientMock{}
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"GET",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`{"value":[{}]}`)),
|
||||
},
|
||||
})
|
||||
handler.Client.Request = clientMock
|
||||
res, err := handler.List(context.Background(), "/", false)
|
||||
asserts.NoError(err)
|
||||
asserts.Len(res, 1)
|
||||
}
|
||||
|
||||
// 递归一次
|
||||
{
|
||||
clientMock := ClientMock{}
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"GET",
|
||||
"me/drive/root/children?$top=999999999",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`{"value":[{"name":"1","folder":{}}]}`)),
|
||||
},
|
||||
})
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"GET",
|
||||
"me/drive/root:/1:/children?$top=999999999",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`{"value":[{"name":"2"}]}`)),
|
||||
},
|
||||
})
|
||||
handler.Client.Request = clientMock
|
||||
res, err := handler.List(context.Background(), "/", true)
|
||||
asserts.NoError(err)
|
||||
asserts.Len(res, 2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriver_Thumb(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
handler := Driver{
|
||||
|
||||
@@ -32,6 +32,16 @@ type FileInfo struct {
|
||||
Image imageInfo `json:"image"`
|
||||
ParentReference parentReference `json:"parentReference"`
|
||||
DownloadURL string `json:"@microsoft.graph.downloadUrl"`
|
||||
File *file `json:"file"`
|
||||
Folder *folder `json:"folder"`
|
||||
}
|
||||
|
||||
type file struct {
|
||||
MimeType string `json:"mimeType"`
|
||||
}
|
||||
|
||||
type folder struct {
|
||||
ChildCount int `json:"childCount"`
|
||||
}
|
||||
|
||||
type imageInfo struct {
|
||||
@@ -83,6 +93,12 @@ type ThumbResponse struct {
|
||||
URL string `json:"url"`
|
||||
}
|
||||
|
||||
// ListResponse 列取子项目响应
|
||||
type ListResponse struct {
|
||||
Value []FileInfo `json:"value"`
|
||||
Context string `json:"@odata.context"`
|
||||
}
|
||||
|
||||
// Chunk 文件分片
|
||||
type Chunk struct {
|
||||
Offset int
|
||||
|
||||
@@ -18,6 +18,8 @@ import (
|
||||
"io"
|
||||
"net/url"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -99,6 +101,78 @@ func (handler *Driver) InitOSSClient() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// List 列出OSS上的文件
|
||||
func (handler Driver) List(ctx context.Context, base string, recursive bool) ([]response.Object, error) {
|
||||
// 初始化客户端
|
||||
if err := handler.InitOSSClient(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 列取文件
|
||||
base = strings.TrimPrefix(base, "/")
|
||||
if base != "" {
|
||||
base += "/"
|
||||
}
|
||||
|
||||
var (
|
||||
delimiter string
|
||||
marker string
|
||||
objects []oss.ObjectProperties
|
||||
commons []string
|
||||
)
|
||||
if !recursive {
|
||||
delimiter = "/"
|
||||
}
|
||||
|
||||
for {
|
||||
subRes, err := handler.bucket.ListObjects(oss.Marker(marker), oss.Prefix(base),
|
||||
oss.MaxKeys(1000), oss.Delimiter(delimiter))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
objects = append(objects, subRes.Objects...)
|
||||
commons = append(commons, subRes.CommonPrefixes...)
|
||||
marker = subRes.NextMarker
|
||||
if marker == "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// 处理列取结果
|
||||
res := make([]response.Object, 0, len(objects)+len(commons))
|
||||
// 处理目录
|
||||
for _, object := range commons {
|
||||
rel, err := filepath.Rel(base, object)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
res = append(res, response.Object{
|
||||
Name: path.Base(object),
|
||||
RelativePath: filepath.ToSlash(rel),
|
||||
Size: 0,
|
||||
IsDir: true,
|
||||
LastModify: time.Now(),
|
||||
})
|
||||
}
|
||||
// 处理文件
|
||||
for _, object := range objects {
|
||||
rel, err := filepath.Rel(base, object.Key)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
res = append(res, response.Object{
|
||||
Name: path.Base(object.Key),
|
||||
Source: object.Key,
|
||||
RelativePath: filepath.ToSlash(rel),
|
||||
Size: uint64(object.Size),
|
||||
IsDir: false,
|
||||
LastModify: object.LastModified,
|
||||
})
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// Get 获取文件
|
||||
func (handler Driver) Get(ctx context.Context, path string) (response.RSCloser, error) {
|
||||
// 通过VersionID禁止缓存
|
||||
@@ -248,6 +322,9 @@ func (handler Driver) Source(
|
||||
signOptions = append(signOptions, oss.ResponseContentDisposition("attachment; filename=\""+url.PathEscape(fileName)+"\""))
|
||||
}
|
||||
if speed > 0 {
|
||||
// Byte 转换为 bit
|
||||
speed *= 8
|
||||
|
||||
// OSS对速度值有范围限制
|
||||
if speed < 819200 {
|
||||
speed = 819200
|
||||
@@ -276,11 +353,13 @@ func (handler Driver) signSourceURL(ctx context.Context, path string, ttl int64,
|
||||
// 优先使用https
|
||||
finalURL.Scheme = "https"
|
||||
|
||||
// 公有空间替换掉Key
|
||||
// 公有空间替换掉Key及不支持的头
|
||||
if !handler.Policy.IsPrivate {
|
||||
query := finalURL.Query()
|
||||
query.Del("OSSAccessKeyId")
|
||||
query.Del("Signature")
|
||||
query.Del("response-content-disposition")
|
||||
query.Del("x-oss-traffic-limit")
|
||||
finalURL.RawQuery = query.Encode()
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ func TestDriver_Source(t *testing.T) {
|
||||
// 限速 + 下载
|
||||
{
|
||||
ctx := context.WithValue(context.Background(), fsctx.FileModelCtx, model.File{Name: "123.txt"})
|
||||
res, err := handler.Source(ctx, "/123", url.URL{}, 10, true, 819201)
|
||||
res, err := handler.Source(ctx, "/123", url.URL{}, 10, true, 102401)
|
||||
asserts.NoError(err)
|
||||
resURL, err := url.Parse(res)
|
||||
asserts.NoError(err)
|
||||
@@ -125,7 +125,7 @@ func TestDriver_Source(t *testing.T) {
|
||||
asserts.NotEmpty(query.Get("Signature"))
|
||||
asserts.NotEmpty(query.Get("Expires"))
|
||||
asserts.Equal("ak", query.Get("OSSAccessKeyId"))
|
||||
asserts.EqualValues("819201", query.Get("x-oss-traffic-limit"))
|
||||
asserts.EqualValues("819208", query.Get("x-oss-traffic-limit"))
|
||||
asserts.NotEmpty(query.Get("response-content-disposition"))
|
||||
}
|
||||
|
||||
@@ -311,3 +311,23 @@ func TestDriver_Get(t *testing.T) {
|
||||
asserts.Equal("123", string(content))
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriver_List(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
handler := Driver{
|
||||
Policy: &model.Policy{
|
||||
AccessKey: "ak",
|
||||
SecretKey: "sk",
|
||||
BucketName: "test",
|
||||
Server: "test.com",
|
||||
IsPrivate: true,
|
||||
},
|
||||
}
|
||||
|
||||
// 连接失败
|
||||
{
|
||||
res, err := handler.List(context.Background(), "/", true)
|
||||
asserts.Error(err)
|
||||
asserts.Empty(res)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,6 +14,9 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -22,6 +25,79 @@ type Driver struct {
|
||||
Policy *model.Policy
|
||||
}
|
||||
|
||||
// List 列出给定路径下的文件
|
||||
func (handler Driver) List(ctx context.Context, base string, recursive bool) ([]response.Object, error) {
|
||||
base = strings.TrimPrefix(base, "/")
|
||||
if base != "" {
|
||||
base += "/"
|
||||
}
|
||||
|
||||
var (
|
||||
delimiter string
|
||||
marker string
|
||||
objects []storage.ListItem
|
||||
commons []string
|
||||
)
|
||||
if !recursive {
|
||||
delimiter = "/"
|
||||
}
|
||||
|
||||
mac := qbox.NewMac(handler.Policy.AccessKey, handler.Policy.SecretKey)
|
||||
cfg := storage.Config{
|
||||
UseHTTPS: true,
|
||||
}
|
||||
bucketManager := storage.NewBucketManager(mac, &cfg)
|
||||
|
||||
for {
|
||||
entries, folders, nextMarker, hashNext, err := bucketManager.ListFiles(
|
||||
handler.Policy.BucketName,
|
||||
base, delimiter, marker, 1000)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
objects = append(objects, entries...)
|
||||
commons = append(commons, folders...)
|
||||
if !hashNext {
|
||||
break
|
||||
}
|
||||
marker = nextMarker
|
||||
}
|
||||
|
||||
// 处理列取结果
|
||||
res := make([]response.Object, 0, len(objects)+len(commons))
|
||||
// 处理目录
|
||||
for _, object := range commons {
|
||||
rel, err := filepath.Rel(base, object)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
res = append(res, response.Object{
|
||||
Name: path.Base(object),
|
||||
RelativePath: filepath.ToSlash(rel),
|
||||
Size: 0,
|
||||
IsDir: true,
|
||||
LastModify: time.Now(),
|
||||
})
|
||||
}
|
||||
// 处理文件
|
||||
for _, object := range objects {
|
||||
rel, err := filepath.Rel(base, object.Key)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
res = append(res, response.Object{
|
||||
Name: path.Base(object.Key),
|
||||
Source: object.Key,
|
||||
RelativePath: filepath.ToSlash(rel),
|
||||
Size: uint64(object.Fsize),
|
||||
IsDir: false,
|
||||
LastModify: time.Now(),
|
||||
})
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// Get 获取文件
|
||||
func (handler Driver) Get(ctx context.Context, path string) (response.RSCloser, error) {
|
||||
// 给文件名加上随机参数以强制拉取
|
||||
@@ -27,6 +27,47 @@ type Driver struct {
|
||||
AuthInstance auth.Auth
|
||||
}
|
||||
|
||||
// List 列取文件
|
||||
func (handler Driver) List(ctx context.Context, path string, recursive bool) ([]response.Object, error) {
|
||||
var res []response.Object
|
||||
|
||||
reqBody := serializer.ListRequest{
|
||||
Path: path,
|
||||
Recursive: recursive,
|
||||
}
|
||||
reqBodyEncoded, err := json.Marshal(reqBody)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
// 发送列表请求
|
||||
bodyReader := strings.NewReader(string(reqBodyEncoded))
|
||||
signTTL := model.GetIntSetting("slave_api_timeout", 60)
|
||||
resp, err := handler.Client.Request(
|
||||
"POST",
|
||||
handler.getAPIUrl("list"),
|
||||
bodyReader,
|
||||
request.WithCredential(handler.AuthInstance, int64(signTTL)),
|
||||
).CheckHTTPResponse(200).DecodeResponse()
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
|
||||
// 处理列取结果
|
||||
if resp.Code != 0 {
|
||||
return res, errors.New(resp.Error)
|
||||
}
|
||||
|
||||
if resStr, ok := resp.Data.(string); ok {
|
||||
err = json.Unmarshal([]byte(resStr), &res)
|
||||
if err != nil {
|
||||
return res, err
|
||||
}
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// getAPIUrl 获取接口请求地址
|
||||
func (handler Driver) getAPIUrl(scope string, routes ...string) string {
|
||||
serverURL, err := url.Parse(handler.Policy.Server)
|
||||
@@ -40,6 +81,8 @@ func (handler Driver) getAPIUrl(scope string, routes ...string) string {
|
||||
controller, _ = url.Parse("/api/v3/slave/delete")
|
||||
case "thumb":
|
||||
controller, _ = url.Parse("/api/v3/slave/thumb")
|
||||
case "list":
|
||||
controller, _ = url.Parse("/api/v3/slave/list")
|
||||
default:
|
||||
controller = serverURL
|
||||
}
|
||||
|
||||
@@ -223,6 +223,89 @@ func TestHandler_Delete(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestDriver_List(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
handler := Driver{
|
||||
Policy: &model.Policy{
|
||||
SecretKey: "test",
|
||||
Server: "http://test.com",
|
||||
},
|
||||
AuthInstance: auth.HMACAuth{},
|
||||
}
|
||||
ctx := context.Background()
|
||||
cache.Set("setting_slave_api_timeout", "60", 0)
|
||||
|
||||
// 成功
|
||||
{
|
||||
clientMock := ClientMock{}
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"POST",
|
||||
"http://test.com/api/v3/slave/list",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`{"code":0,"data":"[{}]"}`)),
|
||||
},
|
||||
})
|
||||
handler.Client = clientMock
|
||||
res, err := handler.List(ctx, "/", true)
|
||||
clientMock.AssertExpectations(t)
|
||||
asserts.NoError(err)
|
||||
asserts.Len(res, 1)
|
||||
|
||||
}
|
||||
|
||||
// 响应解析失败
|
||||
{
|
||||
clientMock := ClientMock{}
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"POST",
|
||||
"http://test.com/api/v3/slave/list",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`{"code":0,"data":"233"}`)),
|
||||
},
|
||||
})
|
||||
handler.Client = clientMock
|
||||
res, err := handler.List(ctx, "/", true)
|
||||
clientMock.AssertExpectations(t)
|
||||
asserts.Error(err)
|
||||
asserts.Len(res, 0)
|
||||
}
|
||||
|
||||
// 从机返回错误
|
||||
{
|
||||
clientMock := ClientMock{}
|
||||
clientMock.On(
|
||||
"Request",
|
||||
"POST",
|
||||
"http://test.com/api/v3/slave/list",
|
||||
testMock.Anything,
|
||||
testMock.Anything,
|
||||
).Return(&request.Response{
|
||||
Err: nil,
|
||||
Response: &http.Response{
|
||||
StatusCode: 200,
|
||||
Body: ioutil.NopCloser(strings.NewReader(`{"code":203}`)),
|
||||
},
|
||||
})
|
||||
handler.Client = clientMock
|
||||
res, err := handler.List(ctx, "/", true)
|
||||
clientMock.AssertExpectations(t)
|
||||
asserts.Error(err)
|
||||
asserts.Len(res, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHandler_Get(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
handler := Driver{
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -40,6 +41,67 @@ type Driver struct {
|
||||
Policy *model.Policy
|
||||
}
|
||||
|
||||
func (handler Driver) List(ctx context.Context, base string, recursive bool) ([]response.Object, error) {
|
||||
base = strings.TrimPrefix(base, "/")
|
||||
|
||||
// 用于接受SDK返回对象的chan
|
||||
objChan := make(chan *upyun.FileInfo)
|
||||
objects := []*upyun.FileInfo{}
|
||||
|
||||
// 列取配置
|
||||
listConf := &upyun.GetObjectsConfig{
|
||||
Path: "/" + base,
|
||||
ObjectsChan: objChan,
|
||||
MaxListTries: 1,
|
||||
}
|
||||
// 递归列取时不限制递归次数
|
||||
if recursive {
|
||||
listConf.MaxListLevel = -1
|
||||
}
|
||||
|
||||
// 启动一个goroutine收集列取的对象信
|
||||
wg := &sync.WaitGroup{}
|
||||
wg.Add(1)
|
||||
go func(input chan *upyun.FileInfo, output *[]*upyun.FileInfo, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
for {
|
||||
file, ok := <-input
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
*output = append(*output, file)
|
||||
}
|
||||
}(objChan, &objects, wg)
|
||||
|
||||
up := upyun.NewUpYun(&upyun.UpYunConfig{
|
||||
Bucket: handler.Policy.BucketName,
|
||||
Operator: handler.Policy.AccessKey,
|
||||
Password: handler.Policy.SecretKey,
|
||||
})
|
||||
|
||||
err := up.List(listConf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
// 汇总处理列取结果
|
||||
res := make([]response.Object, 0, len(objects))
|
||||
for _, object := range objects {
|
||||
res = append(res, response.Object{
|
||||
Name: path.Base(object.Name),
|
||||
RelativePath: object.Name,
|
||||
Source: path.Join(base, object.Name),
|
||||
Size: uint64(object.Size),
|
||||
IsDir: object.IsDir,
|
||||
LastModify: object.Time,
|
||||
})
|
||||
}
|
||||
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// Get 获取文件
|
||||
func (handler Driver) Get(ctx context.Context, path string) (response.RSCloser, error) {
|
||||
// 给文件名加上随机参数以强制拉取
|
||||
@@ -63,6 +63,11 @@ func (fs *FileSystem) AddFile(ctx context.Context, parent *model.Folder) (*model
|
||||
FolderID: parent.ID,
|
||||
PolicyID: fs.User.Policy.ID,
|
||||
}
|
||||
|
||||
if fs.User.Policy.IsThumbExist(file.GetFileName()) {
|
||||
newFile.PicInfo = "1,1"
|
||||
}
|
||||
|
||||
_, err = newFile.Create()
|
||||
|
||||
if err != nil {
|
||||
|
||||
@@ -20,7 +20,7 @@ func TestFileSystem_AddFile(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
file := local.FileStream{
|
||||
Size: 5,
|
||||
Name: "1.txt",
|
||||
Name: "1.png",
|
||||
}
|
||||
folder := model.Folder{
|
||||
Model: gorm.Model{
|
||||
@@ -33,6 +33,7 @@ func TestFileSystem_AddFile(t *testing.T) {
|
||||
ID: 1,
|
||||
},
|
||||
Policy: model.Policy{
|
||||
Type: "cos",
|
||||
Model: gorm.Model{
|
||||
ID: 1,
|
||||
},
|
||||
@@ -40,7 +41,7 @@ func TestFileSystem_AddFile(t *testing.T) {
|
||||
},
|
||||
}
|
||||
ctx := context.WithValue(context.Background(), fsctx.FileHeaderCtx, file)
|
||||
ctx = context.WithValue(ctx, fsctx.SavePathCtx, "/Uploads/1_sad.txt")
|
||||
ctx = context.WithValue(ctx, fsctx.SavePathCtx, "/Uploads/1_sad.png")
|
||||
|
||||
_, err := fs.AddFile(ctx, &folder)
|
||||
|
||||
@@ -54,7 +55,8 @@ func TestFileSystem_AddFile(t *testing.T) {
|
||||
|
||||
asserts.NoError(err)
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.Equal("/Uploads/1_sad.txt", f.SourceName)
|
||||
asserts.Equal("/Uploads/1_sad.png", f.SourceName)
|
||||
asserts.NotEmpty(f.PicInfo)
|
||||
}
|
||||
|
||||
func TestFileSystem_GetContent(t *testing.T) {
|
||||
|
||||
@@ -41,7 +41,7 @@ type FileHeader interface {
|
||||
GetVirtualPath() string
|
||||
}
|
||||
|
||||
// Driver 存储策略适配器
|
||||
// Handler 存储策略适配器
|
||||
type Handler interface {
|
||||
// 上传文件, dst为文件存储路径,size 为文件大小。上下文关闭
|
||||
// 时,应取消上传并清理临时文件
|
||||
@@ -64,6 +64,11 @@ type Handler interface {
|
||||
|
||||
// Token 获取有效期为ttl的上传凭证和签名,同时回调会话有效期为sessionTTL
|
||||
Token(ctx context.Context, ttl int64, callbackKey string) (serializer.UploadCredential, error)
|
||||
|
||||
// List 递归列取远程端path路径下文件、目录,不包含path本身,
|
||||
// 返回的对象路径以path作为起始根目录.
|
||||
// recursive - 是否递归列出
|
||||
List(ctx context.Context, path string, recursive bool) ([]response.Object, error)
|
||||
}
|
||||
|
||||
// FileSystem 管理文件的文件系统
|
||||
|
||||
@@ -297,8 +297,6 @@ func GenericAfterUpload(ctx context.Context, fs *FileSystem) error {
|
||||
// 异步尝试生成缩略图
|
||||
if fs.User.Policy.IsThumbGenerateNeeded() {
|
||||
go fs.GenerateThumbnail(ctx, file)
|
||||
} else if fs.User.Policy.IsMockThumbNeeded() {
|
||||
file.UpdatePicInfo("1,1")
|
||||
}
|
||||
|
||||
return nil
|
||||
|
||||
@@ -38,7 +38,11 @@ func (fs *FileSystem) GetThumb(ctx context.Context, id uint) (*response.ContentR
|
||||
res.MaxAge = model.GetIntSetting("preview_timeout", 60)
|
||||
}
|
||||
|
||||
// TODO 出错时重新生成缩略图
|
||||
// 出错时重新生成缩略图
|
||||
if err != nil {
|
||||
fs.GenerateThumbnail(ctx, &fs.FileTarget[0])
|
||||
}
|
||||
|
||||
return res, err
|
||||
}
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ type Object struct {
|
||||
// Rename 重命名对象
|
||||
func (fs *FileSystem) Rename(ctx context.Context, dir, file []uint, new string) (err error) {
|
||||
// 验证新名字
|
||||
if !fs.ValidateLegalName(ctx, new) || !fs.ValidateExtension(ctx, new) {
|
||||
if !fs.ValidateLegalName(ctx, new) || (len(file) > 0 && !fs.ValidateExtension(ctx, new)) {
|
||||
return ErrIllegalObjectName
|
||||
}
|
||||
|
||||
@@ -131,8 +131,8 @@ func (fs *FileSystem) Move(ctx context.Context, dirs, files []uint, src, dst str
|
||||
return err
|
||||
}
|
||||
|
||||
// Delete 递归删除对象
|
||||
func (fs *FileSystem) Delete(ctx context.Context, dirs, files []uint) error {
|
||||
// Delete 递归删除对象, force 为 true 时强制删除文件记录,忽略物理删除是否成功
|
||||
func (fs *FileSystem) Delete(ctx context.Context, dirs, files []uint, force bool) error {
|
||||
// 已删除的总容量,map用于去重
|
||||
var deletedStorage = make(map[uint]uint64)
|
||||
var totalStorage = make(map[uint]uint64)
|
||||
@@ -182,7 +182,12 @@ func (fs *FileSystem) Delete(ctx context.Context, dirs, files []uint) error {
|
||||
totalStorage[fs.FileTarget[i].ID] = fs.FileTarget[i].Size
|
||||
allFileIDs = append(allFileIDs, fs.FileTarget[i].ID)
|
||||
}
|
||||
// TODO 用户自主选择是否强制删除
|
||||
|
||||
// 如果强制删除,则将全部文件视为删除成功
|
||||
if force {
|
||||
deletedFileIDs = allFileIDs
|
||||
deletedStorage = totalStorage
|
||||
}
|
||||
|
||||
// 删除文件记录
|
||||
err = model.DeleteFileByIDs(deletedFileIDs)
|
||||
@@ -280,6 +285,38 @@ func (fs *FileSystem) List(ctx context.Context, dirPath string, pathProcessor fu
|
||||
return fs.listObjects(ctx, parentPath, childFiles, childFolders, pathProcessor), nil
|
||||
}
|
||||
|
||||
// ListPhysical 列出存储策略中的外部目录
|
||||
// TODO:测试
|
||||
func (fs *FileSystem) ListPhysical(ctx context.Context, dirPath string) ([]Object, error) {
|
||||
if err := fs.DispatchHandler(); fs.Policy == nil || err != nil {
|
||||
return nil, ErrUnknownPolicyType
|
||||
}
|
||||
|
||||
// 存储策略不支持列取时,返回空结果
|
||||
if !fs.Policy.CanStructureBeListed() {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// 列取路径
|
||||
objects, err := fs.Handler.List(ctx, dirPath, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var (
|
||||
folders []model.Folder
|
||||
)
|
||||
for _, object := range objects {
|
||||
if object.IsDir {
|
||||
folders = append(folders, model.Folder{
|
||||
Name: object.Name,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return fs.listObjects(ctx, dirPath, nil, folders, nil), nil
|
||||
}
|
||||
|
||||
func (fs *FileSystem) listObjects(ctx context.Context, parent string, files []model.File, folders []model.Folder, pathProcessor func(string) string) []Object {
|
||||
// 分享文件的ID
|
||||
shareKey := ""
|
||||
|
||||
@@ -8,14 +8,62 @@ import (
|
||||
"github.com/HFO4/cloudreve/pkg/cache"
|
||||
"github.com/HFO4/cloudreve/pkg/conf"
|
||||
"github.com/HFO4/cloudreve/pkg/filesystem/fsctx"
|
||||
"github.com/HFO4/cloudreve/pkg/filesystem/response"
|
||||
"github.com/HFO4/cloudreve/pkg/serializer"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
testMock "github.com/stretchr/testify/mock"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFileSystem_ListPhysical(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
fs := &FileSystem{
|
||||
User: &model.User{
|
||||
Model: gorm.Model{
|
||||
ID: 1,
|
||||
},
|
||||
},
|
||||
Policy: &model.Policy{Type: "mock"},
|
||||
}
|
||||
ctx := context.Background()
|
||||
|
||||
// 未知存储策略
|
||||
{
|
||||
fs.Policy.Type = "unknown"
|
||||
res, err := fs.ListPhysical(ctx, "/")
|
||||
asserts.Equal(ErrUnknownPolicyType, err)
|
||||
asserts.Empty(res)
|
||||
fs.Policy.Type = "mock"
|
||||
}
|
||||
|
||||
// 无法列取目录
|
||||
{
|
||||
testHandler := new(FileHeaderMock)
|
||||
testHandler.On("List", testMock.Anything, "/", testMock.Anything).Return([]response.Object{}, errors.New("error"))
|
||||
fs.Handler = testHandler
|
||||
res, err := fs.ListPhysical(ctx, "/")
|
||||
asserts.EqualError(err, "error")
|
||||
asserts.Empty(res)
|
||||
}
|
||||
|
||||
// 成功
|
||||
{
|
||||
testHandler := new(FileHeaderMock)
|
||||
testHandler.On("List", testMock.Anything, "/", testMock.Anything).Return(
|
||||
[]response.Object{{IsDir: true, Name: "1"}, {IsDir: false, Name: "2"}},
|
||||
nil,
|
||||
)
|
||||
fs.Handler = testHandler
|
||||
res, err := fs.ListPhysical(ctx, "/")
|
||||
asserts.NoError(err)
|
||||
asserts.Len(res, 1)
|
||||
asserts.Equal("1", res[0].Name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_List(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
fs := &FileSystem{User: &model.User{
|
||||
@@ -342,12 +390,65 @@ func TestFileSystem_Delete(t *testing.T) {
|
||||
WillReturnResult(sqlmock.NewResult(0, 3))
|
||||
mock.ExpectCommit()
|
||||
|
||||
err := fs.Delete(ctx, []uint{1}, []uint{1})
|
||||
err := fs.Delete(ctx, []uint{1}, []uint{1}, false)
|
||||
asserts.Error(err)
|
||||
asserts.Equal(203, err.(serializer.AppError).Code)
|
||||
asserts.Equal(uint64(3), fs.User.Storage)
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
}
|
||||
//全部未成功,强制
|
||||
{
|
||||
fs.CleanTargets()
|
||||
mock.ExpectQuery("SELECT(.+)").
|
||||
WillReturnRows(
|
||||
sqlmock.NewRows([]string{"id"}).
|
||||
AddRow(1).
|
||||
AddRow(2).
|
||||
AddRow(3),
|
||||
)
|
||||
mock.ExpectQuery("SELECT(.+)").
|
||||
WithArgs(1, 2, 3).
|
||||
WillReturnRows(
|
||||
sqlmock.NewRows([]string{"id", "name", "source_name", "policy_id", "size"}).
|
||||
AddRow(4, "1.txt", "1.txt", 365, 1),
|
||||
)
|
||||
mock.ExpectQuery("SELECT(.+)").WillReturnRows(sqlmock.NewRows([]string{"id", "name", "source_name", "policy_id", "size"}).AddRow(1, "2.txt", "2.txt", 365, 2))
|
||||
mock.ExpectQuery("SELECT(.+)files(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "policy_id", "source_name"}))
|
||||
// 查询上传策略
|
||||
mock.ExpectQuery("SELECT(.+)").WillReturnRows(sqlmock.NewRows([]string{"id", "type"}).AddRow(365, "local"))
|
||||
// 删除文件记录
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("DELETE(.+)").
|
||||
WillReturnResult(sqlmock.NewResult(0, 3))
|
||||
mock.ExpectCommit()
|
||||
// 删除对应分享
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)shares").
|
||||
WillReturnResult(sqlmock.NewResult(0, 3))
|
||||
mock.ExpectCommit()
|
||||
// 归还容量
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)").
|
||||
WillReturnResult(sqlmock.NewResult(0, 3))
|
||||
mock.ExpectCommit()
|
||||
// 删除目录
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("DELETE(.+)").
|
||||
WillReturnResult(sqlmock.NewResult(0, 3))
|
||||
mock.ExpectCommit()
|
||||
// 删除对应分享
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)shares").
|
||||
WillReturnResult(sqlmock.NewResult(0, 3))
|
||||
mock.ExpectCommit()
|
||||
|
||||
fs.FileTarget = []model.File{}
|
||||
fs.DirTarget = []model.Folder{}
|
||||
err := fs.Delete(ctx, []uint{1}, []uint{1}, true)
|
||||
asserts.NoError(err)
|
||||
asserts.Equal(uint64(0), fs.User.Storage)
|
||||
}
|
||||
//全部成功
|
||||
{
|
||||
fs.CleanTargets()
|
||||
@@ -402,7 +503,7 @@ func TestFileSystem_Delete(t *testing.T) {
|
||||
|
||||
fs.FileTarget = []model.File{}
|
||||
fs.DirTarget = []model.Folder{}
|
||||
err = fs.Delete(ctx, []uint{1}, []uint{1})
|
||||
err = fs.Delete(ctx, []uint{1}, []uint{1}, false)
|
||||
asserts.NoError(err)
|
||||
asserts.Equal(uint64(0), fs.User.Storage)
|
||||
}
|
||||
@@ -606,12 +707,39 @@ func TestFileSystem_Rename(t *testing.T) {
|
||||
asserts.Equal(ErrPathNotExist, err)
|
||||
}
|
||||
|
||||
// 新名字不合法
|
||||
// 新名字是目录,不合法
|
||||
{
|
||||
err := fs.Rename(ctx, []uint{10}, []uint{}, "ne/w")
|
||||
asserts.Error(err)
|
||||
asserts.Equal(ErrIllegalObjectName, err)
|
||||
}
|
||||
|
||||
// 新名字是文件,不合法
|
||||
{
|
||||
err := fs.Rename(ctx, []uint{}, []uint{10}, "ne/w")
|
||||
asserts.Error(err)
|
||||
asserts.Equal(ErrIllegalObjectName, err)
|
||||
}
|
||||
|
||||
// 新名字是文件,扩展名不合法
|
||||
{
|
||||
fs.User.Policy.OptionsSerialized.FileType = []string{"txt"}
|
||||
err := fs.Rename(ctx, []uint{}, []uint{10}, "1.jpg")
|
||||
asserts.Error(err)
|
||||
asserts.Equal(ErrIllegalObjectName, err)
|
||||
}
|
||||
|
||||
// 新名字是目录,不应该检测扩展名
|
||||
{
|
||||
fs.User.Policy.OptionsSerialized.FileType = []string{"txt"}
|
||||
mock.ExpectQuery("SELECT(.+)folders(.+)").
|
||||
WithArgs(10, 1).
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "name"}))
|
||||
err := fs.Rename(ctx, []uint{10}, []uint{}, "new")
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.Error(err)
|
||||
asserts.Equal(ErrPathNotExist, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileSystem_SaveTo(t *testing.T) {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package response
|
||||
|
||||
import "io"
|
||||
import (
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ContentResponse 获取文件内容类方法的通用返回值。
|
||||
// 有些上传策略需要重定向,
|
||||
@@ -17,3 +20,13 @@ type RSCloser interface {
|
||||
io.ReadSeeker
|
||||
io.Closer
|
||||
}
|
||||
|
||||
// Object 列出文件、目录时返回的对象
|
||||
type Object struct {
|
||||
Name string `json:"name"`
|
||||
RelativePath string `json:"relative_path"`
|
||||
Source string `json:"source"`
|
||||
Size uint64 `json:"size"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
LastModify time.Time `json:"last_modify"`
|
||||
}
|
||||
|
||||
@@ -26,6 +26,11 @@ type FileHeaderMock struct {
|
||||
testMock.Mock
|
||||
}
|
||||
|
||||
func (m FileHeaderMock) List(ctx context.Context, path string, recursive bool) ([]response.Object, error) {
|
||||
args := m.Called(ctx, path, recursive)
|
||||
return args.Get(0).([]response.Object), args.Error(1)
|
||||
}
|
||||
|
||||
func (m FileHeaderMock) Get(ctx context.Context, path string) (response.RSCloser, error) {
|
||||
args := m.Called(ctx, path)
|
||||
return args.Get(0).(response.RSCloser), args.Error(1)
|
||||
@@ -60,10 +65,10 @@ func TestFileSystem_Upload(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
|
||||
// 正常
|
||||
testHandller := new(FileHeaderMock)
|
||||
testHandller.On("Put", testMock.Anything, testMock.Anything, testMock.Anything).Return(nil)
|
||||
testHandler := new(FileHeaderMock)
|
||||
testHandler.On("Put", testMock.Anything, testMock.Anything, testMock.Anything).Return(nil)
|
||||
fs := &FileSystem{
|
||||
Handler: testHandller,
|
||||
Handler: testHandler,
|
||||
User: &model.User{
|
||||
Model: gorm.Model{
|
||||
ID: 1,
|
||||
@@ -88,10 +93,10 @@ func TestFileSystem_Upload(t *testing.T) {
|
||||
asserts.NoError(err)
|
||||
|
||||
// 正常,上下文已指定源文件
|
||||
testHandller = new(FileHeaderMock)
|
||||
testHandller.On("Put", testMock.Anything, testMock.Anything, "123/123.txt").Return(nil)
|
||||
testHandler = new(FileHeaderMock)
|
||||
testHandler.On("Put", testMock.Anything, testMock.Anything, "123/123.txt").Return(nil)
|
||||
fs = &FileSystem{
|
||||
Handler: testHandller,
|
||||
Handler: testHandler,
|
||||
User: &model.User{
|
||||
Model: gorm.Model{
|
||||
ID: 1,
|
||||
@@ -124,20 +129,20 @@ func TestFileSystem_Upload(t *testing.T) {
|
||||
err = fs.Upload(ctx, file)
|
||||
asserts.Error(err)
|
||||
fs.Hooks["BeforeUpload"] = nil
|
||||
testHandller.AssertExpectations(t)
|
||||
testHandler.AssertExpectations(t)
|
||||
|
||||
// 上传文件失败
|
||||
testHandller2 := new(FileHeaderMock)
|
||||
testHandller2.On("Put", testMock.Anything, testMock.Anything, testMock.Anything).Return(errors.New("error"))
|
||||
fs.Handler = testHandller2
|
||||
testHandler2 := new(FileHeaderMock)
|
||||
testHandler2.On("Put", testMock.Anything, testMock.Anything, testMock.Anything).Return(errors.New("error"))
|
||||
fs.Handler = testHandler2
|
||||
err = fs.Upload(ctx, file)
|
||||
asserts.Error(err)
|
||||
testHandller2.AssertExpectations(t)
|
||||
testHandler2.AssertExpectations(t)
|
||||
|
||||
// AfterUpload失败
|
||||
testHandller3 := new(FileHeaderMock)
|
||||
testHandller3.On("Put", testMock.Anything, testMock.Anything, testMock.Anything).Return(nil)
|
||||
fs.Handler = testHandller3
|
||||
testHandler3 := new(FileHeaderMock)
|
||||
testHandler3.On("Put", testMock.Anything, testMock.Anything, testMock.Anything).Return(nil)
|
||||
fs.Handler = testHandler3
|
||||
fs.Use("AfterUpload", func(ctx context.Context, fs *FileSystem) error {
|
||||
return errors.New("error")
|
||||
})
|
||||
@@ -146,7 +151,7 @@ func TestFileSystem_Upload(t *testing.T) {
|
||||
})
|
||||
err = fs.Upload(ctx, file)
|
||||
asserts.Error(err)
|
||||
testHandller2.AssertExpectations(t)
|
||||
testHandler2.AssertExpectations(t)
|
||||
|
||||
}
|
||||
|
||||
@@ -180,11 +185,11 @@ func TestFileSystem_GetUploadToken(t *testing.T) {
|
||||
"upload_credential_timeout": "10",
|
||||
"upload_session_timeout": "10",
|
||||
}, "setting_")
|
||||
testHandller := new(FileHeaderMock)
|
||||
testHandller.On("Token", testMock.Anything, int64(10), testMock.Anything).Return(serializer.UploadCredential{Token: "test"}, nil)
|
||||
fs.Handler = testHandller
|
||||
testHandler := new(FileHeaderMock)
|
||||
testHandler.On("Token", testMock.Anything, int64(10), testMock.Anything).Return(serializer.UploadCredential{Token: "test"}, nil)
|
||||
fs.Handler = testHandler
|
||||
res, err := fs.GetUploadToken(ctx, "/", 10, "123")
|
||||
testHandller.AssertExpectations(t)
|
||||
testHandler.AssertExpectations(t)
|
||||
asserts.NoError(err)
|
||||
asserts.Equal("test", res.Token)
|
||||
}
|
||||
@@ -195,11 +200,11 @@ func TestFileSystem_GetUploadToken(t *testing.T) {
|
||||
"upload_credential_timeout": "10",
|
||||
"upload_session_timeout": "10",
|
||||
}, "setting_")
|
||||
testHandller := new(FileHeaderMock)
|
||||
testHandller.On("Token", testMock.Anything, int64(10), testMock.Anything).Return(serializer.UploadCredential{}, errors.New("error"))
|
||||
fs.Handler = testHandller
|
||||
testHandler := new(FileHeaderMock)
|
||||
testHandler.On("Token", testMock.Anything, int64(10), testMock.Anything).Return(serializer.UploadCredential{}, errors.New("error"))
|
||||
fs.Handler = testHandler
|
||||
_, err := fs.GetUploadToken(ctx, "/", 10, "123")
|
||||
testHandller.AssertExpectations(t)
|
||||
testHandler.AssertExpectations(t)
|
||||
asserts.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
package recaptcha
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"time"
|
||||
)
|
||||
|
||||
const reCAPTCHALink = "https://www.recaptcha.net/recaptcha/api/siteverify"
|
||||
|
||||
// VERSION the recaptcha api version
|
||||
type VERSION int8
|
||||
|
||||
const (
|
||||
// V2 recaptcha api v2
|
||||
V2 VERSION = iota
|
||||
// V3 recaptcha api v3, more details can be found here : https://developers.google.com/recaptcha/docs/v3
|
||||
V3
|
||||
// DefaultTreshold Default minimin score when using V3 api
|
||||
DefaultTreshold float32 = 0.5
|
||||
)
|
||||
|
||||
type reCHAPTCHARequest struct {
|
||||
Secret string `json:"secret"`
|
||||
Response string `json:"response"`
|
||||
RemoteIP string `json:"remoteip,omitempty"`
|
||||
}
|
||||
|
||||
type reCHAPTCHAResponse struct {
|
||||
Success bool `json:"success"`
|
||||
ChallengeTS time.Time `json:"challenge_ts"`
|
||||
Hostname string `json:"hostname,omitempty"`
|
||||
ApkPackageName string `json:"apk_package_name,omitempty"`
|
||||
Action string `json:"action,omitempty"`
|
||||
Score float32 `json:"score,omitempty"`
|
||||
ErrorCodes []string `json:"error-codes,omitempty"`
|
||||
}
|
||||
|
||||
// custom client so we can mock in tests
|
||||
type netClient interface {
|
||||
PostForm(url string, formValues url.Values) (resp *http.Response, err error)
|
||||
}
|
||||
|
||||
// custom clock so we can mock in tests
|
||||
type clock interface {
|
||||
Since(t time.Time) time.Duration
|
||||
}
|
||||
|
||||
type realClock struct {
|
||||
}
|
||||
|
||||
func (realClock) Since(t time.Time) time.Duration {
|
||||
return time.Since(t)
|
||||
}
|
||||
|
||||
// ReCAPTCHA recpatcha holder struct, make adding mocking code simpler
|
||||
type ReCAPTCHA struct {
|
||||
client netClient
|
||||
Secret string
|
||||
ReCAPTCHALink string
|
||||
Version VERSION
|
||||
Timeout time.Duration
|
||||
horloge clock
|
||||
}
|
||||
|
||||
// NewReCAPTCHA new ReCAPTCHA instance if version is set to V2 uses recatpcha v2 API, get your secret from https://www.google.com/recaptcha/admin
|
||||
// if version is set to V2 uses recatpcha v2 API, get your secret from https://g.co/recaptcha/v3
|
||||
func NewReCAPTCHA(ReCAPTCHASecret string, version VERSION, timeout time.Duration) (ReCAPTCHA, error) {
|
||||
if ReCAPTCHASecret == "" {
|
||||
return ReCAPTCHA{}, fmt.Errorf("recaptcha secret cannot be blank")
|
||||
}
|
||||
return ReCAPTCHA{
|
||||
client: &http.Client{
|
||||
Timeout: timeout,
|
||||
},
|
||||
horloge: &realClock{},
|
||||
Secret: ReCAPTCHASecret,
|
||||
ReCAPTCHALink: reCAPTCHALink,
|
||||
Timeout: timeout,
|
||||
Version: version,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Verify returns `nil` if no error and the client solved the challenge correctly
|
||||
func (r *ReCAPTCHA) Verify(challengeResponse string) error {
|
||||
body := reCHAPTCHARequest{Secret: r.Secret, Response: challengeResponse}
|
||||
return r.confirm(body, VerifyOption{})
|
||||
}
|
||||
|
||||
// VerifyOption verification options expected for the challenge
|
||||
type VerifyOption struct {
|
||||
Threshold float32 // ignored in v2 recaptcha
|
||||
Action string // ignored in v2 recaptcha
|
||||
Hostname string
|
||||
ApkPackageName string
|
||||
ResponseTime time.Duration
|
||||
RemoteIP string
|
||||
}
|
||||
|
||||
// VerifyWithOptions returns `nil` if no error and the client solved the challenge correctly and all options are natching
|
||||
// `Threshold` and `Action` are ignored when using V2 version
|
||||
func (r *ReCAPTCHA) VerifyWithOptions(challengeResponse string, options VerifyOption) error {
|
||||
var body reCHAPTCHARequest
|
||||
if options.RemoteIP == "" {
|
||||
body = reCHAPTCHARequest{Secret: r.Secret, Response: challengeResponse}
|
||||
} else {
|
||||
body = reCHAPTCHARequest{Secret: r.Secret, Response: challengeResponse, RemoteIP: options.RemoteIP}
|
||||
}
|
||||
return r.confirm(body, options)
|
||||
}
|
||||
|
||||
func (r *ReCAPTCHA) confirm(recaptcha reCHAPTCHARequest, options VerifyOption) (Err error) {
|
||||
Err = nil
|
||||
var formValues url.Values
|
||||
if recaptcha.RemoteIP != "" {
|
||||
formValues = url.Values{"secret": {recaptcha.Secret}, "remoteip": {recaptcha.RemoteIP}, "response": {recaptcha.Response}}
|
||||
} else {
|
||||
formValues = url.Values{"secret": {recaptcha.Secret}, "response": {recaptcha.Response}}
|
||||
}
|
||||
response, err := r.client.PostForm(r.ReCAPTCHALink, formValues)
|
||||
if err != nil {
|
||||
Err = fmt.Errorf("error posting to recaptcha endpoint: '%s'", err)
|
||||
return
|
||||
}
|
||||
defer response.Body.Close()
|
||||
resultBody, err := ioutil.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
Err = fmt.Errorf("couldn't read response body: '%s'", err)
|
||||
return
|
||||
}
|
||||
var result reCHAPTCHAResponse
|
||||
err = json.Unmarshal(resultBody, &result)
|
||||
if err != nil {
|
||||
Err = fmt.Errorf("invalid response body json: '%s'", err)
|
||||
return
|
||||
}
|
||||
|
||||
if options.Hostname != "" && options.Hostname != result.Hostname {
|
||||
Err = fmt.Errorf("invalid response hostname '%s', while expecting '%s'", result.Hostname, options.Hostname)
|
||||
return
|
||||
}
|
||||
|
||||
if options.ApkPackageName != "" && options.ApkPackageName != result.ApkPackageName {
|
||||
Err = fmt.Errorf("invalid response ApkPackageName '%s', while expecting '%s'", result.ApkPackageName, options.ApkPackageName)
|
||||
return
|
||||
}
|
||||
|
||||
if options.ResponseTime != 0 {
|
||||
duration := r.horloge.Since(result.ChallengeTS)
|
||||
if options.ResponseTime < duration {
|
||||
Err = fmt.Errorf("time spent in resolving challenge '%fs', while expecting maximum '%fs'", duration.Seconds(), options.ResponseTime.Seconds())
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.Version == V3 {
|
||||
if options.Action != "" && options.Action != result.Action {
|
||||
Err = fmt.Errorf("invalid response action '%s', while expecting '%s'", result.Action, options.Action)
|
||||
return
|
||||
}
|
||||
if options.Threshold != 0 && options.Threshold >= result.Score {
|
||||
Err = fmt.Errorf("received score '%f', while expecting minimum '%f'", result.Score, options.Threshold)
|
||||
return
|
||||
}
|
||||
if options.Threshold == 0 && DefaultTreshold >= result.Score {
|
||||
Err = fmt.Errorf("received score '%f', while expecting minimum '%f'", result.Score, DefaultTreshold)
|
||||
return
|
||||
}
|
||||
}
|
||||
if result.ErrorCodes != nil {
|
||||
Err = fmt.Errorf("remote error codes: %v", result.ErrorCodes)
|
||||
return
|
||||
}
|
||||
if !result.Success && recaptcha.RemoteIP != "" {
|
||||
Err = fmt.Errorf("invalid challenge solution or remote IP")
|
||||
} else if !result.Success {
|
||||
Err = fmt.Errorf("invalid challenge solution")
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import model "github.com/HFO4/cloudreve/models"
|
||||
// SiteConfig 站点全局设置序列
|
||||
type SiteConfig struct {
|
||||
SiteName string `json:"title"`
|
||||
SiteICPId string `json:"siteICPId"`
|
||||
LoginCaptcha bool `json:"loginCaptcha"`
|
||||
RegCaptcha bool `json:"regCaptcha"`
|
||||
ForgetCaptcha bool `json:"forgetCaptcha"`
|
||||
@@ -13,8 +14,10 @@ type SiteConfig struct {
|
||||
DefaultTheme string `json:"defaultTheme"`
|
||||
HomepageViewMethod string `json:"home_view_method"`
|
||||
ShareViewMethod string `json:"share_view_method"`
|
||||
Authn bool `json:"authn"'`
|
||||
Authn bool `json:"authn"`
|
||||
User User `json:"user"`
|
||||
UseReCaptcha bool `json:"captcha_IsUseReCaptcha"`
|
||||
ReCaptchaKey string `json:"captcha_ReCaptchaKey"`
|
||||
}
|
||||
|
||||
type task struct {
|
||||
@@ -62,6 +65,7 @@ func BuildSiteConfig(settings map[string]string, user *model.User) Response {
|
||||
res := Response{
|
||||
Data: SiteConfig{
|
||||
SiteName: checkSettingValue(settings, "siteName"),
|
||||
SiteICPId: checkSettingValue(settings, "siteICPId"),
|
||||
LoginCaptcha: model.IsTrueVal(checkSettingValue(settings, "login_captcha")),
|
||||
RegCaptcha: model.IsTrueVal(checkSettingValue(settings, "reg_captcha")),
|
||||
ForgetCaptcha: model.IsTrueVal(checkSettingValue(settings, "forget_captcha")),
|
||||
@@ -72,6 +76,8 @@ func BuildSiteConfig(settings map[string]string, user *model.User) Response {
|
||||
ShareViewMethod: checkSettingValue(settings, "share_view_method"),
|
||||
Authn: model.IsTrueVal(checkSettingValue(settings, "authn_enabled")),
|
||||
User: userRes,
|
||||
UseReCaptcha: model.IsTrueVal(checkSettingValue(settings, "captcha_IsUseReCaptcha")),
|
||||
ReCaptchaKey: checkSettingValue(settings, "captcha_ReCaptchaKey"),
|
||||
}}
|
||||
return res
|
||||
}
|
||||
|
||||
@@ -4,3 +4,9 @@ package serializer
|
||||
type RemoteDeleteRequest struct {
|
||||
Files []string `json:"files"`
|
||||
}
|
||||
|
||||
// ListRequest 远程策略列文件请求正文
|
||||
type ListRequest struct {
|
||||
Path string `json:"path"`
|
||||
Recursive bool `json:"recursive"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,221 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
model "github.com/HFO4/cloudreve/models"
|
||||
"github.com/HFO4/cloudreve/pkg/filesystem"
|
||||
"github.com/HFO4/cloudreve/pkg/filesystem/driver/local"
|
||||
"github.com/HFO4/cloudreve/pkg/filesystem/fsctx"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"path"
|
||||
)
|
||||
|
||||
// ImportTask 导入务
|
||||
type ImportTask struct {
|
||||
User *model.User
|
||||
TaskModel *model.Task
|
||||
TaskProps ImportProps
|
||||
Err *JobError
|
||||
}
|
||||
|
||||
// ImportProps 导入任务属性
|
||||
type ImportProps struct {
|
||||
PolicyID uint `json:"policy_id"` // 存储策略ID
|
||||
Src string `json:"src"` // 原始路径
|
||||
Recursive bool `json:"is_recursive"` // 是否递归导入
|
||||
Dst string `json:"dst"` // 目的目录
|
||||
}
|
||||
|
||||
// Props 获取任务属性
|
||||
func (job *ImportTask) Props() string {
|
||||
res, _ := json.Marshal(job.TaskProps)
|
||||
return string(res)
|
||||
}
|
||||
|
||||
// Type 获取任务状态
|
||||
func (job *ImportTask) Type() int {
|
||||
return ImportTaskType
|
||||
}
|
||||
|
||||
// Creator 获取创建者ID
|
||||
func (job *ImportTask) Creator() uint {
|
||||
return job.User.ID
|
||||
}
|
||||
|
||||
// Model 获取任务的数据库模型
|
||||
func (job *ImportTask) Model() *model.Task {
|
||||
return job.TaskModel
|
||||
}
|
||||
|
||||
// SetStatus 设定状态
|
||||
func (job *ImportTask) SetStatus(status int) {
|
||||
job.TaskModel.SetStatus(status)
|
||||
}
|
||||
|
||||
// SetError 设定任务失败信息
|
||||
func (job *ImportTask) SetError(err *JobError) {
|
||||
job.Err = err
|
||||
res, _ := json.Marshal(job.Err)
|
||||
job.TaskModel.SetError(string(res))
|
||||
}
|
||||
|
||||
// SetErrorMsg 设定任务失败信息
|
||||
func (job *ImportTask) SetErrorMsg(msg string, err error) {
|
||||
jobErr := &JobError{Msg: msg}
|
||||
if err != nil {
|
||||
jobErr.Error = err.Error()
|
||||
}
|
||||
job.SetError(jobErr)
|
||||
}
|
||||
|
||||
// GetError 返回任务失败信息
|
||||
func (job *ImportTask) GetError() *JobError {
|
||||
return job.Err
|
||||
}
|
||||
|
||||
// Do 开始执行任务
|
||||
func (job *ImportTask) Do() {
|
||||
ctx := context.Background()
|
||||
|
||||
// 查找存储策略
|
||||
policy, err := model.GetPolicyByID(job.TaskProps.PolicyID)
|
||||
if err != nil {
|
||||
job.SetErrorMsg("找不到存储策略", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 创建文件系统
|
||||
job.User.Policy = policy
|
||||
fs, err := filesystem.NewFileSystem(job.User)
|
||||
if err != nil {
|
||||
job.SetErrorMsg(err.Error(), nil)
|
||||
return
|
||||
}
|
||||
defer fs.Recycle()
|
||||
|
||||
// 注册钩子
|
||||
fs.Use("BeforeAddFile", filesystem.HookValidateFile)
|
||||
fs.Use("BeforeAddFile", filesystem.HookValidateCapacity)
|
||||
fs.Use("AfterValidateFailed", filesystem.HookGiveBackCapacity)
|
||||
|
||||
// 列取目录、对象
|
||||
job.TaskModel.SetProgress(ListingProgress)
|
||||
coxIgnoreConflict := context.WithValue(context.Background(), fsctx.IgnoreConflictCtx,
|
||||
true)
|
||||
objects, err := fs.Handler.List(ctx, job.TaskProps.Src, job.TaskProps.Recursive)
|
||||
if err != nil {
|
||||
job.SetErrorMsg("无法列取文件", err)
|
||||
return
|
||||
}
|
||||
|
||||
job.TaskModel.SetProgress(InsertingProgress)
|
||||
|
||||
// 虚拟目录路径与folder对象ID的对应
|
||||
pathCache := make(map[string]*model.Folder, len(objects))
|
||||
|
||||
// 插入目录记录到用户文件系统
|
||||
for _, object := range objects {
|
||||
if object.IsDir {
|
||||
// 创建目录
|
||||
virtualPath := path.Join(job.TaskProps.Dst, object.RelativePath)
|
||||
folder, err := fs.CreateDirectory(coxIgnoreConflict, virtualPath)
|
||||
if err != nil {
|
||||
util.Log().Warning("导入任务无法创建用户目录[%s], %s", virtualPath, err)
|
||||
} else if folder.ID > 0 {
|
||||
pathCache[virtualPath] = folder
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 插入文件记录到用户文件系统
|
||||
for _, object := range objects {
|
||||
if !object.IsDir {
|
||||
// 创建文件信息
|
||||
virtualPath := path.Dir(path.Join(job.TaskProps.Dst, object.RelativePath))
|
||||
fileHeader := local.FileStream{
|
||||
Size: object.Size,
|
||||
VirtualPath: virtualPath,
|
||||
Name: object.Name,
|
||||
}
|
||||
addFileCtx := context.WithValue(ctx, fsctx.FileHeaderCtx, fileHeader)
|
||||
addFileCtx = context.WithValue(addFileCtx, fsctx.SavePathCtx, object.Source)
|
||||
|
||||
// 查找父目录
|
||||
parentFolder := &model.Folder{}
|
||||
if parent, ok := pathCache[virtualPath]; ok {
|
||||
parentFolder = parent
|
||||
} else {
|
||||
exist, folder := fs.IsPathExist(virtualPath)
|
||||
if exist {
|
||||
parentFolder = folder
|
||||
} else {
|
||||
folder, err := fs.CreateDirectory(context.Background(), virtualPath)
|
||||
if err != nil {
|
||||
util.Log().Warning("导入任务无法创建用户目录[%s], %s",
|
||||
virtualPath, err)
|
||||
continue
|
||||
}
|
||||
parentFolder = folder
|
||||
}
|
||||
}
|
||||
|
||||
// 插入文件记录
|
||||
_, err := fs.AddFile(addFileCtx, parentFolder)
|
||||
if err != nil {
|
||||
util.Log().Warning("导入任务无法创插入文件[%s], %s",
|
||||
object.RelativePath, err)
|
||||
if err == filesystem.ErrInsufficientCapacity {
|
||||
job.SetErrorMsg("容量不足", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NewImportTask 新建导入任务
|
||||
func NewImportTask(user, policy uint, src, dst string, recursive bool) (Job, error) {
|
||||
creator, err := model.GetActiveUserByID(user)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
newTask := &ImportTask{
|
||||
User: &creator,
|
||||
TaskProps: ImportProps{
|
||||
PolicyID: policy,
|
||||
Recursive: recursive,
|
||||
Src: src,
|
||||
Dst: dst,
|
||||
},
|
||||
}
|
||||
|
||||
record, err := Record(newTask)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
newTask.TaskModel = record
|
||||
|
||||
return newTask, nil
|
||||
}
|
||||
|
||||
// NewImportTaskFromModel 从数据库记录中恢复导入任务
|
||||
func NewImportTaskFromModel(task *model.Task) (Job, error) {
|
||||
user, err := model.GetActiveUserByID(task.UserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
newTask := &ImportTask{
|
||||
User: &user,
|
||||
TaskModel: task,
|
||||
}
|
||||
|
||||
err = json.Unmarshal([]byte(task.Props), &newTask.TaskProps)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return newTask, nil
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
model "github.com/HFO4/cloudreve/models"
|
||||
"github.com/HFO4/cloudreve/pkg/cache"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/jinzhu/gorm"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestImportTask_Props(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
task := &ImportTask{
|
||||
User: &model.User{},
|
||||
}
|
||||
asserts.NotEmpty(task.Props())
|
||||
asserts.Equal(ImportTaskType, task.Type())
|
||||
asserts.EqualValues(0, task.Creator())
|
||||
asserts.Nil(task.Model())
|
||||
}
|
||||
|
||||
func TestImportTask_SetStatus(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
task := &ImportTask{
|
||||
User: &model.User{},
|
||||
TaskModel: &model.Task{
|
||||
Model: gorm.Model{ID: 1},
|
||||
},
|
||||
}
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
task.SetStatus(3)
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
}
|
||||
|
||||
func TestImportTask_SetError(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
task := &ImportTask{
|
||||
User: &model.User{},
|
||||
TaskModel: &model.Task{
|
||||
Model: gorm.Model{ID: 1},
|
||||
},
|
||||
}
|
||||
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
task.SetErrorMsg("error", nil)
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.Equal("error", task.GetError().Msg)
|
||||
}
|
||||
|
||||
func TestImportTask_Do(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
task := &ImportTask{
|
||||
User: &model.User{},
|
||||
TaskModel: &model.Task{
|
||||
Model: gorm.Model{ID: 1},
|
||||
},
|
||||
TaskProps: ImportProps{
|
||||
PolicyID: 63,
|
||||
Src: "",
|
||||
Recursive: false,
|
||||
Dst: "",
|
||||
},
|
||||
}
|
||||
|
||||
// 存储策略不存在
|
||||
{
|
||||
cache.Deletes([]string{"63"}, "policy_")
|
||||
mock.ExpectQuery("SELECT(.+)policies(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id"}))
|
||||
// 设定失败状态
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
task.Do()
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.NotEmpty(task.Err.Error)
|
||||
task.Err = nil
|
||||
}
|
||||
|
||||
// 无法分配 Filesystem
|
||||
{
|
||||
cache.Deletes([]string{"63"}, "policy_")
|
||||
mock.ExpectQuery("SELECT(.+)policies(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "type"}).AddRow(63, "unknown"))
|
||||
// 设定失败状态
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
task.Do()
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.NotEmpty(task.Err.Msg)
|
||||
task.Err = nil
|
||||
}
|
||||
|
||||
// 成功列取,但是文件为空
|
||||
{
|
||||
cache.Deletes([]string{"63"}, "policy_")
|
||||
task.TaskProps.Src = "TestImportTask_Do/empty"
|
||||
mock.ExpectQuery("SELECT(.+)policies(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "type"}).AddRow(63, "local"))
|
||||
// 设定listing状态
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
// 设定inserting状态
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
task.Do()
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.Nil(task.Err)
|
||||
task.Err = nil
|
||||
}
|
||||
|
||||
// 创建测试文件
|
||||
f, _ := util.CreatNestedFile(util.RelativePath("tests/TestImportTask_Do/test.txt"))
|
||||
f.Close()
|
||||
|
||||
// 成功列取,包含一个文件一个目录,父目录创建失败
|
||||
{
|
||||
cache.Deletes([]string{"63"}, "policy_")
|
||||
task.TaskProps.Src = "tests"
|
||||
task.TaskProps.Dst = "/"
|
||||
task.TaskProps.Recursive = true
|
||||
mock.ExpectQuery("SELECT(.+)policies(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "type"}).AddRow(63, "local"))
|
||||
// 设定listing状态
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
// 设定inserting状态
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
// 查找父目录,但是不存在
|
||||
mock.ExpectQuery("SELECT(.+)folders").WillReturnRows(sqlmock.NewRows([]string{"id"}))
|
||||
// 仍然不存在
|
||||
mock.ExpectQuery("SELECT(.+)folders").WillReturnRows(sqlmock.NewRows([]string{"id"}))
|
||||
// 创建文件时查找父目录,仍然不存在
|
||||
mock.ExpectQuery("SELECT(.+)folders").WillReturnRows(sqlmock.NewRows([]string{"id"}))
|
||||
|
||||
task.Do()
|
||||
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.Nil(task.Err)
|
||||
task.Err = nil
|
||||
}
|
||||
|
||||
// 成功列取,包含一个文件一个目录, 全部操作成功
|
||||
{
|
||||
cache.Deletes([]string{"63"}, "policy_")
|
||||
task.TaskProps.Src = "tests"
|
||||
task.TaskProps.Dst = "/"
|
||||
task.TaskProps.Recursive = true
|
||||
mock.ExpectQuery("SELECT(.+)policies(.+)").
|
||||
WillReturnRows(sqlmock.NewRows([]string{"id", "type"}).AddRow(63, "local"))
|
||||
// 设定listing状态
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
// 设定inserting状态
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("UPDATE(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
// 查找父目录,存在
|
||||
mock.ExpectQuery("SELECT(.+)folders").WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
// 查找同名文件,不存在
|
||||
mock.ExpectQuery("SELECT(.+)files").WillReturnRows(sqlmock.NewRows([]string{"id"}))
|
||||
// 创建目录
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("INSERT(.+)folders(.+)").WillReturnResult(sqlmock.NewResult(2, 1))
|
||||
mock.ExpectCommit()
|
||||
// 插入文件记录
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("INSERT(.+)files(.+)").WillReturnResult(sqlmock.NewResult(2, 1))
|
||||
mock.ExpectCommit()
|
||||
|
||||
task.Do()
|
||||
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.Nil(task.Err)
|
||||
task.Err = nil
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewImportTask(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
|
||||
// 成功
|
||||
{
|
||||
mock.ExpectQuery("SELECT(.+)").WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("INSERT(.+)").WillReturnResult(sqlmock.NewResult(1, 1))
|
||||
mock.ExpectCommit()
|
||||
job, err := NewImportTask(1, 1, "/", "/", false)
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.NotNil(job)
|
||||
asserts.NoError(err)
|
||||
}
|
||||
|
||||
// 失败
|
||||
{
|
||||
mock.ExpectQuery("SELECT(.+)").WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
mock.ExpectBegin()
|
||||
mock.ExpectExec("INSERT(.+)").WillReturnError(errors.New("error"))
|
||||
mock.ExpectRollback()
|
||||
job, err := NewImportTask(1, 1, "/", "/", false)
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.Nil(job)
|
||||
asserts.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewImportTaskFromModel(t *testing.T) {
|
||||
asserts := assert.New(t)
|
||||
|
||||
// 成功
|
||||
{
|
||||
mock.ExpectQuery("SELECT(.+)").WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
job, err := NewImportTaskFromModel(&model.Task{Props: "{}"})
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.NoError(err)
|
||||
asserts.NotNil(job)
|
||||
}
|
||||
|
||||
// JSON解析失败
|
||||
{
|
||||
mock.ExpectQuery("SELECT(.+)").WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
|
||||
job, err := NewImportTaskFromModel(&model.Task{Props: "?"})
|
||||
asserts.NoError(mock.ExpectationsWereMet())
|
||||
asserts.Error(err)
|
||||
asserts.Nil(job)
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,8 @@ const (
|
||||
DecompressTaskType
|
||||
// TransferTaskType 中转任务
|
||||
TransferTaskType
|
||||
// ImportTaskType 导入任务
|
||||
ImportTaskType
|
||||
)
|
||||
|
||||
// 任务状态
|
||||
@@ -41,6 +43,10 @@ const (
|
||||
DownloadingProgress
|
||||
// Transferring 转存中
|
||||
TransferringProgress
|
||||
// ListingProgress 索引中
|
||||
ListingProgress
|
||||
// InsertingProgress 插入中
|
||||
InsertingProgress
|
||||
)
|
||||
|
||||
// Job 任务接口
|
||||
@@ -103,6 +109,8 @@ func GetJobFromModel(task *model.Task) (Job, error) {
|
||||
return NewDecompressTaskFromModel(task)
|
||||
case TransferTaskType:
|
||||
return NewTransferTaskFromModel(task)
|
||||
case ImportTaskType:
|
||||
return NewImportTaskFromModel(task)
|
||||
default:
|
||||
return nil, ErrUnknownTaskType
|
||||
}
|
||||
|
||||
@@ -78,6 +78,8 @@ func (job *TransferTask) GetError() *JobError {
|
||||
|
||||
// Do 开始执行任务
|
||||
func (job *TransferTask) Do() {
|
||||
defer job.Recycle()
|
||||
|
||||
// 创建文件系统
|
||||
fs, err := filesystem.NewFileSystem(job.User)
|
||||
if err != nil {
|
||||
|
||||
@@ -3,6 +3,7 @@ package util
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/fatih/color"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
@@ -23,6 +24,7 @@ var Level = LevelDebug
|
||||
// Logger 日志
|
||||
type Logger struct {
|
||||
level int
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
// 日志颜色
|
||||
@@ -49,6 +51,10 @@ func (ll *Logger) Println(prefix string, msg string) {
|
||||
// color.NoColor = false
|
||||
|
||||
c := color.New()
|
||||
|
||||
ll.mu.Lock()
|
||||
defer ll.mu.Unlock()
|
||||
|
||||
_, _ = c.Printf(
|
||||
"%s%s %s %s\n",
|
||||
colors[prefix]("["+prefix+"]"),
|
||||
|
||||
@@ -281,7 +281,7 @@ func (h *Handler) handleDelete(w http.ResponseWriter, r *http.Request, fs *files
|
||||
|
||||
// 尝试作为文件删除
|
||||
if ok, file := fs.IsFileExist(reqPath); ok {
|
||||
if err := fs.Delete(ctx, []uint{}, []uint{file.ID}); err != nil {
|
||||
if err := fs.Delete(ctx, []uint{}, []uint{file.ID}, false); err != nil {
|
||||
return http.StatusMethodNotAllowed, err
|
||||
}
|
||||
return http.StatusNoContent, nil
|
||||
@@ -289,7 +289,7 @@ func (h *Handler) handleDelete(w http.ResponseWriter, r *http.Request, fs *files
|
||||
|
||||
// 尝试作为目录删除
|
||||
if ok, folder := fs.IsPathExist(reqPath); ok {
|
||||
if err := fs.Delete(ctx, []uint{folder.ID}, []uint{}); err != nil {
|
||||
if err := fs.Delete(ctx, []uint{folder.ID}, []uint{}, false); err != nil {
|
||||
return http.StatusMethodNotAllowed, err
|
||||
}
|
||||
return http.StatusNoContent, nil
|
||||
@@ -400,6 +400,11 @@ func (h *Handler) handleMkcol(w http.ResponseWriter, r *http.Request, fs *filesy
|
||||
if r.ContentLength > 0 {
|
||||
return http.StatusUnsupportedMediaType, nil
|
||||
}
|
||||
if strings.Contains(r.UserAgent(), "rclone") {
|
||||
if _, ok := ctx.Value(fsctx.IgnoreConflictCtx).(bool); !ok {
|
||||
ctx = context.WithValue(ctx, fsctx.IgnoreConflictCtx, true)
|
||||
}
|
||||
}
|
||||
if _, err := fs.CreateDirectory(ctx, reqPath); err != nil {
|
||||
return http.StatusConflict, err
|
||||
}
|
||||
|
||||
@@ -314,7 +314,7 @@ func AdminGetFile(c *gin.Context) {
|
||||
res := service.Get(c)
|
||||
// 是否需要重定向
|
||||
if res.Code == -301 {
|
||||
c.Redirect(301, res.Data.(string))
|
||||
c.Redirect(302, res.Data.(string))
|
||||
return
|
||||
}
|
||||
// 是否有错误发生
|
||||
@@ -402,3 +402,25 @@ func AdminDeleteTask(c *gin.Context) {
|
||||
c.JSON(200, ErrorResponse(err))
|
||||
}
|
||||
}
|
||||
|
||||
// AdminCreateImportTask 新建文件导入任务
|
||||
func AdminCreateImportTask(c *gin.Context) {
|
||||
var service admin.ImportTaskService
|
||||
if err := c.ShouldBindJSON(&service); err == nil {
|
||||
res := service.Create(c, CurrentUser(c))
|
||||
c.JSON(200, res)
|
||||
} else {
|
||||
c.JSON(200, ErrorResponse(err))
|
||||
}
|
||||
}
|
||||
|
||||
// AdminListFolders 列出用户或外部文件系统目录
|
||||
func AdminListFolders(c *gin.Context) {
|
||||
var service admin.ListFolderService
|
||||
if err := c.ShouldBindUri(&service); err == nil {
|
||||
res := service.List(c)
|
||||
c.JSON(200, res)
|
||||
} else {
|
||||
c.JSON(200, ErrorResponse(err))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -353,3 +353,14 @@ func SearchFile(c *gin.Context) {
|
||||
c.JSON(200, ErrorResponse(err))
|
||||
}
|
||||
}
|
||||
|
||||
// CreateFile 创建空白文件
|
||||
func CreateFile(c *gin.Context) {
|
||||
var service explorer.SingleFileService
|
||||
if err := c.ShouldBindJSON(&service); err == nil {
|
||||
res := service.Create(c)
|
||||
c.JSON(200, res)
|
||||
} else {
|
||||
c.JSON(200, ErrorResponse(err))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
func SiteConfig(c *gin.Context) {
|
||||
siteConfig := model.GetSettingByNames(
|
||||
"siteName",
|
||||
"siteICPId",
|
||||
"login_captcha",
|
||||
"reg_captcha",
|
||||
"email_active",
|
||||
@@ -23,6 +24,8 @@ func SiteConfig(c *gin.Context) {
|
||||
"home_view_method",
|
||||
"share_view_method",
|
||||
"authn_enabled",
|
||||
"captcha_IsUseReCaptcha",
|
||||
"captcha_ReCaptchaKey",
|
||||
)
|
||||
|
||||
// 如果已登录,则同时返回用户信息和标签
|
||||
|
||||
@@ -158,3 +158,14 @@ func SlavePing(c *gin.Context) {
|
||||
c.JSON(200, ErrorResponse(err))
|
||||
}
|
||||
}
|
||||
|
||||
// SlaveList 从机列出文件
|
||||
func SlaveList(c *gin.Context) {
|
||||
var service explorer.SlaveListService
|
||||
if err := c.ShouldBindJSON(&service); err == nil {
|
||||
res := service.List(c)
|
||||
c.JSON(200, res)
|
||||
} else {
|
||||
c.JSON(200, ErrorResponse(err))
|
||||
}
|
||||
}
|
||||
|
||||
+16
-3
@@ -8,6 +8,7 @@ import (
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/HFO4/cloudreve/routers/controllers"
|
||||
"github.com/gin-contrib/cors"
|
||||
"github.com/gin-contrib/gzip"
|
||||
"github.com/gin-contrib/static"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
@@ -48,6 +49,8 @@ func InitSlaveRouter() *gin.Engine {
|
||||
v3.GET("thumb/:path", controllers.SlaveThumb)
|
||||
// 删除文件
|
||||
v3.POST("delete", controllers.SlaveDelete)
|
||||
// 列出文件
|
||||
v3.POST("list", controllers.SlaveList)
|
||||
}
|
||||
return r
|
||||
}
|
||||
@@ -78,6 +81,8 @@ func InitMasterRouter() *gin.Engine {
|
||||
/*
|
||||
静态资源
|
||||
*/
|
||||
r.Use(gzip.Gzip(gzip.DefaultCompression, gzip.WithExcludedPaths([]string{"/api/"})))
|
||||
r.Use(middleware.InjectSiteInfo())
|
||||
r.Use(static.Serve("/", bootstrap.StaticFS))
|
||||
r.GET("manifest.json", controllers.Manifest)
|
||||
|
||||
@@ -107,7 +112,7 @@ func InitMasterRouter() *gin.Engine {
|
||||
// 验证码
|
||||
site.GET("captcha", controllers.Captcha)
|
||||
// 站点全局配置
|
||||
site.GET("config", controllers.SiteConfig)
|
||||
site.GET("config", middleware.CSRFInit(), controllers.SiteConfig)
|
||||
}
|
||||
|
||||
// 用户相关路由
|
||||
@@ -231,6 +236,7 @@ func InitMasterRouter() *gin.Engine {
|
||||
)
|
||||
// 预览分享文件
|
||||
share.GET("preview/:id",
|
||||
middleware.CSRFCheck(),
|
||||
middleware.CheckShareUnlocked(),
|
||||
middleware.ShareCanPreview(),
|
||||
middleware.BeforeShareDownload(),
|
||||
@@ -271,6 +277,8 @@ func InitMasterRouter() *gin.Engine {
|
||||
middleware.ShareCanPreview(),
|
||||
controllers.ShareThumb,
|
||||
)
|
||||
// 搜索公共分享
|
||||
v3.Group("share").GET("search", controllers.SearchShare)
|
||||
}
|
||||
|
||||
// 需要登录保护的
|
||||
@@ -360,6 +368,9 @@ func InitMasterRouter() *gin.Engine {
|
||||
file.GET("preview/:id", controllers.AdminGetFile)
|
||||
// 删除
|
||||
file.POST("delete", controllers.AdminDeleteFile)
|
||||
// 列出用户或外部文件系统目录
|
||||
file.GET("folders/:type/:id/*path",
|
||||
controllers.AdminListFolders)
|
||||
}
|
||||
|
||||
share := admin.Group("share")
|
||||
@@ -384,6 +395,8 @@ func InitMasterRouter() *gin.Engine {
|
||||
task.POST("list", controllers.AdminListTask)
|
||||
// 删除
|
||||
task.POST("delete", controllers.AdminDeleteTask)
|
||||
// 新建文件导入任务
|
||||
task.POST("import", controllers.AdminCreateImportTask)
|
||||
}
|
||||
|
||||
}
|
||||
@@ -433,6 +446,8 @@ func InitMasterRouter() *gin.Engine {
|
||||
file.GET("upload/credential", controllers.GetUploadCredential)
|
||||
// 更新文件
|
||||
file.PUT("update/:id", controllers.PutContent)
|
||||
// 创建空白文件
|
||||
file.POST("create", controllers.CreateFile)
|
||||
// 创建文件下载会话
|
||||
file.PUT("download/:id", controllers.CreateDownloadSession)
|
||||
// 预览文件
|
||||
@@ -501,8 +516,6 @@ func InitMasterRouter() *gin.Engine {
|
||||
share.POST("", controllers.CreateShare)
|
||||
// 列出我的分享
|
||||
share.GET("", controllers.ListShare)
|
||||
// 搜索公共分享
|
||||
share.GET("search", controllers.SearchShare)
|
||||
// 更新分享属性
|
||||
share.PATCH(":id",
|
||||
middleware.ShareAvailable(),
|
||||
|
||||
+68
-2
@@ -18,7 +18,73 @@ type FileService struct {
|
||||
|
||||
// FileBatchService 文件批量操作服务
|
||||
type FileBatchService struct {
|
||||
ID []uint `json:"id" binding:"min=1"`
|
||||
ID []uint `json:"id" binding:"min=1"`
|
||||
Force bool `json:"force"`
|
||||
}
|
||||
|
||||
// ListFolderService 列目录结构
|
||||
type ListFolderService struct {
|
||||
Path string `uri:"path" binding:"required,max=65535"`
|
||||
ID uint `uri:"id" binding:"required"`
|
||||
Type string `uri:"type" binding:"eq=policy|eq=user"`
|
||||
}
|
||||
|
||||
// List 列出指定路径下的目录
|
||||
func (service *ListFolderService) List(c *gin.Context) serializer.Response {
|
||||
if service.Type == "policy" {
|
||||
// 列取存储策略中的目录
|
||||
policy, err := model.GetPolicyByID(service.ID)
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeNotFound, "存储策略不存在", err)
|
||||
}
|
||||
|
||||
// 创建文件系统
|
||||
fs, err := filesystem.NewAnonymousFileSystem()
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeInternalSetting, "无法创建文件系统", err)
|
||||
}
|
||||
defer fs.Recycle()
|
||||
|
||||
// 列取存储策略中的文件
|
||||
fs.Policy = &policy
|
||||
res, err := fs.ListPhysical(c.Request.Context(), service.Path)
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeIOFailed, "无法列取目录", err)
|
||||
}
|
||||
|
||||
return serializer.Response{
|
||||
Data: map[string]interface{}{
|
||||
"objects": res,
|
||||
},
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// 列取用户空间目录
|
||||
// 查找用户
|
||||
user, err := model.GetUserByID(service.ID)
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeNotFound, "用户不存在", err)
|
||||
}
|
||||
|
||||
// 创建文件系统
|
||||
fs, err := filesystem.NewFileSystem(&user)
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeInternalSetting, "无法创建文件系统", err)
|
||||
}
|
||||
defer fs.Recycle()
|
||||
|
||||
// 列取目录
|
||||
res, err := fs.List(c.Request.Context(), service.Path, nil)
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeIOFailed, "无法列取目录", err)
|
||||
}
|
||||
|
||||
return serializer.Response{
|
||||
Data: map[string]interface{}{
|
||||
"objects": res,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// Delete 删除文件
|
||||
@@ -58,7 +124,7 @@ func (service *FileBatchService) Delete(c *gin.Context) serializer.Response {
|
||||
}
|
||||
|
||||
// 执行删除
|
||||
fs.Delete(context.Background(), []uint{}, ids)
|
||||
fs.Delete(context.Background(), []uint{}, ids, service.Force)
|
||||
fs.Recycle()
|
||||
}
|
||||
}(userFile)
|
||||
|
||||
@@ -54,6 +54,11 @@ type PolicyService struct {
|
||||
|
||||
// Delete 删除存储策略
|
||||
func (service *PolicyService) Delete() serializer.Response {
|
||||
// 禁止删除默认策略
|
||||
if service.ID == 1 {
|
||||
return serializer.Err(serializer.CodeNoPermissionErr, "默认存储策略无法删除", nil)
|
||||
}
|
||||
|
||||
policy, err := model.GetPolicyByID(service.ID)
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeNotFound, "存储策略不存在", err)
|
||||
@@ -239,7 +244,9 @@ func (service *SlaveTestService) Test() serializer.Response {
|
||||
|
||||
// Add 添加存储策略
|
||||
func (service *AddPolicyService) Add() serializer.Response {
|
||||
service.Policy.DirNameRule = strings.TrimPrefix(service.Policy.DirNameRule, "/")
|
||||
if service.Policy.Type != "local" && service.Policy.Type != "remote" {
|
||||
service.Policy.DirNameRule = strings.TrimPrefix(service.Policy.DirNameRule, "/")
|
||||
}
|
||||
|
||||
if service.Policy.ID > 0 {
|
||||
if err := model.DB.Save(&service.Policy).Error; err != nil {
|
||||
|
||||
@@ -3,6 +3,7 @@ package admin
|
||||
import (
|
||||
model "github.com/HFO4/cloudreve/models"
|
||||
"github.com/HFO4/cloudreve/pkg/serializer"
|
||||
"github.com/HFO4/cloudreve/pkg/task"
|
||||
"github.com/gin-gonic/gin"
|
||||
"strings"
|
||||
)
|
||||
@@ -12,6 +13,26 @@ type TaskBatchService struct {
|
||||
ID []uint `json:"id" binding:"min=1"`
|
||||
}
|
||||
|
||||
// ImportTaskService 导入任务
|
||||
type ImportTaskService struct {
|
||||
UID uint `json:"uid" binding:"required"`
|
||||
PolicyID uint `json:"policy_id" binding:"required"`
|
||||
Src string `json:"src" binding:"required,min=1,max=65535"`
|
||||
Dst string `json:"dst" binding:"required,min=1,max=65535"`
|
||||
Recursive bool `json:"recursive"`
|
||||
}
|
||||
|
||||
// Create 新建导入任务
|
||||
func (service *ImportTaskService) Create(c *gin.Context, user *model.User) serializer.Response {
|
||||
// 创建任务
|
||||
job, err := task.NewImportTask(service.UID, service.PolicyID, service.Src, service.Dst, service.Recursive)
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeNotSet, "任务创建失败", err)
|
||||
}
|
||||
task.TaskPoll.Submit(job)
|
||||
return serializer.Response{}
|
||||
}
|
||||
|
||||
// Delete 删除任务
|
||||
func (service *TaskBatchService) Delete(c *gin.Context) serializer.Response {
|
||||
if err := model.DB.Where("id in (?)", service.ID).Delete(&model.Download{}).Error; err != nil {
|
||||
|
||||
@@ -65,7 +65,7 @@ func (service *UserBatchService) Delete() serializer.Response {
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeNotFound, "无法找到用户根目录", err)
|
||||
}
|
||||
fs.Delete(context.Background(), []uint{root.ID}, []uint{})
|
||||
fs.Delete(context.Background(), []uint{root.ID}, []uint{}, false)
|
||||
|
||||
// 删除相关任务
|
||||
model.DB.Where("user_id = ?", uid).Delete(&model.Download{})
|
||||
|
||||
@@ -23,7 +23,11 @@ func (service *OneDriveOauthService) Auth(c *gin.Context) serializer.Response {
|
||||
return serializer.ParamErr(service.ErrorMsg, nil)
|
||||
}
|
||||
|
||||
policyID := util.GetSession(c, "onedrive_oauth_policy").(uint)
|
||||
policyID, ok := util.GetSession(c, "onedrive_oauth_policy").(uint)
|
||||
if !ok {
|
||||
return serializer.Err(serializer.CodeNotFound, "授权会话不存在,请重试", nil)
|
||||
}
|
||||
|
||||
util.DeleteSession(c, "onedrive_oauth_policy")
|
||||
|
||||
policy, err := model.GetPolicyByID(policyID)
|
||||
|
||||
@@ -13,15 +13,18 @@ import (
|
||||
"github.com/HFO4/cloudreve/pkg/serializer"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/jinzhu/gorm"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// SingleFileService 对单文件进行操作的五福,path为文件完整路径
|
||||
type SingleFileService struct {
|
||||
Path string `uri:"path" binding:"required,min=1,max=65535"`
|
||||
Path string `uri:"path" json:"path" binding:"required,min=1,max=65535"`
|
||||
}
|
||||
|
||||
// FileIDService 通过文件ID对文件进行操作的服务
|
||||
@@ -56,6 +59,63 @@ type SlaveFilesService struct {
|
||||
Files []string `json:"files" binding:"required,gt=0"`
|
||||
}
|
||||
|
||||
// SlaveListService 从机列表服务
|
||||
type SlaveListService struct {
|
||||
Path string `json:"path" binding:"required,min=1,max=65535"`
|
||||
Recursive bool `json:"recursive"`
|
||||
}
|
||||
|
||||
// New 创建新文件
|
||||
func (service *SingleFileService) Create(c *gin.Context) serializer.Response {
|
||||
// 创建文件系统
|
||||
fs, err := filesystem.NewFileSystemFromContext(c)
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodePolicyNotAllowed, err.Error(), err)
|
||||
}
|
||||
defer fs.Recycle()
|
||||
|
||||
// 上下文
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
// 给文件系统分配钩子
|
||||
fs.Use("BeforeUpload", filesystem.HookValidateFile)
|
||||
fs.Use("AfterUpload", filesystem.GenericAfterUpload)
|
||||
|
||||
// 上传空文件
|
||||
err = fs.Upload(ctx, local.FileStream{
|
||||
File: ioutil.NopCloser(strings.NewReader("")),
|
||||
Size: 0,
|
||||
VirtualPath: path.Dir(service.Path),
|
||||
Name: path.Base(service.Path),
|
||||
})
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeUploadFailed, err.Error(), err)
|
||||
}
|
||||
|
||||
return serializer.Response{
|
||||
Code: 0,
|
||||
}
|
||||
}
|
||||
|
||||
// List 列出从机上的文件
|
||||
func (service *SlaveListService) List(c *gin.Context) serializer.Response {
|
||||
// 创建文件系统
|
||||
fs, err := filesystem.NewAnonymousFileSystem()
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodePolicyNotAllowed, err.Error(), err)
|
||||
}
|
||||
defer fs.Recycle()
|
||||
|
||||
objects, err := fs.Handler.List(context.Background(), service.Path, service.Recursive)
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeIOFailed, "无法列取文件", err)
|
||||
}
|
||||
|
||||
res, _ := json.Marshal(objects)
|
||||
return serializer.Response{Data: string(res)}
|
||||
}
|
||||
|
||||
// DownloadArchived 下載已打包的多文件
|
||||
func (service *DownloadService) DownloadArchived(ctx context.Context, c *gin.Context) serializer.Response {
|
||||
// 创建文件系统
|
||||
|
||||
@@ -146,6 +146,11 @@ func (service *ItemCompressService) CreateCompressTask(c *gin.Context) serialize
|
||||
return serializer.Err(serializer.CodeGroupNotAllowed, "当前用户组无法进行此操作", nil)
|
||||
}
|
||||
|
||||
// 补齐压缩文件扩展名(如果没有)
|
||||
if !strings.HasSuffix(service.Name, ".zip") {
|
||||
service.Name += ".zip"
|
||||
}
|
||||
|
||||
// 存放目录是否存在,是否重名
|
||||
if exist, _ := fs.IsPathExist(service.Dst); !exist {
|
||||
return serializer.Err(serializer.CodeNotFound, "存放路径不存在", nil)
|
||||
@@ -264,7 +269,7 @@ func (service *ItemIDService) Delete(ctx context.Context, c *gin.Context) serial
|
||||
|
||||
// 删除对象
|
||||
items := service.Raw()
|
||||
err = fs.Delete(ctx, items.Dirs, items.Items)
|
||||
err = fs.Delete(ctx, items.Dirs, items.Items, false)
|
||||
if err != nil {
|
||||
return serializer.Err(serializer.CodeNotSet, err.Error(), err)
|
||||
}
|
||||
|
||||
+29
-2
@@ -6,6 +6,7 @@ import (
|
||||
"github.com/HFO4/cloudreve/pkg/cache"
|
||||
"github.com/HFO4/cloudreve/pkg/email"
|
||||
"github.com/HFO4/cloudreve/pkg/hashid"
|
||||
"github.com/HFO4/cloudreve/pkg/recaptcha"
|
||||
"github.com/HFO4/cloudreve/pkg/serializer"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -13,6 +14,7 @@ import (
|
||||
"github.com/pquerna/otp/totp"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// UserLoginService 管理用户登录的服务
|
||||
@@ -69,12 +71,24 @@ func (service *UserResetService) Reset(c *gin.Context) serializer.Response {
|
||||
func (service *UserResetEmailService) Reset(c *gin.Context) serializer.Response {
|
||||
// 检查验证码
|
||||
isCaptchaRequired := model.IsTrueVal(model.GetSettingByName("forget_captcha"))
|
||||
if isCaptchaRequired {
|
||||
useRecaptcha := model.IsTrueVal(model.GetSettingByName("captcha_IsUseReCaptcha"))
|
||||
recaptchaSecret := model.GetSettingByName("captcha_ReCaptchaSecret")
|
||||
if isCaptchaRequired && !useRecaptcha {
|
||||
captchaID := util.GetSession(c, "captchaID")
|
||||
util.DeleteSession(c, "captchaID")
|
||||
if captchaID == nil || !base64Captcha.VerifyCaptcha(captchaID.(string), service.CaptchaCode) {
|
||||
return serializer.ParamErr("验证码错误", nil)
|
||||
}
|
||||
} else if isCaptchaRequired && useRecaptcha {
|
||||
captcha, err := recaptcha.NewReCAPTCHA(recaptchaSecret, recaptcha.V2, 10*time.Second)
|
||||
if err != nil {
|
||||
util.Log().Error(err.Error())
|
||||
}
|
||||
err = captcha.Verify(service.CaptchaCode)
|
||||
if err != nil {
|
||||
util.Log().Error(err.Error())
|
||||
return serializer.ParamErr("验证失败,请刷新网页后再次验证", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// 查找用户
|
||||
@@ -132,14 +146,27 @@ func (service *Enable2FA) Login(c *gin.Context) serializer.Response {
|
||||
// Login 用户登录函数
|
||||
func (service *UserLoginService) Login(c *gin.Context) serializer.Response {
|
||||
isCaptchaRequired := model.GetSettingByName("login_captcha")
|
||||
useRecaptcha := model.GetSettingByName("captcha_IsUseReCaptcha")
|
||||
recaptchaSecret := model.GetSettingByName("captcha_ReCaptchaSecret")
|
||||
expectedUser, err := model.GetUserByEmail(service.UserName)
|
||||
|
||||
if model.IsTrueVal(isCaptchaRequired) {
|
||||
if (model.IsTrueVal(isCaptchaRequired)) && !(model.IsTrueVal(useRecaptcha)) {
|
||||
// TODO 验证码校验
|
||||
captchaID := util.GetSession(c, "captchaID")
|
||||
util.DeleteSession(c, "captchaID")
|
||||
if captchaID == nil || !base64Captcha.VerifyCaptcha(captchaID.(string), service.CaptchaCode) {
|
||||
return serializer.ParamErr("验证码错误", nil)
|
||||
}
|
||||
} else if (model.IsTrueVal(isCaptchaRequired)) && (model.IsTrueVal(useRecaptcha)) {
|
||||
captcha, err := recaptcha.NewReCAPTCHA(recaptchaSecret, recaptcha.V2, 10*time.Second)
|
||||
if err != nil {
|
||||
util.Log().Error(err.Error())
|
||||
}
|
||||
err = captcha.Verify(service.CaptchaCode)
|
||||
if err != nil {
|
||||
util.Log().Error(err.Error())
|
||||
return serializer.ParamErr("验证失败,请刷新网页后再次验证", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// 一系列校验
|
||||
|
||||
@@ -5,12 +5,14 @@ import (
|
||||
"github.com/HFO4/cloudreve/pkg/auth"
|
||||
"github.com/HFO4/cloudreve/pkg/email"
|
||||
"github.com/HFO4/cloudreve/pkg/hashid"
|
||||
"github.com/HFO4/cloudreve/pkg/recaptcha"
|
||||
"github.com/HFO4/cloudreve/pkg/serializer"
|
||||
"github.com/HFO4/cloudreve/pkg/util"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/mojocn/base64Captcha"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// UserRegisterService 管理用户注册的服务
|
||||
@@ -27,12 +29,24 @@ func (service *UserRegisterService) Register(c *gin.Context) serializer.Response
|
||||
options := model.GetSettingByNames("email_active", "reg_captcha")
|
||||
// 检查验证码
|
||||
isCaptchaRequired := model.IsTrueVal(options["reg_captcha"])
|
||||
if isCaptchaRequired {
|
||||
useRecaptcha := model.IsTrueVal(model.GetSettingByName("captcha_IsUseReCaptcha"))
|
||||
recaptchaSecret := model.GetSettingByName("captcha_ReCaptchaSecret")
|
||||
if isCaptchaRequired && !useRecaptcha {
|
||||
captchaID := util.GetSession(c, "captchaID")
|
||||
util.DeleteSession(c, "captchaID")
|
||||
if captchaID == nil || !base64Captcha.VerifyCaptcha(captchaID.(string), service.CaptchaCode) {
|
||||
return serializer.ParamErr("验证码错误", nil)
|
||||
}
|
||||
} else if isCaptchaRequired && useRecaptcha {
|
||||
captcha, err := recaptcha.NewReCAPTCHA(recaptchaSecret, recaptcha.V2, 10*time.Second)
|
||||
if err != nil {
|
||||
util.Log().Error(err.Error())
|
||||
}
|
||||
err = captcha.Verify(service.CaptchaCode)
|
||||
if err != nil {
|
||||
util.Log().Error(err.Error())
|
||||
return serializer.ParamErr("验证失败,请刷新网页后再次验证", nil)
|
||||
}
|
||||
}
|
||||
|
||||
// 相关设定
|
||||
|
||||
Reference in New Issue
Block a user