Compare commits
251 Commits
Author | SHA1 | Date | |
---|---|---|---|
c35d54d092 | |||
323dad2a1c | |||
62aefc4f68 | |||
6a7eb8b3eb | |||
eb549f2631 | |||
9207eb69ee | |||
866df0540b | |||
04e04a1aa6 | |||
6a66e39d5b | |||
f2b2728be7 | |||
39b8f28fc4 | |||
e1ccc0b215 | |||
87e339850d | |||
79c9b6ac77 | |||
aeb2297f1f | |||
3b59bb5c09 | |||
bc4bac921f | |||
f917882a84 | |||
6a67d1cf69 | |||
041b3587bf | |||
0eef7a129c | |||
4b635f06e3 | |||
279111a8e2 | |||
67674835da | |||
732e9eb1c3 | |||
b6af9aa587 | |||
a9027c0f06 | |||
d780fa18a5 | |||
d5626d6e2f | |||
52dcbfe1a4 | |||
bf0ee3d315 | |||
0237e78c1e | |||
44b8c6abf7 | |||
33e1acd344 | |||
c54cb61f14 | |||
734b204709 | |||
b7d9c5e4ff | |||
e698b457b9 | |||
5258c21656 | |||
1ca9a3d14e | |||
f23bec9a35 | |||
62a1acd1f4 | |||
fa6e3fe567 | |||
b71b62ee35 | |||
410b4939a4 | |||
62c0071f29 | |||
f043a41005 | |||
2e9da57036 | |||
d83cd37984 | |||
bad8b0ebbb | |||
4535e65948 | |||
3b413c2ee2 | |||
427ae56333 | |||
658fd5ad6e | |||
11830bb51c | |||
75c98429bf | |||
f77ea1b3a5 | |||
0a8bd96d33 | |||
68f37fc11f | |||
d6775cda69 | |||
43c6e07bac | |||
4901e9080c | |||
48049a5ea3 | |||
bd7260f0ff | |||
6c0d54394f | |||
ce5dacbf3f | |||
08aaa5e2c0 | |||
42c0e438d5 | |||
e4df146043 | |||
27b7dae113 | |||
293d574ce7 | |||
56b3b35556 | |||
a7a0e85a46 | |||
95c0106fdd | |||
6612338fc1 | |||
c276a1541f | |||
cc96a5bbdb | |||
0810561a8a | |||
82a5c43b94 | |||
d38f36ef44 | |||
f9533440c7 | |||
41a186b051 | |||
4e6a44253c | |||
ebda77cd43 | |||
1a1e86521f | |||
1b4740dae3 | |||
91fc8df84e | |||
e6ecf1fa30 | |||
183a6f1b3a | |||
3c2d59e272 | |||
fd80e3eaf7 | |||
4928c331a8 | |||
3ad75e54cb | |||
a2cf3ab42e | |||
e24814ee2f | |||
37b42e6e17 | |||
30ebb0f4d4 | |||
8e059c64b5 | |||
395de069c2 | |||
4c22f37d54 | |||
a73a40133d | |||
6591af58ea | |||
58568d4ef6 | |||
5295593bf8 | |||
24d031d578 | |||
7141bf0358 | |||
c5d707cf0a | |||
dfcf66b43e | |||
fa6ee62cf0 | |||
1428d90361 | |||
c413c22201 | |||
9b6adecd62 | |||
b3540cf539 | |||
f8650c9c0b | |||
bf2e5768d6 | |||
18c82e79b5 | |||
d69d24a5b2 | |||
342729179d | |||
0537449335 | |||
df90311453 | |||
876579ea3b | |||
e83081380e | |||
9daeaf7562 | |||
e6be11c17f | |||
b52e1e8be3 | |||
948bbe9136 | |||
ced61da33a | |||
a0f4383d41 | |||
5a527dfa2c | |||
49fc475f9f | |||
83c377270e | |||
7ffaef0de6 | |||
dd151480a8 | |||
ad3121d367 | |||
c1525ebc69 | |||
30277cd81f | |||
466ec27ffe | |||
85c757b035 | |||
712687370a | |||
b68ba22df3 | |||
d9652e2a0b | |||
a5b757b251 | |||
0bc05a60b0 | |||
db275f885a | |||
9e483d902f | |||
801f843f8a | |||
77ffb93cbe | |||
bf73ea7f5d | |||
9b23d0ab29 | |||
908cdd2c78 | |||
f4f61a5787 | |||
6db09a2736 | |||
b21801d505 | |||
2dbedc245c | |||
58426613f6 | |||
ef19e851e3 | |||
5a1b16a601 | |||
4eef9cd9bc | |||
79b5c018ea | |||
15651a4356 | |||
7be476cce0 | |||
bb017c5f6d | |||
c51dc4594d | |||
8e30b02efc | |||
0aa438dce4 | |||
9c2fc8e860 | |||
b1d7a980d9 | |||
19d0a88b55 | |||
40567dee0e | |||
4b540a2297 | |||
8a62d55efe | |||
10fce6c0fe | |||
d31d49a9bb | |||
2e91f5ffa5 | |||
8f19c45a81 | |||
c63e05983d | |||
678a982535 | |||
b2c02e6c5e | |||
7e05b0317f | |||
19f06dfaed | |||
1680a18578 | |||
e8f440ca5c | |||
7deff76f49 | |||
cd0afb9536 | |||
668a953cd8 | |||
8bfbaa74f6 | |||
3ccf5ee620 | |||
b44243c021 | |||
4ae81b5a79 | |||
189f4c19a5 | |||
92a3d74af5 | |||
bb73a10332 | |||
3baf1e8c7b | |||
fdb49f5fb4 | |||
2eedcc1626 | |||
6faecbd5d8 | |||
34ed05c62f | |||
ce83d6eb40 | |||
2271cb6c7c | |||
a42b30c96e | |||
ce25d16222 | |||
b392e093e3 | |||
0d5b7298db | |||
2063ebb74d | |||
0408d7ab5d | |||
d52451f9d2 | |||
ca9f77006a | |||
e8e8d925f3 | |||
623aab4c28 | |||
3bc81d471e | |||
dfddb5cfa1 | |||
80f5bde0cb | |||
9de072161e | |||
d08a7440bc | |||
7a4bb2496d | |||
f68ab40d26 | |||
796d490fb7 | |||
2964d5a6db | |||
90b57dacee | |||
6af17e2509 | |||
5193b2aa7d | |||
3f644f07db | |||
d988f98b81 | |||
10634c7b77 | |||
135d505192 | |||
3f2be8a6ca | |||
79bef09ee7 | |||
3534f6afac | |||
106c1d069c | |||
8ed0afe80d | |||
6a6e3944d5 | |||
94d5b5e47e | |||
e61b0f8e34 | |||
f7fbe1de6c | |||
01de01630e | |||
f9f92e2198 | |||
7d5f50b04a | |||
72b5d25e4c | |||
cae7f36531 | |||
aa79f49e25 | |||
b4ad301d53 | |||
00ed54c4c9 | |||
ffa52794db | |||
24058d0c36 | |||
641ca67671 | |||
52ee2e0a8b | |||
724fc7f37e | |||
9d279b104b | |||
eb61f70164 | |||
b3a8201768 | |||
185795954b |
89
.all-contributorsrc
Normal file
89
.all-contributorsrc
Normal file
@ -0,0 +1,89 @@
|
||||
{
|
||||
"files": [
|
||||
"CONTRIBUTORS.md"
|
||||
],
|
||||
"imageSize": 100,
|
||||
"commit": false,
|
||||
"contributors": [
|
||||
{
|
||||
"login": "Xhofe",
|
||||
"name": "Xhofe",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/36558727?v=4",
|
||||
"profile": "http://nn.ci",
|
||||
"contributions": [
|
||||
"code",
|
||||
"ideas",
|
||||
"doc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "foxxorcat",
|
||||
"name": "foxxorcat",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/95907542?v=4",
|
||||
"profile": "https://github.com/foxxorcat",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "DaoChen6",
|
||||
"name": "道辰",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/63903027?v=4",
|
||||
"profile": "https://www.iflu.cf/",
|
||||
"contributions": [
|
||||
"doc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "vg-land",
|
||||
"name": "vg-land",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/16739728?v=4",
|
||||
"profile": "https://vg-land.github.io/",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "Clansty",
|
||||
"name": "凌莞~(=^▽^=)",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/18461360?v=4",
|
||||
"profile": "https://c5y.moe",
|
||||
"contributions": [
|
||||
"doc"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "Windman1320",
|
||||
"name": "Windman",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/9999486?v=4",
|
||||
"profile": "https://github.com/Windman1320",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "ericarena",
|
||||
"name": "ericarena",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/4518927?v=4",
|
||||
"profile": "https://github.com/ericarena",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
},
|
||||
{
|
||||
"login": "WntFlm",
|
||||
"name": "WntFlm",
|
||||
"avatar_url": "https://avatars.githubusercontent.com/u/34620278?v=4",
|
||||
"profile": "https://github.com/WntFlm",
|
||||
"contributions": [
|
||||
"code"
|
||||
]
|
||||
}
|
||||
],
|
||||
"contributorsPerLine": 7,
|
||||
"projectName": "alist",
|
||||
"projectOwner": "Xhofe",
|
||||
"repoType": "github",
|
||||
"repoHost": "https://github.com",
|
||||
"skipCi": true
|
||||
}
|
15
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
15
.github/ISSUE_TEMPLATE/bug_report.yml
vendored
@ -5,7 +5,16 @@ body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thanks for taking the time to fill out this bug report, please confirm that your issue is not a duplicate issue
|
||||
Thanks for taking the time to fill out this bug report, please **confirm that your issue is not a duplicate issue and not because of your operation or version issues**
|
||||
感谢您花时间填写此错误报告,请**务必确认您的issue不是重复的且不是因为您的操作或版本问题**
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Please make sure of the following things
|
||||
description: You may select more than one, even select all.
|
||||
options:
|
||||
- label: I have read the [documentation](https://alist-doc.nn.ci).
|
||||
- label: I'm sure there are no duplicate issues or discussions.
|
||||
- label: I'm sure it's due to `alist` and not something else(such as `Dependencies` or `Operational`).
|
||||
- type: input
|
||||
id: version
|
||||
attributes:
|
||||
@ -28,11 +37,11 @@ body:
|
||||
Please provide a link to a repo that can reproduce the problem you ran into.
|
||||
请提供能复现此问题的链接
|
||||
validations:
|
||||
required: false
|
||||
required: true
|
||||
- type: textarea
|
||||
id: logs
|
||||
attributes:
|
||||
label: 日志 / Logs
|
||||
label: Logs / 日志
|
||||
description: |
|
||||
Please copy and paste any relevant log output.
|
||||
请复制粘贴错误日志,或者截图
|
||||
|
9
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
9
.github/ISSUE_TEMPLATE/feature_request.yml
vendored
@ -2,6 +2,15 @@ name: "Feature request"
|
||||
description: Feature request
|
||||
labels: ["enhancement: pending triage"]
|
||||
body:
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Please make sure of the following things
|
||||
description: You may select more than one, even select all.
|
||||
options:
|
||||
- label: I have read the [documentation](https://alist-doc.nn.ci).
|
||||
- label: I'm sure there are no duplicate issues or discussions.
|
||||
- label: I'm sure this feature is not implemented.
|
||||
- label: I'm sure it's a reasonable and popular requirement.
|
||||
- type: textarea
|
||||
id: feature-description
|
||||
attributes:
|
||||
|
21
.github/config.yml
vendored
Normal file
21
.github/config.yml
vendored
Normal file
@ -0,0 +1,21 @@
|
||||
# Configuration for welcome - https://github.com/behaviorbot/welcome
|
||||
|
||||
# Configuration for new-issue-welcome - https://github.com/behaviorbot/new-issue-welcome
|
||||
|
||||
# Comment to be posted to on first time issues
|
||||
newIssueWelcomeComment: >
|
||||
Thanks for opening your first issue here! Be sure to follow the issue template!
|
||||
|
||||
# Configuration for new-pr-welcome - https://github.com/behaviorbot/new-pr-welcome
|
||||
|
||||
# Comment to be posted to on PRs from first time contributors in your repository
|
||||
newPRWelcomeComment: >
|
||||
Thanks for opening this pull request! Please check out our contributing guidelines.
|
||||
|
||||
# Configuration for first-pr-merge - https://github.com/behaviorbot/first-pr-merge
|
||||
|
||||
# Comment to be posted to on pull requests merged by a first time user
|
||||
firstPRMergeComment: >
|
||||
Congrats on merging your first pull request! We here at behavior bot are proud of you!
|
||||
|
||||
# It is recommend to include as many gifs and emojis as possible
|
9
.github/workflows/build.yml
vendored
9
.github/workflows/build.yml
vendored
@ -2,16 +2,16 @@ name: build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ v2 ]
|
||||
branches: [ '**' ]
|
||||
pull_request:
|
||||
branches: [ v2 ]
|
||||
branches: [ '**' ]
|
||||
|
||||
jobs:
|
||||
build:
|
||||
strategy:
|
||||
matrix:
|
||||
platform: [ubuntu-latest]
|
||||
go-version: [1.17]
|
||||
go-version: [1.18]
|
||||
name: Build
|
||||
runs-on: ${{ matrix.platform }}
|
||||
steps:
|
||||
@ -28,10 +28,9 @@ jobs:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
ref: v2
|
||||
path: alist
|
||||
|
||||
- name: Set up xgo
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
docker pull techknowlogick/xgo:latest
|
||||
go install src.techknowlogick.com/xgo@latest
|
||||
|
2
.github/workflows/build_docker.yml
vendored
2
.github/workflows/build_docker.yml
vendored
@ -3,8 +3,6 @@ name: build_docker
|
||||
on:
|
||||
push:
|
||||
branches: [ v2 ]
|
||||
pull_request:
|
||||
branches: [ v2 ]
|
||||
|
||||
jobs:
|
||||
build_docker:
|
||||
|
25
.github/workflows/issue_invalid.yml
vendored
Normal file
25
.github/workflows/issue_invalid.yml
vendored
Normal file
@ -0,0 +1,25 @@
|
||||
name: Issue Invalid
|
||||
|
||||
on:
|
||||
issues:
|
||||
types: [labeled]
|
||||
|
||||
jobs:
|
||||
create-comment:
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event.label.name == 'invalid'
|
||||
steps:
|
||||
- name: Create comment
|
||||
uses: actions-cool/issues-helper@v2
|
||||
with:
|
||||
actions: 'create-comment'
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
issue-number: ${{ github.event.issue.number }}
|
||||
body: |
|
||||
Hello @${{ github.event.issue.user.login }}, your issue is invalid and will be closed.
|
||||
你好 @${{ github.event.issue.user.login }},你的issue无效,将被关闭。
|
||||
- name: Close issue
|
||||
uses: actions-cool/issues-helper@v2
|
||||
with:
|
||||
actions: 'close-issue'
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
2
.github/workflows/issue_question.yml
vendored
2
.github/workflows/issue_question.yml
vendored
@ -17,4 +17,4 @@ jobs:
|
||||
issue-number: ${{ github.event.issue.number }}
|
||||
body: |
|
||||
Hello @${{ github.event.issue.user.login }}, please input issue by template and add detail. Issues labeled by `question` will be closed if no activities in 7 days.
|
||||
你好 @${{ github.event.issue.user.login }},请按照issue模板填写, 并详细说明问题/复现步骤/实现思路或提供更多信息等, 7天内未回复issue自动关闭。
|
||||
你好 @${{ github.event.issue.user.login }},请按照issue模板填写, 并详细说明问题/复现步骤/复现链接/实现思路或提供更多信息等, 7天内未回复issue自动关闭。
|
4
.github/workflows/release.yml
vendored
4
.github/workflows/release.yml
vendored
@ -10,7 +10,7 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
platform: [ubuntu-latest]
|
||||
go-version: [1.17]
|
||||
go-version: [1.18]
|
||||
name: Release
|
||||
runs-on: ${{ matrix.platform }}
|
||||
steps:
|
||||
@ -27,7 +27,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Set up xgo
|
||||
- name: Install upx
|
||||
run: |
|
||||
docker pull techknowlogick/xgo:latest
|
||||
go install src.techknowlogick.com/xgo@latest
|
||||
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -22,6 +22,7 @@ dist/
|
||||
# vendor/
|
||||
bin/*
|
||||
/alist
|
||||
/alist.exe
|
||||
*.json
|
||||
public/*.html
|
||||
public/assets/
|
||||
|
105
CONTRIBUTING.md
Normal file
105
CONTRIBUTING.md
Normal file
@ -0,0 +1,105 @@
|
||||
# Contributing
|
||||
|
||||
## Setup your machine
|
||||
|
||||
`alist` is written in [Go](https://golang.org/) and [React](https://reactjs.org/).
|
||||
|
||||
Prerequisites:
|
||||
|
||||
- [git](https://nodejs.org/zh-cn/)
|
||||
- [Go 1.18+](https://golang.org/doc/install)
|
||||
- [gcc](https://gcc.gnu.org/)
|
||||
- [nodejs](https://nodejs.org/)
|
||||
|
||||
Clone `alist` and `alist-web` anywhere:
|
||||
|
||||
```shell
|
||||
$ git clone https://github.com/Xhofe/alist.git
|
||||
$ git clone https://github.com/Xhofe/alist-web.git
|
||||
```
|
||||
You should switch to the dev branch for development.
|
||||
|
||||
## Preview your change
|
||||
### backend
|
||||
```shell
|
||||
$ go run alist.go
|
||||
```
|
||||
### frontend
|
||||
```shell
|
||||
$ yarn dev
|
||||
```
|
||||
|
||||
## Create a commit
|
||||
|
||||
Commit messages should be well formatted, and to make that "standardized".
|
||||
|
||||
### Commit Message Format
|
||||
Each commit message consists of a **header**, a **body** and a **footer**. The header has a special
|
||||
format that includes a **type**, a **scope** and a **subject**:
|
||||
|
||||
```
|
||||
<type>(<scope>): <subject>
|
||||
<BLANK LINE>
|
||||
<body>
|
||||
<BLANK LINE>
|
||||
<footer>
|
||||
```
|
||||
|
||||
The **header** is mandatory and the **scope** of the header is optional.
|
||||
|
||||
Any line of the commit message cannot be longer than 100 characters! This allows the message to be easier
|
||||
to read on GitHub as well as in various git tools.
|
||||
|
||||
### Revert
|
||||
If the commit reverts a previous commit, it should begin with `revert: `, followed by the header
|
||||
of the reverted commit.
|
||||
In the body it should say: `This reverts commit <hash>.`, where the hash is the SHA of the commit
|
||||
being reverted.
|
||||
|
||||
### Type
|
||||
Must be one of the following:
|
||||
|
||||
* **feat**: A new feature
|
||||
* **fix**: A bug fix
|
||||
* **docs**: Documentation only changes
|
||||
* **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing
|
||||
semi-colons, etc)
|
||||
* **refactor**: A code change that neither fixes a bug nor adds a feature
|
||||
* **perf**: A code change that improves performance
|
||||
* **test**: Adding missing or correcting existing tests
|
||||
* **build**: Affects project builds or dependency modifications
|
||||
* **revert**: Restore the previous commit
|
||||
* **ci**: Continuous integration of related file modifications
|
||||
* **chore**: Changes to the build process or auxiliary tools and libraries such as documentation
|
||||
generation
|
||||
* **release**: Release a new version
|
||||
* **workflow**: Workflow related file modification
|
||||
|
||||
### Scope
|
||||
The scope could be anything specifying place of the commit change. For example `$location`,
|
||||
`$browser`, `$compile`, `$rootScope`, `ngHref`, `ngClick`, `ngView`, etc...
|
||||
|
||||
You can use `*` when the change affects more than a single scope.
|
||||
|
||||
### Subject
|
||||
The subject contains succinct description of the change:
|
||||
|
||||
* use the imperative, present tense: "change" not "changed" nor "changes"
|
||||
* don't capitalize first letter
|
||||
* no dot (.) at the end
|
||||
|
||||
### Body
|
||||
Just as in the **subject**, use the imperative, present tense: "change" not "changed" nor "changes".
|
||||
The body should include the motivation for the change and contrast this with previous behavior.
|
||||
|
||||
### Footer
|
||||
The footer should contain any information about **Breaking Changes** and is also the place to
|
||||
[reference GitHub issues that this commit closes](https://help.github.com/articles/closing-issues-via-commit-messages/).
|
||||
|
||||
**Breaking Changes** should start with the word `BREAKING CHANGE:` with a space or two newlines.
|
||||
The rest of the commit message is then used for this.
|
||||
|
||||
## Submit a pull request
|
||||
|
||||
Push your branch to your `alist` fork and open a pull request against the
|
||||
`dev` branch.
|
32
CONTRIBUTORS.md
Normal file
32
CONTRIBUTORS.md
Normal file
@ -0,0 +1,32 @@
|
||||
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
|
||||
[](#contributors-)
|
||||
<!-- ALL-CONTRIBUTORS-BADGE:END -->
|
||||
|
||||
## Contributors ✨
|
||||
|
||||
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
|
||||
<!-- prettier-ignore-start -->
|
||||
<!-- markdownlint-disable -->
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center"><a href="http://nn.ci"><img src="https://avatars.githubusercontent.com/u/36558727?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Xhofe</b></sub></a><br /><a href="https://github.com/Xhofe/alist/commits?author=Xhofe" title="Code">💻</a> <a href="#ideas-Xhofe" title="Ideas, Planning, & Feedback">🤔</a> <a href="https://github.com/Xhofe/alist/commits?author=Xhofe" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/foxxorcat"><img src="https://avatars.githubusercontent.com/u/95907542?v=4?s=100" width="100px;" alt=""/><br /><sub><b>foxxorcat</b></sub></a><br /><a href="https://github.com/Xhofe/alist/commits?author=foxxorcat" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://www.iflu.cf/"><img src="https://avatars.githubusercontent.com/u/63903027?v=4?s=100" width="100px;" alt=""/><br /><sub><b>道辰</b></sub></a><br /><a href="https://github.com/Xhofe/alist/commits?author=DaoChen6" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://vg-land.github.io/"><img src="https://avatars.githubusercontent.com/u/16739728?v=4?s=100" width="100px;" alt=""/><br /><sub><b>vg-land</b></sub></a><br /><a href="https://github.com/Xhofe/alist/commits?author=vg-land" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://c5y.moe"><img src="https://avatars.githubusercontent.com/u/18461360?v=4?s=100" width="100px;" alt=""/><br /><sub><b>凌莞~(=^▽^=)</b></sub></a><br /><a href="https://github.com/Xhofe/alist/commits?author=Clansty" title="Documentation">📖</a></td>
|
||||
<td align="center"><a href="https://github.com/Windman1320"><img src="https://avatars.githubusercontent.com/u/9999486?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Windman</b></sub></a><br /><a href="https://github.com/Xhofe/alist/commits?author=Windman1320" title="Code">💻</a></td>
|
||||
<td align="center"><a href="https://github.com/ericarena"><img src="https://avatars.githubusercontent.com/u/4518927?v=4?s=100" width="100px;" alt=""/><br /><sub><b>ericarena</b></sub></a><br /><a href="https://github.com/Xhofe/alist/commits?author=ericarena" title="Code">💻</a></td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td align="center"><a href="https://github.com/WntFlm"><img src="https://avatars.githubusercontent.com/u/34620278?v=4?s=100" width="100px;" alt=""/><br /><sub><b>WntFlm</b></sub></a><br /><a href="https://github.com/Xhofe/alist/commits?author=WntFlm" title="Code">💻</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<!-- markdownlint-restore -->
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
<!-- ALL-CONTRIBUTORS-LIST:END -->
|
||||
|
||||
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!
|
@ -11,4 +11,4 @@ VOLUME /opt/alist/data/
|
||||
WORKDIR /opt/alist/
|
||||
COPY --from=builder /app/bin/alist ./
|
||||
EXPOSE 5244
|
||||
CMD [ "./alist" ]
|
||||
CMD [ "./alist", "-docker" ]
|
2
LICENSE
2
LICENSE
@ -658,4 +658,4 @@ specific requirements.
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU AGPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
28
README.md
28
README.md
@ -1,5 +1,5 @@
|
||||
<div align="center">
|
||||
<a href="https://alist.nn.ci"><img height="100px" alt="logo" src="https://cdn.jsdelivr.net/gh/alist-org/assets@main/logo.svg"/></a>
|
||||
<a href="https://alist.nn.ci"><img height="100px" alt="logo" src="https://cdn.jsdelivr.net/gh/alist-org/logo@main/logo.svg"/></a>
|
||||
<p><em>🗂️Another file list program that supports multiple storage, powered by Gin and React.</em></p>
|
||||
<a href="https://github.com/Xhofe/alist/releases"><img src="https://img.shields.io/github/release/Xhofe/alist?style=flat-square" alt="latest version"></a>
|
||||
<a href="https://github.com/Xhofe/alist/discussions"><img src="https://img.shields.io/github/discussions/Xhofe/alist?color=%23ED8936&style=flat-square" alt="discussions"></a>
|
||||
@ -11,11 +11,9 @@
|
||||
</a>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
---
|
||||
|
||||
English | [中文](./README_cn.md)
|
||||
English | [中文](./README_cn.md) | [Contributors](./CONTRIBUTORS.md) | [Contributing](./CONTRIBUTING.md)
|
||||
|
||||
## Features
|
||||
|
||||
@ -23,7 +21,7 @@ English | [中文](./README_cn.md)
|
||||
- [x] Local storage
|
||||
- [x] [Aliyundrive](https://www.aliyundrive.com/)
|
||||
- [x] OneDrive / Sharepoint ([global](https://www.office.com/), [cn](https://portal.partner.microsoftonline.cn),de,us)
|
||||
- [x] [189cloud](https://cloud.189.cn)
|
||||
- [x] [189cloud](https://cloud.189.cn) (Personal, Family)
|
||||
- [x] [GoogleDrive](https://drive.google.com/)
|
||||
- [x] [123pan](https://www.123pan.com/)
|
||||
- [x] [Lanzou](https://pc.woozooo.com/)
|
||||
@ -32,13 +30,16 @@ English | [中文](./README_cn.md)
|
||||
- [x] [PikPak](https://www.mypikpak.com/)
|
||||
- [x] [ShandianPan](https://shandianpan.com/)
|
||||
- [x] [S3](https://aws.amazon.com/s3/)
|
||||
- [x] WebDav
|
||||
- [x] WebDav(Support OneDrive/SharePoint without API)
|
||||
- [x] Teambition([China](https://www.teambition.com/ ),[International](https://us.teambition.com/ ))
|
||||
- [x] [Mediatrack](https://www.mediatrack.cn/)
|
||||
- [x] [139yun](https://yun.139.com/) (Personal, Family)
|
||||
- [x] [Yandex.Disk](https://disk.yandex.com/)
|
||||
- [x] [Baidu Disk](http://pan.baidu.com/)
|
||||
- [x] [Quark](https://pan.quark.cn)
|
||||
- [x] [XunleiCloud](https://pan.xunlei.com/)
|
||||
- [x] SFTP
|
||||
- [x] [Baidu.Photo](https://photo.baidu.com/)
|
||||
- [x] Easy to deploy and out-of-the-box
|
||||
- [x] File preview (PDF, markdown, code, plain text, ...)
|
||||
- [x] Image preview in gallery mode
|
||||
@ -64,16 +65,27 @@ Please go to our [discussion forum](https://github.com/Xhofe/alist/discussions)
|
||||
|
||||
Available at: <https://alist.nn.ci>.
|
||||
|
||||

|
||||

|
||||
|
||||
## Document
|
||||
|
||||
<https://alist-doc.nn.ci/en/>
|
||||
|
||||
## Special sponsors
|
||||
- [Find Resources - Aliyundrive Resource Search Engine](https://zhaoziyuan.la/)
|
||||
- [JetBrains: Essential tools for software developers and teams](https://www.jetbrains.com/)
|
||||
|
||||
## License
|
||||
|
||||
The `AList` is open-source software licensed under the AGPL-3.0 license.
|
||||
|
||||
## Disclaimer
|
||||
- This program is a free and open source project. It is designed to share files on the network disk, which is convenient for downloading and learning golang. Please abide by relevant laws and regulations when using it, and do not abuse it;
|
||||
- This program is implemented by calling the official sdk/interface, without destroying the official interface behavior;
|
||||
- This program only does 302 redirect/traffic forwarding, and does not intercept, store, or tamper with any user data;
|
||||
- Before using this program, you should understand and bear the corresponding risks, including but not limited to account ban, download speed limit, etc., which is none of this program's business;
|
||||
- If there is any infringement, please contact me by [email](mailto:i@nn.ci), and it will be dealt with in time.
|
||||
|
||||
---
|
||||
|
||||
> [@Blog](https://www.nn.ci/) · [@GitHub](https://github.com/Xhofe)
|
||||
> [@Blog](https://nn.ci/) · [@GitHub](https://github.com/Xhofe) · [@TelegramGroup](https://t.me/alist_chat) · [@QQGroup](https://jq.qq.com/?_wv=1027&k=YJJj2Gwb)
|
27
README_cn.md
27
README_cn.md
@ -1,5 +1,5 @@
|
||||
<div align="center">
|
||||
<a href="https://alist.nn.ci"><img height="100px" alt="logo" src="https://cdn.jsdelivr.net/gh/alist-org/assets@main/logo.svg"/></a>
|
||||
<a href="https://alist.nn.ci"><img height="100px" alt="logo" src="https://cdn.jsdelivr.net/gh/alist-org/logo@main/logo.svg"/></a>
|
||||
<p><em>🗂️一个支持多存储的文件列表程序,使用 Gin 和 React 。</em></p>
|
||||
<a href="https://github.com/Xhofe/alist/releases"><img src="https://img.shields.io/github/release/Xhofe/alist?style=flat-square" alt="latest version"></a>
|
||||
<a href="https://github.com/Xhofe/alist/discussions"><img src="https://img.shields.io/github/discussions/Xhofe/alist?color=%23ED8936&style=flat-square" alt="discussions"></a>
|
||||
@ -11,10 +11,9 @@
|
||||
</a>
|
||||
</div>
|
||||
|
||||
|
||||
---
|
||||
|
||||
[English](./README.md) | 中文
|
||||
[English](./README.md) | 中文 | [Contributors](./CONTRIBUTORS.md) | [Contributing](./CONTRIBUTING.md)
|
||||
|
||||
## 支持
|
||||
|
||||
@ -22,7 +21,7 @@
|
||||
- [x] 本地存储
|
||||
- [x] [阿里云盘](https://www.aliyundrive.com/)
|
||||
- [x] OneDrive / Sharepoint([国际版](https://www.office.com/), [世纪互联](https://portal.partner.microsoftonline.cn),de,us)
|
||||
- [x] [天翼云盘](https://cloud.189.cn)
|
||||
- [x] [天翼云盘](https://cloud.189.cn) (个人云, 家庭云)
|
||||
- [x] [GoogleDrive](https://drive.google.com/)
|
||||
- [x] [123云盘](https://www.123pan.com/)
|
||||
- [x] [蓝奏云](https://pc.woozooo.com/)
|
||||
@ -31,13 +30,16 @@
|
||||
- [x] [PikPak](https://www.mypikpak.com/)
|
||||
- [x] [闪电盘](https://shandianpan.com/)
|
||||
- [x] [S3](https://aws.amazon.com/cn/s3/)
|
||||
- [x] WebDav
|
||||
- [x] WebDav(支持无API的OneDrive/SharePoint)
|
||||
- [x] Teambition([中国](https://www.teambition.com/ ),[国际](https://us.teambition.com/ ))
|
||||
- [x] [分秒帧](https://www.mediatrack.cn/)
|
||||
- [x] [和彩云](https://yun.139.com/) (个人云, 家庭云)
|
||||
- [x] [Yandex.Disk](https://disk.yandex.com/)
|
||||
- [x] [百度网盘](http://pan.baidu.com/)
|
||||
- [x] [夸克网盘](https://pan.quark.cn)
|
||||
- [x] [迅雷云盘](https://pan.xunlei.com/)
|
||||
- [x] SFTP
|
||||
- [x] [一刻相册](https://photo.baidu.com/)
|
||||
- [x] 部署方便,开箱即用
|
||||
- [x] 文件预览(PDF、markdown、代码、纯文本……)
|
||||
- [x] 画廊模式下的图像预览
|
||||
@ -63,16 +65,27 @@
|
||||
|
||||
<https://alist.nn.ci>。
|
||||
|
||||

|
||||

|
||||
|
||||
## 文档
|
||||
|
||||
<https://alist-doc.nn.ci/>
|
||||
|
||||
## 特别赞助
|
||||
- [找资源 - 阿里云盘资源搜索引擎](https://zhaoziyuan.la/)
|
||||
- [JetBrains: Essential tools for software developers and teams](https://www.jetbrains.com/)
|
||||
|
||||
## 许可
|
||||
|
||||
`AList` 是在 AGPL-3.0 许可下许可的开源软件。
|
||||
|
||||
## 免责声明
|
||||
- 本程序为免费开源项目,旨在分享网盘文件,方便下载以及学习golang,使用时请遵守相关法律法规,请勿滥用;
|
||||
- 本程序通过调用官方sdk/接口实现,无破坏官方接口行为;
|
||||
- 本程序仅做302重定向/流量转发,不拦截、存储、篡改任何用户数据;
|
||||
- 在使用本程序之前,你应了解并承担相应的风险,包括但不限于账号被ban,下载限速等,与本程序无关;
|
||||
- 如有侵权,请通过[邮件](mailto:i@nn.ci)与我联系,会及时处理。
|
||||
|
||||
---
|
||||
|
||||
> [@Blog](https://www.nn.ci/) · [@GitHub](https://github.com/Xhofe)
|
||||
> [@博客](https://nn.ci/) · [@GitHub](https://github.com/Xhofe) · [@Telegram群](https://t.me/alist_chat) · [@QQ群](https://jq.qq.com/?_wv=1027&k=YJJj2Gwb)
|
4
alist.go
4
alist.go
@ -12,7 +12,6 @@ import (
|
||||
)
|
||||
|
||||
func Init() bool {
|
||||
//bootstrap.InitLog()
|
||||
bootstrap.InitConf()
|
||||
bootstrap.InitCron()
|
||||
bootstrap.InitModel()
|
||||
@ -34,7 +33,8 @@ func Init() bool {
|
||||
|
||||
func main() {
|
||||
if conf.Version {
|
||||
fmt.Printf("Built At: %s\nGo Version: %s\nAuthor: %s\nCommit ID: %s\nVersion: %s\n", conf.BuiltAt, conf.GoVersion, conf.GitAuthor, conf.GitCommit, conf.GitTag)
|
||||
fmt.Printf("Built At: %s\nGo Version: %s\nAuthor: %s\nCommit ID: %s\nVersion: %s\nWebVersion: %s\n",
|
||||
conf.BuiltAt, conf.GoVersion, conf.GitAuthor, conf.GitCommit, conf.GitTag, conf.WebTag)
|
||||
return
|
||||
}
|
||||
if !Init() {
|
||||
|
@ -1,12 +0,0 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/url"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestUrl(t *testing.T) {
|
||||
s,_ := url.QueryUnescape("/ali/%E7%8C%AA%E5%A4%B4%E7%9A%84%E6%96%87%E4%BB%B6%5B%E5%98%BF%E5%98%BF%5D/%E9%82%B9%E9%82%B9%E7%9A%84%E6%96%87%E4%BB%B6/%E6%A1%8C%E9%9D%A2%E5%A3%81%E7%BA%B8/v2-e8f266ba17ae387eefed1cb22b2b5e4e_r.jpg")
|
||||
fmt.Print(s)
|
||||
}
|
@ -3,6 +3,7 @@ package bootstrap
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/drivers/operate"
|
||||
"github.com/Xhofe/alist/model"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
@ -20,7 +21,8 @@ func InitAccounts() {
|
||||
log.Errorf("no [%s] driver", account.Type)
|
||||
} else {
|
||||
log.Infof("start init account: [%s], type: [%s]", account.Name, account.Type)
|
||||
err := driver.Save(&accounts[i], nil)
|
||||
//err := driver.Save(&accounts[i], nil)
|
||||
err := operate.Save(driver, &accounts[i], nil)
|
||||
if err != nil {
|
||||
log.Errorf("init account [%s] error:[%s]", account.Name, err.Error())
|
||||
} else {
|
||||
|
@ -3,9 +3,11 @@ package bootstrap
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/caarlos0/env/v6"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// InitConf init config
|
||||
@ -42,8 +44,28 @@ func InitConf() {
|
||||
log.Fatalf("update config struct error: %s", err.Error())
|
||||
}
|
||||
}
|
||||
err := os.MkdirAll(conf.Conf.TempDir, 0700)
|
||||
if !conf.Conf.Force {
|
||||
confFromEnv()
|
||||
}
|
||||
err := os.RemoveAll(filepath.Join(conf.Conf.TempDir))
|
||||
if err != nil {
|
||||
log.Errorln("failed delete temp file:", err)
|
||||
}
|
||||
err = os.MkdirAll(conf.Conf.TempDir, 0700)
|
||||
if err != nil {
|
||||
log.Fatalf("create temp dir error: %s", err.Error())
|
||||
}
|
||||
log.Debugf("config: %+v", conf.Conf)
|
||||
}
|
||||
|
||||
func confFromEnv() {
|
||||
prefix := "ALIST_"
|
||||
if conf.Docker {
|
||||
prefix = ""
|
||||
}
|
||||
if err := env.Parse(conf.Conf, env.Options{
|
||||
Prefix: prefix,
|
||||
}); err != nil {
|
||||
log.Fatalf("load config from env error: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
@ -12,7 +12,7 @@ func InitLog() {
|
||||
log.SetLevel(log.DebugLevel)
|
||||
log.SetReportCaller(true)
|
||||
}
|
||||
if conf.Password {
|
||||
if conf.Password || conf.Version {
|
||||
log.SetLevel(log.WarnLevel)
|
||||
}
|
||||
log.SetFormatter(&log.TextFormatter{
|
||||
@ -30,6 +30,7 @@ func init() {
|
||||
flag.BoolVar(&conf.Debug, "debug", false, "start with debug mode")
|
||||
flag.BoolVar(&conf.Version, "version", false, "print version info")
|
||||
flag.BoolVar(&conf.Password, "password", false, "print current password")
|
||||
flag.BoolVar(&conf.Docker, "docker", false, "is using docker")
|
||||
flag.Parse()
|
||||
InitLog()
|
||||
}
|
||||
|
@ -50,8 +50,8 @@ func InitModel() {
|
||||
}
|
||||
case "mysql":
|
||||
{
|
||||
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
||||
databaseConfig.User, databaseConfig.Password, databaseConfig.Host, databaseConfig.Port, databaseConfig.Name)
|
||||
dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local&tls=%s",
|
||||
databaseConfig.User, databaseConfig.Password, databaseConfig.Host, databaseConfig.Port, databaseConfig.Name, databaseConfig.SslMode)
|
||||
db, err := gorm.Open(mysql.Open(dsn), gormConfig)
|
||||
if err != nil {
|
||||
log.Fatalf("failed to connect database:%s", err.Error())
|
||||
@ -74,11 +74,11 @@ func InitModel() {
|
||||
log.Infof("auto migrate model...")
|
||||
if databaseConfig.Type == "mysql" {
|
||||
err = conf.DB.Set("gorm:table_options", "ENGINE=InnoDB CHARSET=utf8mb4").
|
||||
AutoMigrate(&model.SettingItem{}, &model.Account{}, &model.Meta{})
|
||||
AutoMigrate(&model.SettingItem{}, &model.Account{}, &model.Meta{}, &model.SearchFile{})
|
||||
} else {
|
||||
err = conf.DB.AutoMigrate(&model.SettingItem{}, &model.Account{}, &model.Meta{})
|
||||
err = conf.DB.AutoMigrate(&model.SettingItem{}, &model.Account{}, &model.Meta{}, &model.SearchFile{})
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatalf("failed to auto migrate")
|
||||
log.Fatalf("failed to auto migrate: %s", err.Error())
|
||||
}
|
||||
}
|
||||
|
@ -58,6 +58,14 @@ func InitSettings() {
|
||||
Access: model.PUBLIC,
|
||||
Group: model.FRONT,
|
||||
},
|
||||
{
|
||||
Key: "announcement",
|
||||
Value: "This is a test announcement.",
|
||||
Description: "announcement message (support markdown)",
|
||||
Type: "text",
|
||||
Access: model.PUBLIC,
|
||||
Group: model.FRONT,
|
||||
},
|
||||
{
|
||||
Key: "text types",
|
||||
Value: strings.Join(conf.TextTypes, ","),
|
||||
@ -65,13 +73,28 @@ func InitSettings() {
|
||||
Description: "text type extensions",
|
||||
Group: model.FRONT,
|
||||
},
|
||||
//{
|
||||
// Key: "hide readme file",
|
||||
// Value: "true",
|
||||
// Type: "bool",
|
||||
// Description: "hide readme file? ",
|
||||
// Group: model.FRONT,
|
||||
//},
|
||||
{
|
||||
Key: "audio types",
|
||||
Value: strings.Join(conf.AudioTypes, ","),
|
||||
Type: "string",
|
||||
Description: "audio type extensions",
|
||||
Group: model.FRONT,
|
||||
},
|
||||
{
|
||||
Key: "video types",
|
||||
Value: strings.Join(conf.VideoTypes, ","),
|
||||
Type: "string",
|
||||
Description: "video type extensions",
|
||||
Group: model.FRONT,
|
||||
},
|
||||
{
|
||||
Key: "d_proxy types",
|
||||
Value: strings.Join(conf.DProxyTypes, ","),
|
||||
Type: "string",
|
||||
Description: "/d but proxy",
|
||||
Access: model.PRIVATE,
|
||||
Group: model.BACK,
|
||||
},
|
||||
{
|
||||
Key: "hide files",
|
||||
Value: "/\\/README.md/i",
|
||||
@ -95,12 +118,19 @@ func InitSettings() {
|
||||
Group: model.FRONT,
|
||||
},
|
||||
{
|
||||
Key: "home readme url",
|
||||
Description: "when have multiple, the readme file to show",
|
||||
Key: "global readme url",
|
||||
Description: "Default display when directory has no readme",
|
||||
Type: "string",
|
||||
Access: model.PUBLIC,
|
||||
Group: model.FRONT,
|
||||
},
|
||||
{
|
||||
Key: "pdf viewer url",
|
||||
Type: "string",
|
||||
Value: "https://alist-org.github.io/pdf.js/web/viewer.html?file=$url",
|
||||
Access: model.PUBLIC,
|
||||
Group: model.FRONT,
|
||||
},
|
||||
{
|
||||
Key: "autoplay video",
|
||||
Value: "false",
|
||||
@ -229,12 +259,36 @@ func InitSettings() {
|
||||
},
|
||||
{
|
||||
Key: "ocr api",
|
||||
Value: "https://api.xhofe.top/ocr/file/json",
|
||||
Value: "https://api.nn.ci/ocr/file/json",
|
||||
Description: "Used to identify verification codes",
|
||||
Type: "string",
|
||||
Access: model.PRIVATE,
|
||||
Group: model.BACK,
|
||||
},
|
||||
{
|
||||
Key: "enable search",
|
||||
Value: "false",
|
||||
Type: "bool",
|
||||
Access: model.PUBLIC,
|
||||
Group: model.BACK,
|
||||
Description: "Experimental function, not recommended as it's still under development",
|
||||
},
|
||||
{
|
||||
Key: "Aria2 RPC url",
|
||||
Value: "http://localhost:6800/jsonrpc",
|
||||
Description: "Aria2 RPC url, e.g. 'http://aria2.example.com:6800/jsonrpc'",
|
||||
Type: "string",
|
||||
Access: model.PRIVATE,
|
||||
Group: model.BACK,
|
||||
},
|
||||
{
|
||||
Key: "Aria2 RPC secret",
|
||||
Value: "",
|
||||
Description: "Aria2 RPC secret, e.g. '123456'",
|
||||
Type: "string",
|
||||
Access: model.PRIVATE,
|
||||
Group: model.BACK,
|
||||
},
|
||||
}
|
||||
for i, _ := range settings {
|
||||
v := settings[i]
|
||||
@ -244,7 +298,7 @@ func InitSettings() {
|
||||
if err == gorm.ErrRecordNotFound {
|
||||
err = model.SaveSetting(v)
|
||||
if v.Key == "password" {
|
||||
log.Infof("Initial password: %s", v.Value)
|
||||
log.Infof("Initial password: %s", conf.C.Sprintf(v.Value))
|
||||
}
|
||||
if err != nil {
|
||||
log.Fatalf("failed write setting: %s", err.Error())
|
||||
@ -260,6 +314,9 @@ func InitSettings() {
|
||||
if err != nil {
|
||||
log.Fatalf("failed write setting: %s", err.Error())
|
||||
}
|
||||
if v.Key == "password" {
|
||||
log.Infof("Your password: %s", conf.C.Sprintf(v.Value))
|
||||
}
|
||||
}
|
||||
}
|
||||
model.LoadSettings()
|
||||
|
36
build.sh
36
build.sh
@ -6,8 +6,11 @@ BUILD_WEB() {
|
||||
cd alist-web
|
||||
yarn
|
||||
yarn build
|
||||
sed -i -e "s/\/CDN_URL\//\//g" dist/index.html
|
||||
sed -i -e "s/assets/\/assets/g" dist/index.html
|
||||
rm -f dist/index.html-e
|
||||
mv dist ..
|
||||
cd ..
|
||||
cd .. || exit
|
||||
rm -rf alist-web
|
||||
}
|
||||
|
||||
@ -25,6 +28,7 @@ BUILD_DOCKER() {
|
||||
gitAuthor=$(git show -s --format='format:%aN <%ae>' HEAD)
|
||||
gitCommit=$(git log --pretty=format:"%h" -1)
|
||||
gitTag=$(git describe --long --tags --dirty --always)
|
||||
webTag=$(wget -qO- -t1 -T2 "https://api.github.com/repos/alist-org/alist-web/releases/latest" | grep "tag_name" | head -n 1 | awk -F ":" '{print $2}' | sed 's/\"//g;s/,//g;s/ //g')
|
||||
ldflags="\
|
||||
-w -s \
|
||||
-X 'github.com/Xhofe/alist/conf.BuiltAt=$builtAt' \
|
||||
@ -32,6 +36,7 @@ BUILD_DOCKER() {
|
||||
-X 'github.com/Xhofe/alist/conf.GitAuthor=$gitAuthor' \
|
||||
-X 'github.com/Xhofe/alist/conf.GitCommit=$gitCommit' \
|
||||
-X 'github.com/Xhofe/alist/conf.GitTag=$gitTag' \
|
||||
-X 'github.com/Xhofe/alist/conf.WebTag=$webTag' \
|
||||
"
|
||||
go build -o ./bin/alist -ldflags="$ldflags" -tags=jsoniter alist.go
|
||||
}
|
||||
@ -44,7 +49,9 @@ BUILD() {
|
||||
gitAuthor=$(git show -s --format='format:%aN <%ae>' HEAD)
|
||||
gitCommit=$(git log --pretty=format:"%h" -1)
|
||||
gitTag=$(git describe --long --tags --dirty --always)
|
||||
webTag=$(wget -qO- -t1 -T2 "https://api.github.com/repos/alist-org/alist-web/releases/latest" | grep "tag_name" | head -n 1 | awk -F ":" '{print $2}' | sed 's/\"//g;s/,//g;s/ //g')
|
||||
echo "build version: $gitTag"
|
||||
|
||||
ldflags="\
|
||||
-w -s \
|
||||
-X 'github.com/Xhofe/alist/conf.BuiltAt=$builtAt' \
|
||||
@ -52,23 +59,25 @@ BUILD() {
|
||||
-X 'github.com/Xhofe/alist/conf.GitAuthor=$gitAuthor' \
|
||||
-X 'github.com/Xhofe/alist/conf.GitCommit=$gitCommit' \
|
||||
-X 'github.com/Xhofe/alist/conf.GitTag=$gitTag' \
|
||||
-X 'github.com/Xhofe/alist/conf.WebTag=$webTag' \
|
||||
"
|
||||
|
||||
rm -rf .git/
|
||||
if [ "$1" == "release" ]; then
|
||||
xgo -out "$appName" -ldflags="$ldflags" -tags=jsoniter .
|
||||
else
|
||||
xgo -targets=linux/amd64,windows/amd64 -out "$appName" -ldflags="$ldflags" -tags=jsoniter .
|
||||
xgo -targets=linux/amd64,windows/amd64,darwin/amd64 -out "$appName" -ldflags="$ldflags" -tags=jsoniter .
|
||||
fi
|
||||
mkdir -p "build"
|
||||
mv alist-* build
|
||||
if [ "$1" != "release" ]; then
|
||||
cd build
|
||||
upx -9 ./*
|
||||
upx -9 ./alist-linux*
|
||||
upx -9 ./alist-windows*
|
||||
find . -type f -print0 | xargs -0 md5sum >md5.txt
|
||||
cat md5.txt
|
||||
cd ..
|
||||
cd .. || exit
|
||||
fi
|
||||
cd ..
|
||||
cd .. || exit
|
||||
}
|
||||
|
||||
BUILD_MUSL() {
|
||||
@ -86,13 +95,15 @@ BUILD_MUSL() {
|
||||
gitAuthor=$(git show -s --format='format:%aN <%ae>' HEAD)
|
||||
gitCommit=$(git log --pretty=format:"%h" -1)
|
||||
gitTag=$(git describe --long --tags --dirty --always)
|
||||
webTag=$(wget -qO- -t1 -T2 "https://api.github.com/repos/alist-org/alist-web/releases/latest" | grep "tag_name" | head -n 1 | awk -F ":" '{print $2}' | sed 's/\"//g;s/,//g;s/ //g')
|
||||
ldflags="\
|
||||
-w -s \
|
||||
-w -s --extldflags '-static -fpic' \
|
||||
-X 'github.com/Xhofe/alist/conf.BuiltAt=$builtAt' \
|
||||
-X 'github.com/Xhofe/alist/conf.GoVersion=$goVersion' \
|
||||
-X 'github.com/Xhofe/alist/conf.GitAuthor=$gitAuthor' \
|
||||
-X 'github.com/Xhofe/alist/conf.GitCommit=$gitCommit' \
|
||||
-X 'github.com/Xhofe/alist/conf.GitTag=$gitTag' \
|
||||
-X 'github.com/Xhofe/alist/conf.WebTag=$webTag' \
|
||||
"
|
||||
OS_ARCHES=(linux-musl-amd64 linux-musl-arm64 linux-musl-arm linux-musl-mips linux-musl-mips64 linux-musl-mips64le linux-musl-mipsle linux-musl-ppc64le linux-musl-s390x)
|
||||
CGO_ARGS=(x86_64-linux-musl-gcc aarch64-linux-musl-gcc arm-linux-musleabihf-gcc mips-linux-musl-gcc mips64-linux-musl-gcc mips64el-linux-musl-gcc mipsel-linux-musl-gcc powerpc64le-linux-musl-gcc s390x-linux-musl-gcc)
|
||||
@ -106,12 +117,13 @@ BUILD_MUSL() {
|
||||
export CGO_ENABLED=1
|
||||
go build -o ./build/$appName-$os_arch -ldflags="$ldflags" -tags=jsoniter alist.go
|
||||
done
|
||||
cd ..
|
||||
cd .. || exit
|
||||
}
|
||||
|
||||
RELEASE() {
|
||||
cd alist/build
|
||||
upx -9 ./*
|
||||
upx -9 ./alist-linux-amd64
|
||||
upx -9 ./alist-windows*
|
||||
find . -type f -print0 | xargs -0 md5sum >md5.txt
|
||||
cat md5.txt
|
||||
mkdir compress
|
||||
@ -125,7 +137,7 @@ RELEASE() {
|
||||
for i in $(find . -type f -name "$appName-windows-*"); do
|
||||
zip compress/$(echo $i | sed 's/\.[^.]*$//').zip "$i"
|
||||
done
|
||||
cd ../..
|
||||
cd ../.. || exit
|
||||
}
|
||||
|
||||
if [ "$1" = "web" ]; then
|
||||
@ -137,9 +149,9 @@ elif [ "$1" = "docker" ]; then
|
||||
elif [ "$1" = "build" ]; then
|
||||
BUILD build
|
||||
elif [ "$1" = "release" ]; then
|
||||
BUILD release
|
||||
BUILD_MUSL
|
||||
BUILD release
|
||||
RELEASE
|
||||
else
|
||||
echo -e "${RED_COLOR} Parameter error ${RES}"
|
||||
fi
|
||||
fi
|
@ -1,50 +1,50 @@
|
||||
package conf
|
||||
|
||||
type Database struct {
|
||||
Type string `json:"type"`
|
||||
User string `json:"user"`
|
||||
Password string `json:"password"`
|
||||
Host string `json:"host"`
|
||||
Port int `json:"port"`
|
||||
Name string `json:"name"`
|
||||
TablePrefix string `json:"table_prefix"`
|
||||
DBFile string `json:"db_file"`
|
||||
SslMode string `json:"ssl_mode"`
|
||||
Type string `json:"type" env:"DB_TYPE"`
|
||||
Host string `json:"host" env:"DB_HOST"`
|
||||
Port int `json:"port" env:"DB_PORT"`
|
||||
User string `json:"user" env:"DB_USER"`
|
||||
Password string `json:"password" env:"DB_PASS"`
|
||||
Name string `json:"name" env:"DB_NAME"`
|
||||
DBFile string `json:"db_file" env:"DB_FILE"`
|
||||
TablePrefix string `json:"table_prefix" env:"DB_TABLE_PREFIX"`
|
||||
SslMode string `json:"ssl_mode" env:"DB_SLL_MODE"`
|
||||
}
|
||||
|
||||
type Scheme struct {
|
||||
Https bool `json:"https"`
|
||||
CertFile string `json:"cert_file"`
|
||||
KeyFile string `json:"key_file"`
|
||||
Https bool `json:"https" env:"HTTPS"`
|
||||
CertFile string `json:"cert_file" env:"CERT_FILE"`
|
||||
KeyFile string `json:"key_file" env:"KEY_FILE"`
|
||||
}
|
||||
|
||||
type CacheConfig struct {
|
||||
Expiration int64 `json:"expiration"`
|
||||
CleanupInterval int64 `json:"cleanup_interval"`
|
||||
Expiration int64 `json:"expiration" env:"CACHE_EXPIRATION"`
|
||||
CleanupInterval int64 `json:"cleanup_interval" env:"CLEANUP_INTERVAL"`
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Address string `json:"address"`
|
||||
Port int `json:"port"`
|
||||
Assets string `json:"assets"`
|
||||
Force bool `json:"force"`
|
||||
Address string `json:"address" env:"ADDR"`
|
||||
Port int `json:"port" env:"PORT"`
|
||||
Assets string `json:"assets" env:"ASSETS"`
|
||||
Database Database `json:"database"`
|
||||
Scheme Scheme `json:"scheme"`
|
||||
Cache CacheConfig `json:"cache"`
|
||||
TempDir string `json:"temp_dir"`
|
||||
TempDir string `json:"temp_dir" env:"TEMP_DIR"`
|
||||
}
|
||||
|
||||
func DefaultConfig() *Config {
|
||||
return &Config{
|
||||
Address: "0.0.0.0",
|
||||
Port: 5244,
|
||||
Assets: "jsdelivr",
|
||||
Assets: "https://npm.elemecdn.com/alist-web@$version/dist",
|
||||
TempDir: "data/temp",
|
||||
Database: Database{
|
||||
Type: "sqlite3",
|
||||
Port: 0,
|
||||
TablePrefix: "x_",
|
||||
DBFile: "data/data.db",
|
||||
SslMode: "disable",
|
||||
},
|
||||
Cache: CacheConfig{
|
||||
Expiration: 60,
|
||||
|
11
conf/var.go
11
conf/var.go
@ -3,6 +3,7 @@ package conf
|
||||
import (
|
||||
"context"
|
||||
"github.com/eko/gocache/v2/cache"
|
||||
"github.com/fatih/color"
|
||||
"github.com/robfig/cron/v3"
|
||||
"gorm.io/gorm"
|
||||
"strconv"
|
||||
@ -14,6 +15,7 @@ var (
|
||||
GitAuthor string
|
||||
GitCommit string
|
||||
GitTag string = "dev"
|
||||
WebTag string
|
||||
)
|
||||
|
||||
var (
|
||||
@ -22,20 +24,24 @@ var (
|
||||
Debug bool
|
||||
Version bool
|
||||
Password bool
|
||||
Docker bool
|
||||
|
||||
DB *gorm.DB
|
||||
Cache *cache.Cache
|
||||
Ctx = context.TODO()
|
||||
Cron *cron.Cron
|
||||
|
||||
C = color.New(color.FgHiBlue, color.Bold, color.BgHiWhite, color.Underline)
|
||||
)
|
||||
|
||||
var (
|
||||
TextTypes = []string{"txt", "htm", "html", "xml", "java", "properties", "sql",
|
||||
"js", "md", "json", "conf", "ini", "vue", "php", "py", "bat", "gitignore", "yml",
|
||||
"go", "sh", "c", "cpp", "h", "hpp", "tsx", "vtt", "srt", "ass"}
|
||||
DProxyTypes = []string{"m3u8"}
|
||||
OfficeTypes = []string{"doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf"}
|
||||
VideoTypes = []string{"mp4", "mkv", "avi", "mov", "rmvb", "webm", "flv"}
|
||||
AudioTypes = []string{"mp3", "flac", "ogg", "m4a", "wav"}
|
||||
VideoTypes = []string{"mp4", "mkv", "avi", "mov", "rmvb", "webm", "flv", "m4v"}
|
||||
AudioTypes = []string{"mp3", "flac", "ogg", "m4a", "wav", "opus"}
|
||||
ImageTypes = []string{"jpg", "tiff", "jpeg", "png", "gif", "bmp", "svg", "ico", "swf", "webp"}
|
||||
)
|
||||
|
||||
@ -79,6 +85,7 @@ var (
|
||||
"Visitor WebDAV username", "Visitor WebDAV password",
|
||||
"default page size", "load type",
|
||||
"ocr api", "favicon",
|
||||
"enable search",
|
||||
}
|
||||
)
|
||||
|
||||
|
@ -3,67 +3,17 @@ package _23
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/go-resty/resty/v2"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type BaseResp struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type Pan123TokenResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
Token string `json:"token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type Pan123File struct {
|
||||
FileName string `json:"FileName"`
|
||||
Size int64 `json:"Size"`
|
||||
UpdateAt *time.Time `json:"UpdateAt"`
|
||||
FileId int64 `json:"FileId"`
|
||||
Type int `json:"Type"`
|
||||
Etag string `json:"Etag"`
|
||||
S3KeyFlag string `json:"S3KeyFlag"`
|
||||
}
|
||||
|
||||
type Pan123Files struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
InfoList []Pan123File `json:"InfoList"`
|
||||
Next string `json:"Next"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type Pan123DownResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
DownloadUrl string `json:"DownloadUrl"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type UploadResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
AccessKeyId string `json:"AccessKeyId"`
|
||||
Bucket string `json:"Bucket"`
|
||||
Key string `json:"Key"`
|
||||
SecretAccessKey string `json:"SecretAccessKey"`
|
||||
SessionToken string `json:"SessionToken"`
|
||||
FileId int64 `json:"FileId"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func (driver Pan123) Login(account *model.Account) error {
|
||||
url := "https://www.123pan.com/api/user/sign_in"
|
||||
if account.APIProxyUrl != "" {
|
||||
@ -90,25 +40,22 @@ func (driver Pan123) Login(account *model.Account) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver Pan123) FormatFile(file *Pan123File) *model.File {
|
||||
func (driver Pan123) FormatFile(file *File) *model.File {
|
||||
f := &model.File{
|
||||
Id: strconv.FormatInt(file.FileId, 10),
|
||||
Name: file.FileName,
|
||||
Size: file.Size,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: file.UpdateAt,
|
||||
Thumbnail: file.DownloadUrl,
|
||||
}
|
||||
if file.Type == 1 {
|
||||
f.Type = conf.FOLDER
|
||||
} else {
|
||||
f.Type = utils.GetFileType(filepath.Ext(file.FileName))
|
||||
}
|
||||
f.Type = file.GetType()
|
||||
return f
|
||||
}
|
||||
|
||||
func (driver Pan123) GetFiles(parentId string, account *model.Account) ([]Pan123File, error) {
|
||||
func (driver Pan123) GetFiles(parentId string, account *model.Account) ([]File, error) {
|
||||
next := "0"
|
||||
res := make([]Pan123File, 0)
|
||||
res := make([]File, 0)
|
||||
for next != "-1" {
|
||||
var resp Pan123Files
|
||||
query := map[string]string{
|
||||
@ -120,7 +67,7 @@ func (driver Pan123) GetFiles(parentId string, account *model.Account) ([]Pan123
|
||||
"parentFileId": parentId,
|
||||
"trashed": "false",
|
||||
}
|
||||
_, err := driver.Request("https://www.123pan.com/api/file/list",
|
||||
_, err := driver.Request("https://www.123pan.com/api/file/list/new",
|
||||
base.Get, nil, query, nil, &resp, false, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -193,7 +140,7 @@ func (driver Pan123) Request(url string, method int, headers, query map[string]s
|
||||
// return body, nil
|
||||
//}
|
||||
|
||||
func (driver Pan123) GetFile(path string, account *model.Account) (*Pan123File, error) {
|
||||
func (driver Pan123) GetFile(path string, account *model.Account) (*File, error) {
|
||||
dir, name := filepath.Split(path)
|
||||
dir = utils.ParsePath(dir)
|
||||
_, err := driver.Files(dir, account)
|
||||
@ -201,14 +148,15 @@ func (driver Pan123) GetFile(path string, account *model.Account) (*Pan123File,
|
||||
return nil, err
|
||||
}
|
||||
parentFiles_, _ := base.GetCache(dir, account)
|
||||
parentFiles, _ := parentFiles_.([]Pan123File)
|
||||
parentFiles, _ := parentFiles_.([]File)
|
||||
for _, file := range parentFiles {
|
||||
if file.FileName == name {
|
||||
if file.Type != conf.FOLDER {
|
||||
return &file, err
|
||||
} else {
|
||||
return nil, base.ErrNotFile
|
||||
}
|
||||
//if file.Type != conf.FOLDER {
|
||||
// return &file, err
|
||||
//} else {
|
||||
// return nil, base.ErrNotFile
|
||||
//}
|
||||
return &file, nil
|
||||
}
|
||||
}
|
||||
return nil, base.ErrPathNotFound
|
||||
|
@ -1,9 +1,18 @@
|
||||
package _23
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/binary"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
@ -13,12 +22,6 @@ import (
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/s3/s3manager"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Pan123 struct{}
|
||||
@ -67,6 +70,12 @@ func (driver Pan123) Items() []base.Item {
|
||||
Required: true,
|
||||
Default: "asc",
|
||||
},
|
||||
{
|
||||
Name: "bool_1",
|
||||
Label: "stream upload",
|
||||
Type: base.TypeBool,
|
||||
Description: "io stream upload (test)",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -108,10 +117,10 @@ func (driver Pan123) File(path string, account *model.Account) (*model.File, err
|
||||
|
||||
func (driver Pan123) Files(path string, account *model.Account) ([]model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
var rawFiles []Pan123File
|
||||
var rawFiles []File
|
||||
cache, err := base.GetCache(path, account)
|
||||
if err == nil {
|
||||
rawFiles, _ = cache.([]Pan123File)
|
||||
rawFiles, _ = cache.([]File)
|
||||
} else {
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
@ -125,7 +134,7 @@ func (driver Pan123) Files(path string, account *model.Account) ([]model.File, e
|
||||
_ = base.SetCache(path, rawFiles, account)
|
||||
}
|
||||
}
|
||||
files := make([]model.File, 0)
|
||||
files := make([]model.File, 0, len(rawFiles))
|
||||
for _, file := range rawFiles {
|
||||
files = append(files, *driver.FormatFile(&file))
|
||||
}
|
||||
@ -140,7 +149,7 @@ func (driver Pan123) Link(args base.Args, account *model.Account) (*base.Link, e
|
||||
}
|
||||
var resp Pan123DownResp
|
||||
var headers map[string]string
|
||||
if args.IP != "" && args.IP != "::1" {
|
||||
if !utils.IsLocalIPAddr(args.IP) {
|
||||
headers = map[string]string{
|
||||
//"X-Real-IP": "1.1.1.1",
|
||||
"X-Forwarded-For": args.IP,
|
||||
@ -278,12 +287,13 @@ func (driver Pan123) Delete(path string, account *model.Account) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Debugln("delete 123 file: ", file)
|
||||
data := base.Json{
|
||||
"driveId": 0,
|
||||
"operation": true,
|
||||
"fileTrashInfoList": file,
|
||||
"fileTrashInfoList": []File{*file},
|
||||
}
|
||||
_, err = driver.Request("https://www.123pan.com/api/file/trash",
|
||||
_, err = driver.Request("https://www.123pan.com/b/api/file/trash",
|
||||
base.Post, nil, nil, &data, nil, false, account)
|
||||
return err
|
||||
}
|
||||
@ -299,46 +309,57 @@ func (driver Pan123) Upload(file *model.FileStream, account *model.Account) erro
|
||||
if !parentFile.IsDir() {
|
||||
return base.ErrNotFolder
|
||||
}
|
||||
parentFileId, _ := strconv.Atoi(parentFile.Id)
|
||||
tempFile, err := ioutil.TempFile(conf.Conf.TempDir, "file-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = tempFile.Close()
|
||||
_ = os.Remove(tempFile.Name())
|
||||
}()
|
||||
_, err = io.Copy(tempFile, file)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tempFile.Seek(0, io.SeekStart)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
const DEFAULT int64 = 10485760
|
||||
var uploadFile io.Reader
|
||||
h := md5.New()
|
||||
_, err = io.Copy(h, tempFile)
|
||||
if err != nil {
|
||||
return err
|
||||
if account.Bool1 && file.GetSize() > uint64(DEFAULT) {
|
||||
// 只计算前10MIB
|
||||
buf := bytes.NewBuffer(make([]byte, 0, DEFAULT))
|
||||
if n, err := io.CopyN(io.MultiWriter(buf, h), file, DEFAULT); err != io.EOF && n == 0 {
|
||||
return err
|
||||
}
|
||||
// 增加额外参数防止MD5碰撞
|
||||
h.Write([]byte(file.Name))
|
||||
num := make([]byte, 8)
|
||||
binary.BigEndian.PutUint64(num, file.Size)
|
||||
h.Write(num)
|
||||
// 拼装
|
||||
uploadFile = io.MultiReader(buf, file)
|
||||
} else {
|
||||
// 计算完整文件MD5
|
||||
tempFile, err := ioutil.TempFile(conf.Conf.TempDir, "file-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = tempFile.Close()
|
||||
_ = os.Remove(tempFile.Name())
|
||||
}()
|
||||
|
||||
if _, err = io.Copy(io.MultiWriter(tempFile, h), file); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = tempFile.Seek(0, io.SeekStart)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
uploadFile = tempFile
|
||||
}
|
||||
etag := hex.EncodeToString(h.Sum(nil))
|
||||
log.Debugln("md5:", etag)
|
||||
_, err = tempFile.Seek(0, io.SeekStart)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data := base.Json{
|
||||
"driveId": 0,
|
||||
"duplicate": true,
|
||||
"duplicate": 2, // 2->覆盖 1->重命名 0->默认
|
||||
"etag": etag,
|
||||
"fileName": file.GetFileName(),
|
||||
"parentFileId": parentFileId,
|
||||
"parentFileId": parentFile.Id,
|
||||
"size": file.GetSize(),
|
||||
"type": 0,
|
||||
}
|
||||
var resp UploadResp
|
||||
_, err = driver.Request("https://www.123pan.com/api/file/upload_request",
|
||||
base.Post, nil, nil, &data, &resp, false, account)
|
||||
base.Post, map[string]string{"app-version": "1.1"}, nil, &data, &resp, false, account)
|
||||
//res, err := driver.Post("https://www.123pan.com/api/file/upload_request", data, account)
|
||||
if err != nil {
|
||||
return err
|
||||
@ -360,7 +381,7 @@ func (driver Pan123) Upload(file *model.FileStream, account *model.Account) erro
|
||||
input := &s3manager.UploadInput{
|
||||
Bucket: &resp.Data.Bucket,
|
||||
Key: &resp.Data.Key,
|
||||
Body: tempFile,
|
||||
Body: uploadFile,
|
||||
}
|
||||
_, err = uploader.Upload(input)
|
||||
if err != nil {
|
||||
|
74
drivers/123/types.go
Normal file
74
drivers/123/types.go
Normal file
@ -0,0 +1,74 @@
|
||||
package _23
|
||||
|
||||
import (
|
||||
"path"
|
||||
"time"
|
||||
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
)
|
||||
|
||||
type File struct {
|
||||
FileName string `json:"FileName"`
|
||||
Size int64 `json:"Size"`
|
||||
UpdateAt *time.Time `json:"UpdateAt"`
|
||||
FileId int64 `json:"FileId"`
|
||||
Type int `json:"Type"`
|
||||
Etag string `json:"Etag"`
|
||||
S3KeyFlag string `json:"S3KeyFlag"`
|
||||
DownloadUrl string `json:"DownloadUrl"`
|
||||
}
|
||||
|
||||
func (f File) GetSize() uint64 {
|
||||
return uint64(f.Size)
|
||||
}
|
||||
|
||||
func (f File) GetName() string {
|
||||
return f.FileName
|
||||
}
|
||||
|
||||
func (f File) GetType() int {
|
||||
if f.Type == 1 {
|
||||
return conf.FOLDER
|
||||
}
|
||||
return utils.GetFileType(path.Ext(f.FileName))
|
||||
}
|
||||
|
||||
type BaseResp struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type Pan123TokenResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
Token string `json:"token"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type Pan123Files struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
InfoList []File `json:"InfoList"`
|
||||
Next string `json:"Next"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type Pan123DownResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
DownloadUrl string `json:"DownloadUrl"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
type UploadResp struct {
|
||||
BaseResp
|
||||
Data struct {
|
||||
AccessKeyId string `json:"AccessKeyId"`
|
||||
Bucket string `json:"Bucket"`
|
||||
Key string `json:"Key"`
|
||||
SecretAccessKey string `json:"SecretAccessKey"`
|
||||
SessionToken string `json:"SessionToken"`
|
||||
FileId int64 `json:"FileId"`
|
||||
} `json:"data"`
|
||||
}
|
@ -448,6 +448,7 @@ func (driver Cloud139) Upload(file *model.FileStream, account *model.Account) er
|
||||
return err
|
||||
}
|
||||
log.Debugf("%+v", res)
|
||||
res.Body.Close()
|
||||
start += byteSize
|
||||
}
|
||||
return nil
|
||||
|
@ -17,7 +17,6 @@ import (
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
@ -59,11 +58,9 @@ func (driver Cloud189) FormatFile(file *Cloud189File) *model.File {
|
||||
f.UpdatedAt = &lastOpTime
|
||||
}
|
||||
if file.Size == -1 {
|
||||
f.Type = conf.FOLDER
|
||||
f.Size = 0
|
||||
} else {
|
||||
f.Type = utils.GetFileType(filepath.Ext(file.Name))
|
||||
}
|
||||
f.Type = file.GetType()
|
||||
return f
|
||||
}
|
||||
|
||||
@ -88,12 +85,6 @@ func (driver Cloud189) FormatFile(file *Cloud189File) *model.File {
|
||||
// return nil, ErrPathNotFound
|
||||
//}
|
||||
|
||||
type Cloud189Down struct {
|
||||
ResCode int `json:"res_code"`
|
||||
ResMessage string `json:"res_message"`
|
||||
FileDownloadUrl string `json:"fileDownloadUrl"`
|
||||
}
|
||||
|
||||
type LoginResp struct {
|
||||
Msg string `json:"msg"`
|
||||
Result int `json:"result"`
|
||||
@ -102,21 +93,19 @@ type LoginResp struct {
|
||||
|
||||
// Login refer to PanIndex
|
||||
func (driver Cloud189) Login(account *model.Account) error {
|
||||
client, ok := client189Map[account.Name]
|
||||
if !ok {
|
||||
//cookieJar, _ := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
|
||||
client = resty.New()
|
||||
//client.SetCookieJar(cookieJar)
|
||||
client.SetTimeout(base.DefaultTimeout)
|
||||
client.SetRetryCount(3)
|
||||
client.SetHeader("Referer", "https://cloud.189.cn/")
|
||||
}
|
||||
client := resty.New()
|
||||
//client.SetCookieJar(cookieJar)
|
||||
client.SetTimeout(base.DefaultTimeout)
|
||||
client.SetRetryCount(3)
|
||||
client.SetHeader("Referer", "https://cloud.189.cn/")
|
||||
url := "https://cloud.189.cn/api/portal/loginUrl.action?redirectURL=https%3A%2F%2Fcloud.189.cn%2Fmain.action"
|
||||
b := ""
|
||||
lt := ""
|
||||
ltText := regexp.MustCompile(`lt = "(.+?)"`)
|
||||
var res *resty.Response
|
||||
var err error
|
||||
for i := 0; i < 3; i++ {
|
||||
res, err := client.R().Get(url)
|
||||
res, err = client.R().Get(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -134,7 +123,8 @@ func (driver Cloud189) Login(account *model.Account) error {
|
||||
}
|
||||
}
|
||||
if lt == "" {
|
||||
return fmt.Errorf("get empty login page")
|
||||
return fmt.Errorf("get page: %s \nstatus: %d \nrequest url: %s\nredirect url: %s",
|
||||
b, res.StatusCode(), res.RawResponse.Request.URL.String(), res.Header().Get("location"))
|
||||
}
|
||||
captchaToken := regexp.MustCompile(`captchaToken' value='(.+?)'`).FindStringSubmatch(b)[1]
|
||||
returnUrl := regexp.MustCompile(`returnUrl = '(.+?)'`).FindStringSubmatch(b)[1]
|
||||
@ -174,7 +164,7 @@ func (driver Cloud189) Login(account *model.Account) error {
|
||||
passwordRsa := RsaEncode([]byte(account.Password), jRsakey, true)
|
||||
url = "https://open.e.189.cn/api/logbox/oauth2/loginSubmit.do"
|
||||
var loginResp LoginResp
|
||||
res, err := client.R().
|
||||
res, err = client.R().
|
||||
SetHeaders(map[string]string{
|
||||
"lt": lt,
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36",
|
||||
@ -580,6 +570,7 @@ func (driver Cloud189) NewUpload(file *model.FileStream, account *model.Account)
|
||||
|
||||
r, err := base.HttpClient.Do(req)
|
||||
log.Debugf("%+v %+v", r, r.Request.Header)
|
||||
r.Body.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -6,8 +6,11 @@ import (
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/go-resty/resty/v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Cloud189 struct{}
|
||||
@ -152,14 +155,15 @@ func (driver Cloud189) Link(args base.Args, account *model.Account) (*base.Link,
|
||||
if file.Type == conf.FOLDER {
|
||||
return nil, base.ErrNotFile
|
||||
}
|
||||
var resp Cloud189Down
|
||||
u := "https://cloud.189.cn/api/open/file/getFileDownloadUrl.action"
|
||||
var resp DownResp
|
||||
u := "https://cloud.189.cn/api/portal/getFileInfo.action"
|
||||
body, err := driver.Request(u, base.Get, map[string]string{
|
||||
"fileId": file.Id,
|
||||
}, nil, nil, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Debugln(string(body))
|
||||
err = utils.Json.Unmarshal(body, &resp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -167,21 +171,35 @@ func (driver Cloud189) Link(args base.Args, account *model.Account) (*base.Link,
|
||||
if resp.ResCode != 0 {
|
||||
return nil, fmt.Errorf(resp.ResMessage)
|
||||
}
|
||||
res, err := base.NoRedirectClient.R().Get(resp.FileDownloadUrl)
|
||||
client, err := driver.getClient(account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client = resty.NewWithClient(client.GetClient()).SetRedirectPolicy(
|
||||
resty.RedirectPolicyFunc(func(req *http.Request, via []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
}))
|
||||
res, err := client.R().Get("https:" + resp.FileDownloadUrl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Debugln(res.Status())
|
||||
link := base.Link{
|
||||
Headers: []base.Header{
|
||||
{Name: "User-Agent", Value: base.UserAgent},
|
||||
{Name: "Authorization", Value: ""},
|
||||
//{Name: "Authorization", Value: ""},
|
||||
},
|
||||
}
|
||||
if res.StatusCode() == 302 {
|
||||
link.Url = res.Header().Get("location")
|
||||
res, err = client.R().Get(link.Url)
|
||||
if res.StatusCode() == 302 {
|
||||
link.Url = res.Header().Get("location")
|
||||
}
|
||||
} else {
|
||||
link.Url = resp.FileDownloadUrl
|
||||
}
|
||||
link.Url = strings.Replace(link.Url, "http://", "https://", 1)
|
||||
return &link, nil
|
||||
}
|
||||
|
||||
|
@ -1,5 +1,11 @@
|
||||
package _89
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"path"
|
||||
)
|
||||
|
||||
type Cloud189Error struct {
|
||||
ErrorCode string `json:"errorCode"`
|
||||
ErrorMsg string `json:"errorMsg"`
|
||||
@ -17,6 +23,24 @@ type Cloud189File struct {
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
func (f Cloud189File) GetSize() uint64 {
|
||||
if f.Size == -1 {
|
||||
return 0
|
||||
}
|
||||
return uint64(f.Size)
|
||||
}
|
||||
|
||||
func (f Cloud189File) GetName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
func (f Cloud189File) GetType() int {
|
||||
if f.Size == -1 {
|
||||
return conf.FOLDER
|
||||
}
|
||||
return utils.GetFileType(path.Ext(f.Name))
|
||||
}
|
||||
|
||||
type Cloud189Folder struct {
|
||||
Id int64 `json:"id"`
|
||||
LastOpTime string `json:"lastOpTime"`
|
||||
@ -53,3 +77,15 @@ type Rsa struct {
|
||||
PkId string `json:"pkId"`
|
||||
PubKey string `json:"pubKey"`
|
||||
}
|
||||
|
||||
type Cloud189Down struct {
|
||||
ResCode int `json:"res_code"`
|
||||
ResMessage string `json:"res_message"`
|
||||
FileDownloadUrl string `json:"fileDownloadUrl"`
|
||||
}
|
||||
|
||||
type DownResp struct {
|
||||
ResCode int `json:"res_code"`
|
||||
ResMessage string `json:"res_message"`
|
||||
FileDownloadUrl string `json:"downloadUrl"`
|
||||
}
|
||||
|
318
drivers/189pc/189.go
Normal file
318
drivers/189pc/189.go
Normal file
@ -0,0 +1,318 @@
|
||||
package _189
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sync"
|
||||
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/go-resty/resty/v2"
|
||||
"github.com/google/uuid"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
var userStateCache = struct {
|
||||
sync.Mutex
|
||||
States map[string]*State
|
||||
}{States: make(map[string]*State)}
|
||||
|
||||
func GetState(account *model.Account) *State {
|
||||
userStateCache.Lock()
|
||||
defer userStateCache.Unlock()
|
||||
if v, ok := userStateCache.States[account.Username]; ok && v != nil {
|
||||
return v
|
||||
}
|
||||
state := &State{client: resty.New().
|
||||
SetHeaders(map[string]string{
|
||||
"Accept": "application/json;charset=UTF-8",
|
||||
"User-Agent": base.UserAgent,
|
||||
}).SetTimeout(base.DefaultTimeout),
|
||||
}
|
||||
userStateCache.States[account.Username] = state
|
||||
return state
|
||||
}
|
||||
|
||||
type State struct {
|
||||
sync.Mutex
|
||||
client *resty.Client
|
||||
|
||||
RsaPublicKey string
|
||||
|
||||
SessionKey string
|
||||
SessionSecret string
|
||||
FamilySessionKey string
|
||||
FamilySessionSecret string
|
||||
|
||||
AccessToken string
|
||||
|
||||
//怎么刷新的???
|
||||
RefreshToken string
|
||||
}
|
||||
|
||||
func (s *State) login(account *model.Account) error {
|
||||
// 清除cookie
|
||||
jar, _ := cookiejar.New(nil)
|
||||
s.client.SetCookieJar(jar)
|
||||
|
||||
var err error
|
||||
var res *resty.Response
|
||||
defer func() {
|
||||
account.Status = "work"
|
||||
if err != nil {
|
||||
account.Status = err.Error()
|
||||
}
|
||||
model.SaveAccount(account)
|
||||
if res != nil {
|
||||
log.Debug(res.String())
|
||||
}
|
||||
}()
|
||||
|
||||
var param *LoginParam
|
||||
param, err = s.getLoginParam()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 提交登录
|
||||
s.RsaPublicKey = fmt.Sprintf("-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----", param.jRsaKey)
|
||||
res, err = s.client.R().
|
||||
SetHeaders(map[string]string{
|
||||
"Referer": AUTH_URL,
|
||||
"REQID": param.ReqId,
|
||||
"lt": param.Lt,
|
||||
}).
|
||||
SetFormData(map[string]string{
|
||||
"appKey": APP_ID,
|
||||
"accountType": "02",
|
||||
"userName": "{RSA}" + rsaEncrypt(s.RsaPublicKey, account.Username),
|
||||
"password": "{RSA}" + rsaEncrypt(s.RsaPublicKey, account.Password),
|
||||
"validateCode": param.vCodeRS,
|
||||
"captchaToken": param.CaptchaToken,
|
||||
"returnUrl": RETURN_URL,
|
||||
"mailSuffix": "@189.cn",
|
||||
"dynamicCheck": "FALSE",
|
||||
"clientType": CLIENT_TYPE,
|
||||
"cb_SaveName": "1",
|
||||
"isOauth2": "false",
|
||||
"state": "",
|
||||
"paramId": param.ParamId,
|
||||
}).
|
||||
Post(AUTH_URL + "/api/logbox/oauth2/loginSubmit.do")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
toUrl := utils.Json.Get(res.Body(), "toUrl").ToString()
|
||||
if toUrl == "" {
|
||||
log.Error(res.String())
|
||||
return fmt.Errorf(res.String())
|
||||
}
|
||||
|
||||
// 获取Session
|
||||
var erron Erron
|
||||
var sessionResp appSessionResp
|
||||
res, err = s.client.R().
|
||||
SetResult(&sessionResp).SetError(&erron).
|
||||
SetQueryParams(clientSuffix()).
|
||||
SetQueryParam("redirectURL", url.QueryEscape(toUrl)).
|
||||
Post(API_URL + "/getSessionForPC.action")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if erron.ResCode != "" {
|
||||
err = fmt.Errorf(erron.ResMessage)
|
||||
return err
|
||||
}
|
||||
if sessionResp.ResCode != 0 {
|
||||
err = fmt.Errorf(sessionResp.ResMessage)
|
||||
return err
|
||||
}
|
||||
s.SessionKey = sessionResp.SessionKey
|
||||
s.SessionSecret = sessionResp.SessionSecret
|
||||
s.FamilySessionKey = sessionResp.FamilySessionKey
|
||||
s.FamilySessionSecret = sessionResp.FamilySessionSecret
|
||||
s.AccessToken = sessionResp.AccessToken
|
||||
s.RefreshToken = sessionResp.RefreshToken
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *State) getLoginParam() (*LoginParam, error) {
|
||||
res, err := s.client.R().
|
||||
SetQueryParams(map[string]string{
|
||||
"appId": APP_ID,
|
||||
"clientType": CLIENT_TYPE,
|
||||
"returnURL": RETURN_URL,
|
||||
"timeStamp": fmt.Sprint(timestamp()),
|
||||
}).
|
||||
Get(WEB_URL + "/api/portal/unifyLoginForPC.action")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Debug(res.String())
|
||||
param := &LoginParam{
|
||||
CaptchaToken: regexp.MustCompile(`'captchaToken' value='(.+?)'`).FindStringSubmatch(res.String())[1],
|
||||
Lt: regexp.MustCompile(`lt = "(.+?)"`).FindStringSubmatch(res.String())[1],
|
||||
ParamId: regexp.MustCompile(`paramId = "(.+?)"`).FindStringSubmatch(res.String())[1],
|
||||
ReqId: regexp.MustCompile(`reqId = "(.+?)"`).FindStringSubmatch(res.String())[1],
|
||||
jRsaKey: regexp.MustCompile(`"j_rsaKey" value="(.+?)"`).FindStringSubmatch(res.String())[1],
|
||||
|
||||
vCodeID: regexp.MustCompile(`token=([A-Za-z0-9&=]+)`).FindStringSubmatch(res.String())[1],
|
||||
}
|
||||
|
||||
imgRes, err := s.client.R().Get(fmt.Sprint(AUTH_URL, "/api/logbox/oauth2/picCaptcha.do?token=", param.vCodeID, timestamp()))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(imgRes.Body()) > 0 {
|
||||
vRes, err := resty.New().R().
|
||||
SetMultipartField("image", "validateCode.png", "image/png", bytes.NewReader(imgRes.Body())).
|
||||
Post(conf.GetStr("ocr api"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if utils.Json.Get(vRes.Body(), "status").ToInt() != 200 {
|
||||
return nil, errors.New("ocr error:" + utils.Json.Get(vRes.Body(), "msg").ToString())
|
||||
}
|
||||
param.vCodeRS = utils.Json.Get(vRes.Body(), "result").ToString()
|
||||
log.Debugln("code: ", param.vCodeRS)
|
||||
}
|
||||
return param, nil
|
||||
}
|
||||
|
||||
func (s *State) refreshSession(account *model.Account) error {
|
||||
var erron Erron
|
||||
var userSessionResp UserSessionResp
|
||||
res, err := s.client.R().
|
||||
SetResult(&userSessionResp).SetError(&erron).
|
||||
SetQueryParams(clientSuffix()).
|
||||
SetQueryParams(map[string]string{
|
||||
"appId": APP_ID,
|
||||
"accessToken": s.AccessToken,
|
||||
}).
|
||||
SetHeader("X-Request-ID", uuid.NewString()).
|
||||
Get(API_URL + "/getSessionForPC.action")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Debug(res.String())
|
||||
if erron.ResCode != "" {
|
||||
return fmt.Errorf(erron.ResMessage)
|
||||
}
|
||||
|
||||
switch userSessionResp.ResCode {
|
||||
case 0:
|
||||
s.SessionKey = userSessionResp.SessionKey
|
||||
s.SessionSecret = userSessionResp.SessionSecret
|
||||
s.FamilySessionKey = userSessionResp.FamilySessionKey
|
||||
s.FamilySessionSecret = userSessionResp.FamilySessionSecret
|
||||
case 11, 18:
|
||||
return s.login(account)
|
||||
default:
|
||||
account.Status = userSessionResp.ResMessage
|
||||
_ = model.SaveAccount(account)
|
||||
return fmt.Errorf(userSessionResp.ResMessage)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *State) IsLogin(account *model.Account) bool {
|
||||
_, err := s.Request(http.MethodGet, API_URL+"/getUserInfo.action", nil, func(r *resty.Request) { r.SetQueryParams(clientSuffix()) }, account)
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func (s *State) Login(account *model.Account) error {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.login(account)
|
||||
}
|
||||
|
||||
func (s *State) RefreshSession(account *model.Account) error {
|
||||
s.Lock()
|
||||
defer s.Unlock()
|
||||
return s.refreshSession(account)
|
||||
}
|
||||
|
||||
func (s *State) Request(method string, fullUrl string, params Params, callback func(*resty.Request), account *model.Account) (*resty.Response, error) {
|
||||
s.Lock()
|
||||
dateOfGmt := getHttpDateStr()
|
||||
sessionKey := s.SessionKey
|
||||
sessionSecret := s.SessionSecret
|
||||
if isFamily(account) {
|
||||
sessionKey = s.FamilySessionKey
|
||||
sessionSecret = s.FamilySessionSecret
|
||||
}
|
||||
|
||||
req := s.client.R()
|
||||
req.SetHeaders(map[string]string{
|
||||
"Date": dateOfGmt,
|
||||
"SessionKey": sessionKey,
|
||||
"X-Request-ID": uuid.NewString(),
|
||||
})
|
||||
|
||||
// 设置params
|
||||
var paramsData string
|
||||
if params != nil {
|
||||
paramsData = AesECBEncrypt(params.Encode(), s.SessionSecret[:16])
|
||||
req.SetQueryParam("params", paramsData)
|
||||
}
|
||||
req.SetHeader("Signature", signatureOfHmac(sessionSecret, sessionKey, method, fullUrl, dateOfGmt, paramsData))
|
||||
|
||||
if callback != nil {
|
||||
callback(req)
|
||||
}
|
||||
s.Unlock()
|
||||
|
||||
res, err := req.Execute(method, fullUrl)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Debug(res.String())
|
||||
|
||||
var erron Erron
|
||||
utils.Json.Unmarshal(res.Body(), &erron)
|
||||
if erron.ResCode != "" {
|
||||
return nil, fmt.Errorf(erron.ResMessage)
|
||||
}
|
||||
if erron.Code != "" && erron.Code != "SUCCESS" {
|
||||
if erron.Msg == "" {
|
||||
if erron.Message == "" {
|
||||
return nil, fmt.Errorf(res.String())
|
||||
}
|
||||
return nil, fmt.Errorf(erron.Message)
|
||||
}
|
||||
return nil, fmt.Errorf(erron.Msg)
|
||||
}
|
||||
if erron.ErrorCode != "" {
|
||||
switch erron.ErrorCode {
|
||||
case "InvalidSessionKey":
|
||||
if err := s.RefreshSession(account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.Request(method, fullUrl, params, callback, account)
|
||||
}
|
||||
return nil, fmt.Errorf(erron.ErrorMsg)
|
||||
}
|
||||
|
||||
switch utils.Json.Get(res.Body(), "res_code").ToInt64() {
|
||||
case 11, 18:
|
||||
if err := s.RefreshSession(account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return s.Request(method, fullUrl, params, callback, account)
|
||||
case 0:
|
||||
if res.StatusCode() == http.StatusOK {
|
||||
return res, nil
|
||||
}
|
||||
return nil, fmt.Errorf(res.String())
|
||||
default:
|
||||
return nil, fmt.Errorf(utils.Json.Get(res.Body(), "res_message").ToString())
|
||||
}
|
||||
}
|
923
drivers/189pc/driver.go
Normal file
923
drivers/189pc/driver.go
Normal file
@ -0,0 +1,923 @@
|
||||
package _189
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"math"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/go-resty/resty/v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func init() {
|
||||
base.RegisterDriver(new(Cloud189))
|
||||
}
|
||||
|
||||
type Cloud189 struct {
|
||||
}
|
||||
|
||||
func (driver Cloud189) Config() base.DriverConfig {
|
||||
return base.DriverConfig{
|
||||
Name: "189CloudPC",
|
||||
}
|
||||
}
|
||||
|
||||
func (driver Cloud189) Items() []base.Item {
|
||||
return []base.Item{
|
||||
{
|
||||
Name: "username",
|
||||
Label: "username",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
Description: "account username/phone number",
|
||||
},
|
||||
{
|
||||
Name: "password",
|
||||
Label: "password",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
Description: "account password",
|
||||
},
|
||||
{
|
||||
Name: "root_folder",
|
||||
Label: "root folder file_id",
|
||||
Type: base.TypeString,
|
||||
},
|
||||
{
|
||||
Name: "internal_type",
|
||||
Label: "189cloud type",
|
||||
Type: base.TypeSelect,
|
||||
Required: true,
|
||||
Values: "Personal,Family",
|
||||
},
|
||||
{
|
||||
Name: "site_id",
|
||||
Label: "family id",
|
||||
Type: base.TypeString,
|
||||
},
|
||||
{
|
||||
Name: "order_by",
|
||||
Label: "order_by",
|
||||
Type: base.TypeSelect,
|
||||
Values: "filename,filesize,lastOpTime",
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "order_direction",
|
||||
Label: "desc",
|
||||
Type: base.TypeSelect,
|
||||
Values: "true,false",
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "bool_1",
|
||||
Label: "fast upload",
|
||||
Type: base.TypeBool,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (driver Cloud189) Save(account *model.Account, old *model.Account) error {
|
||||
if account == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if !isFamily(account) && account.RootFolder == "" {
|
||||
account.RootFolder = "-11"
|
||||
account.SiteId = ""
|
||||
}
|
||||
if isFamily(account) && account.RootFolder == "-11" {
|
||||
account.RootFolder = ""
|
||||
}
|
||||
|
||||
state := GetState(account)
|
||||
if !state.IsLogin(account) {
|
||||
if err := state.Login(account); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if isFamily(account) {
|
||||
list, err := driver.getFamilyInfoList(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, l := range list {
|
||||
if account.SiteId == "" {
|
||||
account.SiteId = fmt.Sprint(l.FamilyID)
|
||||
}
|
||||
log.Infof("天翼家庭云 用户名:%s FamilyID %d\n", l.RemarkName, l.FamilyID)
|
||||
}
|
||||
}
|
||||
|
||||
account.Status = "work"
|
||||
model.SaveAccount(account)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (driver Cloud189) getFamilyInfoList(account *model.Account) ([]FamilyInfoResp, error) {
|
||||
var resp FamilyInfoListResp
|
||||
_, err := GetState(account).Request(http.MethodGet, API_URL+"/family/manage/getFamilyList.action", nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(clientSuffix())
|
||||
r.SetResult(&resp)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp.FamilyInfoResp, nil
|
||||
}
|
||||
|
||||
func (driver Cloud189) File(path string, account *model.Account) (*model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
if path == "/" {
|
||||
return &model.File{
|
||||
Id: account.RootFolder,
|
||||
Name: account.Name,
|
||||
Size: 0,
|
||||
Type: conf.FOLDER,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: account.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
dir, name := filepath.Split(path)
|
||||
files, err := driver.Files(dir, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range files {
|
||||
if file.Name == name {
|
||||
return &file, nil
|
||||
}
|
||||
}
|
||||
return nil, base.ErrPathNotFound
|
||||
}
|
||||
|
||||
func (driver Cloud189) Files(path string, account *model.Account) ([]model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
cache, err := base.GetCache(path, account)
|
||||
if err == nil {
|
||||
files, _ := cache.([]model.File)
|
||||
return files, nil
|
||||
}
|
||||
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fullUrl := API_URL
|
||||
if isFamily(account) {
|
||||
fullUrl += "/family/file"
|
||||
}
|
||||
fullUrl += "/listFiles.action"
|
||||
|
||||
files := make([]model.File, 0)
|
||||
client := GetState(account)
|
||||
for pageNum := 1; ; pageNum++ {
|
||||
var resp Cloud189FilesResp
|
||||
_, err = client.Request(http.MethodGet, fullUrl, nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(clientSuffix()).
|
||||
SetQueryParams(map[string]string{
|
||||
"folderId": file.Id,
|
||||
"fileType": "0",
|
||||
"mediaAttr": "0",
|
||||
"iconOption": "5",
|
||||
"pageNum": fmt.Sprint(pageNum),
|
||||
"pageSize": "130",
|
||||
})
|
||||
if isFamily(account) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"familyId": account.SiteId,
|
||||
"orderBy": toFamilyOrderBy(account.OrderBy),
|
||||
"descending": account.OrderDirection,
|
||||
})
|
||||
} else {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"recursive": "0",
|
||||
"orderBy": account.OrderBy,
|
||||
"descending": account.OrderDirection,
|
||||
})
|
||||
}
|
||||
r.SetResult(&resp)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 获取完毕跳出
|
||||
if resp.FileListAO.Count == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
for _, folder := range resp.FileListAO.FolderList {
|
||||
files = append(files, model.File{
|
||||
Id: fmt.Sprint(folder.ID),
|
||||
Name: folder.Name,
|
||||
Size: 0,
|
||||
Type: conf.FOLDER,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: MustParseTime(folder.LastOpTime),
|
||||
})
|
||||
}
|
||||
for _, file := range resp.FileListAO.FileList {
|
||||
files = append(files, model.File{
|
||||
Id: fmt.Sprint(file.ID),
|
||||
Name: file.Name,
|
||||
Size: file.Size,
|
||||
Type: utils.GetFileType(filepath.Ext(file.Name)),
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: MustParseTime(file.LastOpTime),
|
||||
Thumbnail: file.Icon.SmallUrl,
|
||||
})
|
||||
}
|
||||
}
|
||||
if len(files) > 0 {
|
||||
_ = base.SetCache(path, files, account)
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func (driver Cloud189) Path(path string, account *model.Account) (*model.File, []model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
log.Debugf("189PC path: %s", path)
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !file.IsDir() {
|
||||
return file, nil, nil
|
||||
}
|
||||
files, err := driver.Files(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, files, nil
|
||||
}
|
||||
|
||||
func (driver Cloud189) Link(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
file, err := driver.File(utils.ParsePath(args.Path), account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if file.Type == conf.FOLDER {
|
||||
return nil, base.ErrNotFile
|
||||
}
|
||||
|
||||
fullUrl := API_URL
|
||||
if isFamily(account) {
|
||||
fullUrl += "/family/file"
|
||||
}
|
||||
fullUrl += "/getFileDownloadUrl.action"
|
||||
|
||||
var downloadUrl struct {
|
||||
URL string `json:"fileDownloadUrl"`
|
||||
}
|
||||
_, err = GetState(account).Request(http.MethodGet, fullUrl, nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(clientSuffix()).SetQueryParam("fileId", file.Id)
|
||||
if isFamily(account) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"familyId": account.SiteId,
|
||||
})
|
||||
} else {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"dt": "3",
|
||||
"flag": "1",
|
||||
})
|
||||
}
|
||||
r.SetResult(&downloadUrl)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &base.Link{
|
||||
Headers: []base.Header{
|
||||
{Name: "User-Agent", Value: base.UserAgent},
|
||||
},
|
||||
Url: strings.ReplaceAll(downloadUrl.URL, "&", "&"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (driver Cloud189) Preview(path string, account *model.Account) (interface{}, error) {
|
||||
return nil, base.ErrNotSupport
|
||||
}
|
||||
|
||||
func (driver Cloud189) MakeDir(path string, account *model.Account) error {
|
||||
dir, name := filepath.Split(path)
|
||||
parentFile, err := driver.File(dir, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !parentFile.IsDir() {
|
||||
return base.ErrNotFolder
|
||||
}
|
||||
|
||||
fullUrl := API_URL
|
||||
if isFamily(account) {
|
||||
fullUrl += "/family/file"
|
||||
}
|
||||
fullUrl += "/createFolder.action"
|
||||
|
||||
_, err = GetState(account).Request(http.MethodPost, fullUrl, nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(clientSuffix()).SetQueryParams(map[string]string{
|
||||
"folderName": name,
|
||||
"relativePath": "",
|
||||
})
|
||||
if isFamily(account) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"familyId": account.SiteId,
|
||||
"parentId": parentFile.Id,
|
||||
})
|
||||
} else {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"parentFolderId": parentFile.Id,
|
||||
})
|
||||
}
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver Cloud189) Move(src string, dst string, account *model.Account) error {
|
||||
srcFile, err := driver.File(src, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dstDirFile, err := driver.File(filepath.Dir(dst), account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = GetState(account).Request(http.MethodPost, API_URL+"/batch/createBatchTask.action", nil, func(r *resty.Request) {
|
||||
r.SetFormData(clientSuffix()).SetFormData(map[string]string{
|
||||
"type": "MOVE",
|
||||
"taskInfos": string(MustToBytes(utils.Json.Marshal(
|
||||
[]*BatchTaskInfo{
|
||||
{
|
||||
FileId: srcFile.Id,
|
||||
FileName: srcFile.Name,
|
||||
IsFolder: BoolToNumber(srcFile.IsDir()),
|
||||
},
|
||||
}))),
|
||||
"targetFolderId": dstDirFile.Id,
|
||||
})
|
||||
if isFamily(account) {
|
||||
r.SetFormData(map[string]string{
|
||||
"familyId": account.SiteId,
|
||||
})
|
||||
}
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
/*
|
||||
func (driver Cloud189) Move(src string, dst string, account *model.Account) error {
|
||||
srcFile, err := driver.File(src, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dstDirFile, err := driver.File(filepath.Dir(dst), account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var queryParam map[string]string
|
||||
fullUrl := API_URL
|
||||
method := http.MethodPost
|
||||
if isFamily(account) {
|
||||
fullUrl += "/family/file"
|
||||
method = http.MethodGet
|
||||
}
|
||||
if srcFile.IsDir() {
|
||||
fullUrl += "/moveFolder.action"
|
||||
queryParam = map[string]string{
|
||||
"folderId": srcFile.Id,
|
||||
"destFolderName": srcFile.Name,
|
||||
}
|
||||
} else {
|
||||
fullUrl += "/moveFile.action"
|
||||
queryParam = map[string]string{
|
||||
"fileId": srcFile.Id,
|
||||
"destFileName": srcFile.Name,
|
||||
}
|
||||
}
|
||||
|
||||
_, err = GetState(account).Request(method, fullUrl, nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(queryParam).SetQueryParams(clientSuffix())
|
||||
if isFamily(account) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"familyId": account.SiteId,
|
||||
"destParentId": dstDirFile.Id,
|
||||
})
|
||||
} else {
|
||||
r.SetQueryParam("destParentFolderId", dstDirFile.Id)
|
||||
}
|
||||
}, account)
|
||||
return err
|
||||
}*/
|
||||
|
||||
func (driver Cloud189) Rename(src string, dst string, account *model.Account) error {
|
||||
srcFile, err := driver.File(src, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var queryParam map[string]string
|
||||
fullUrl := API_URL
|
||||
method := http.MethodPost
|
||||
if isFamily(account) {
|
||||
fullUrl += "/family/file"
|
||||
method = http.MethodGet
|
||||
}
|
||||
if srcFile.IsDir() {
|
||||
fullUrl += "/renameFolder.action"
|
||||
queryParam = map[string]string{
|
||||
"folderId": srcFile.Id,
|
||||
"destFolderName": filepath.Base(dst),
|
||||
}
|
||||
} else {
|
||||
fullUrl += "/renameFile.action"
|
||||
queryParam = map[string]string{
|
||||
"fileId": srcFile.Id,
|
||||
"destFileName": filepath.Base(dst),
|
||||
}
|
||||
}
|
||||
|
||||
_, err = GetState(account).Request(method, fullUrl, nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(queryParam).SetQueryParams(clientSuffix())
|
||||
if isFamily(account) {
|
||||
r.SetQueryParam("familyId", account.SiteId)
|
||||
}
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver Cloud189) Copy(src string, dst string, account *model.Account) error {
|
||||
srcFile, err := driver.File(src, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dstDirFile, err := driver.File(filepath.Dir(dst), account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = GetState(account).Request(http.MethodPost, API_URL+"/batch/createBatchTask.action", nil, func(r *resty.Request) {
|
||||
r.SetFormData(clientSuffix()).SetFormData(map[string]string{
|
||||
"type": "COPY",
|
||||
"taskInfos": string(MustToBytes(utils.Json.Marshal(
|
||||
[]*BatchTaskInfo{
|
||||
{
|
||||
FileId: srcFile.Id,
|
||||
FileName: srcFile.Name,
|
||||
IsFolder: BoolToNumber(srcFile.IsDir()),
|
||||
},
|
||||
}))),
|
||||
"targetFolderId": dstDirFile.Id,
|
||||
"targetFileName": filepath.Base(dst),
|
||||
})
|
||||
if isFamily(account) {
|
||||
r.SetFormData(map[string]string{
|
||||
"familyId": account.SiteId,
|
||||
})
|
||||
}
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver Cloud189) Delete(path string, account *model.Account) error {
|
||||
path = utils.ParsePath(path)
|
||||
srcFile, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = GetState(account).Request(http.MethodPost, API_URL+"/batch/createBatchTask.action", nil, func(r *resty.Request) {
|
||||
r.SetFormData(clientSuffix()).SetFormData(map[string]string{
|
||||
"type": "DELETE",
|
||||
"taskInfos": string(MustToBytes(utils.Json.Marshal(
|
||||
[]*BatchTaskInfo{
|
||||
{
|
||||
FileId: srcFile.Id,
|
||||
FileName: srcFile.Name,
|
||||
IsFolder: BoolToNumber(srcFile.IsDir()),
|
||||
},
|
||||
}))),
|
||||
})
|
||||
|
||||
if isFamily(account) {
|
||||
r.SetFormData(map[string]string{
|
||||
"familyId": account.SiteId,
|
||||
})
|
||||
}
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver Cloud189) Upload(file *model.FileStream, account *model.Account) error {
|
||||
if file == nil {
|
||||
return base.ErrEmptyFile
|
||||
}
|
||||
|
||||
parentFile, err := driver.File(file.ParentPath, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !parentFile.IsDir() {
|
||||
return base.ErrNotFolder
|
||||
}
|
||||
|
||||
if account.Bool1 {
|
||||
return driver.FastUpload(file, parentFile, account)
|
||||
}
|
||||
return driver.CommonUpload(file, parentFile, account)
|
||||
/*
|
||||
if isFamily(account) {
|
||||
return driver.uploadFamily(file, parentFile, account)
|
||||
}
|
||||
return driver.uploadPerson(file, parentFile, account)
|
||||
*/
|
||||
}
|
||||
|
||||
func (driver Cloud189) CommonUpload(file *model.FileStream, parentFile *model.File, account *model.Account) error {
|
||||
// 初始化上传
|
||||
state := GetState(account)
|
||||
const DEFAULT int64 = 10485760
|
||||
count := int(math.Ceil(float64(file.Size) / float64(DEFAULT)))
|
||||
|
||||
params := Params{
|
||||
"parentFolderId": parentFile.Id,
|
||||
"fileName": url.PathEscape(file.Name),
|
||||
"fileSize": fmt.Sprint(file.Size),
|
||||
"sliceSize": fmt.Sprint(DEFAULT),
|
||||
"lazyCheck": "1",
|
||||
}
|
||||
|
||||
fullUrl := UPLOAD_URL
|
||||
if isFamily(account) {
|
||||
params.Set("familyId", account.SiteId)
|
||||
fullUrl += "/family"
|
||||
} else {
|
||||
//params.Set("extend", `{"opScene":"1","relativepath":"","rootfolderid":""}`)
|
||||
fullUrl += "/person"
|
||||
}
|
||||
|
||||
var initMultiUpload InitMultiUploadResp
|
||||
_, err := state.Request(http.MethodGet, fullUrl+"/initMultiUpload", params, func(r *resty.Request) { r.SetQueryParams(clientSuffix()).SetResult(&initMultiUpload) }, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fileMd5 := md5.New()
|
||||
silceMd5 := md5.New()
|
||||
silceMd5Hexs := make([]string, 0, count)
|
||||
byteData := bytes.NewBuffer(make([]byte, DEFAULT))
|
||||
for i := 1; i <= count; i++ {
|
||||
byteData.Reset()
|
||||
silceMd5.Reset()
|
||||
if n, err := io.CopyN(io.MultiWriter(fileMd5, silceMd5, byteData), file, DEFAULT); err != io.EOF && n == 0 {
|
||||
return err
|
||||
}
|
||||
md5Bytes := silceMd5.Sum(nil)
|
||||
silceMd5Hexs = append(silceMd5Hexs, strings.ToUpper(hex.EncodeToString(md5Bytes)))
|
||||
silceMd5Base64 := base64.StdEncoding.EncodeToString(md5Bytes)
|
||||
|
||||
var uploadUrl UploadUrlsResp
|
||||
_, err = state.Request(http.MethodGet, fullUrl+"/getMultiUploadUrls",
|
||||
Params{"partInfo": fmt.Sprintf("%d-%s", i, silceMd5Base64), "uploadFileId": initMultiUpload.Data.UploadFileID},
|
||||
func(r *resty.Request) { r.SetQueryParams(clientSuffix()).SetResult(&uploadUrl) },
|
||||
account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
uploadData := uploadUrl.UploadUrls[fmt.Sprint("partNumber_", i)]
|
||||
req, _ := http.NewRequest(http.MethodPut, uploadData.RequestURL, byteData)
|
||||
req.Header.Set("User-Agent", "")
|
||||
for k, v := range ParseHttpHeader(uploadData.RequestHeader) {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
for k, v := range clientSuffix() {
|
||||
req.URL.RawQuery += fmt.Sprintf("&%s=%s", k, v)
|
||||
}
|
||||
r, err := base.HttpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r.StatusCode != http.StatusOK {
|
||||
data, _ := io.ReadAll(r.Body)
|
||||
r.Body.Close()
|
||||
return fmt.Errorf(string(data))
|
||||
}
|
||||
r.Body.Close()
|
||||
}
|
||||
|
||||
fileMd5Hex := strings.ToUpper(hex.EncodeToString(fileMd5.Sum(nil)))
|
||||
sliceMd5Hex := fileMd5Hex
|
||||
if int64(file.Size) > DEFAULT {
|
||||
sliceMd5Hex = strings.ToUpper(utils.GetMD5Encode(strings.Join(silceMd5Hexs, "\n")))
|
||||
}
|
||||
|
||||
_, err = state.Request(http.MethodGet, fullUrl+"/commitMultiUploadFile",
|
||||
Params{
|
||||
"uploadFileId": initMultiUpload.Data.UploadFileID,
|
||||
"fileMd5": fileMd5Hex,
|
||||
"sliceMd5": sliceMd5Hex,
|
||||
"lazyCheck": "1",
|
||||
"isLog": "0",
|
||||
"opertype": "3",
|
||||
},
|
||||
func(r *resty.Request) { r.SetQueryParams(clientSuffix()) }, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver Cloud189) FastUpload(file *model.FileStream, parentFile *model.File, account *model.Account) error {
|
||||
tempFile, err := ioutil.TempFile(conf.Conf.TempDir, "file-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = tempFile.Close()
|
||||
_ = os.Remove(tempFile.Name())
|
||||
}()
|
||||
// 初始化上传
|
||||
state := GetState(account)
|
||||
|
||||
const DEFAULT int64 = 10485760
|
||||
count := int(math.Ceil(float64(file.Size) / float64(DEFAULT)))
|
||||
|
||||
// 优先计算所需信息
|
||||
fileMd5 := md5.New()
|
||||
silceMd5 := md5.New()
|
||||
silceMd5Hexs := make([]string, 0, count)
|
||||
silceMd5Base64s := make([]string, 0, count)
|
||||
for i := 1; i <= count; i++ {
|
||||
silceMd5.Reset()
|
||||
if n, err := io.CopyN(io.MultiWriter(fileMd5, silceMd5, tempFile), file, DEFAULT); err != nil && n == 0 {
|
||||
return err
|
||||
}
|
||||
md5Byte := silceMd5.Sum(nil)
|
||||
silceMd5Hexs = append(silceMd5Hexs, strings.ToUpper(hex.EncodeToString(md5Byte)))
|
||||
silceMd5Base64s = append(silceMd5Base64s, fmt.Sprint(i, "-", base64.StdEncoding.EncodeToString(md5Byte)))
|
||||
}
|
||||
fileMd5Hex := strings.ToUpper(hex.EncodeToString(fileMd5.Sum(nil)))
|
||||
sliceMd5Hex := fileMd5Hex
|
||||
if int64(file.Size) > DEFAULT {
|
||||
sliceMd5Hex = strings.ToUpper(utils.GetMD5Encode(strings.Join(silceMd5Hexs, "\n")))
|
||||
}
|
||||
|
||||
params := Params{
|
||||
"parentFolderId": parentFile.Id,
|
||||
"fileName": url.PathEscape(file.Name),
|
||||
"fileSize": fmt.Sprint(file.Size),
|
||||
"fileMd5": fileMd5Hex,
|
||||
"sliceSize": fmt.Sprint(DEFAULT),
|
||||
"sliceMd5": sliceMd5Hex,
|
||||
}
|
||||
|
||||
fullUrl := UPLOAD_URL
|
||||
if isFamily(account) {
|
||||
params.Set("familyId", account.SiteId)
|
||||
fullUrl += "/family"
|
||||
} else {
|
||||
//params.Set("extend", `{"opScene":"1","relativepath":"","rootfolderid":""}`)
|
||||
fullUrl += "/person"
|
||||
}
|
||||
|
||||
var uploadInfo InitMultiUploadResp
|
||||
_, err = state.Request(http.MethodGet, fullUrl+"/initMultiUpload", params, func(r *resty.Request) { r.SetQueryParams(clientSuffix()).SetResult(&uploadInfo) }, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if uploadInfo.Data.FileDataExists != 1 {
|
||||
var uploadUrls UploadUrlsResp
|
||||
_, err := state.Request(http.MethodGet, fullUrl+"/getMultiUploadUrls",
|
||||
Params{
|
||||
"uploadFileId": uploadInfo.Data.UploadFileID,
|
||||
"partInfo": strings.Join(silceMd5Base64s, ","),
|
||||
},
|
||||
func(r *resty.Request) { r.SetQueryParams(clientSuffix()).SetResult(&uploadUrls) },
|
||||
account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 1; i <= count; i++ {
|
||||
uploadData := uploadUrls.UploadUrls[fmt.Sprint("partNumber_", i)]
|
||||
req, _ := http.NewRequest(http.MethodPut, uploadData.RequestURL, io.NewSectionReader(tempFile, int64(i-1)*DEFAULT, DEFAULT))
|
||||
req.Header.Set("User-Agent", "")
|
||||
for k, v := range ParseHttpHeader(uploadData.RequestHeader) {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
for k, v := range clientSuffix() {
|
||||
req.URL.RawQuery += fmt.Sprintf("&%s=%s", k, v)
|
||||
}
|
||||
r, err := base.HttpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if r.StatusCode != http.StatusOK {
|
||||
data, _ := io.ReadAll(r.Body)
|
||||
r.Body.Close()
|
||||
return fmt.Errorf(string(data))
|
||||
}
|
||||
r.Body.Close()
|
||||
}
|
||||
}
|
||||
|
||||
_, err = state.Request(http.MethodGet, fullUrl+"/commitMultiUploadFile",
|
||||
Params{
|
||||
"uploadFileId": uploadInfo.Data.UploadFileID,
|
||||
"isLog": "0",
|
||||
"opertype": "3",
|
||||
},
|
||||
func(r *resty.Request) { r.SetQueryParams(clientSuffix()) },
|
||||
account)
|
||||
return err
|
||||
}
|
||||
|
||||
/*
|
||||
func (driver Cloud189) uploadFamily(file *model.FileStream, parentFile *model.File, account *model.Account) error {
|
||||
tempFile, err := ioutil.TempFile(conf.Conf.TempDir, "file-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = tempFile.Close()
|
||||
_ = os.Remove(tempFile.Name())
|
||||
}()
|
||||
|
||||
fileMd5 := md5.New()
|
||||
if _, err = io.Copy(io.MultiWriter(fileMd5, tempFile), file); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
client := GetState(account)
|
||||
var createUpload CreateUploadFileResult
|
||||
_, err = client.Request(http.MethodGet, API_URL+"/family/file/createFamilyFile.action", nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"fileMd5": hex.EncodeToString(fileMd5.Sum(nil)),
|
||||
"fileName": file.Name,
|
||||
"familyId": account.SiteId,
|
||||
"parentId": parentFile.Id,
|
||||
"resumePolicy": "1",
|
||||
"fileSize": fmt.Sprint(file.Size),
|
||||
})
|
||||
r.SetQueryParams(clientSuffix())
|
||||
r.SetResult(&createUpload)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if createUpload.FileDataExists != 1 {
|
||||
if createUpload.UploadFileId, err = driver.uploadFileData(file, tempFile, createUpload, account); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
_, err = client.Request(http.MethodGet, createUpload.FileCommitUrl, nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(clientSuffix())
|
||||
r.SetHeaders(map[string]string{
|
||||
"FamilyId": account.SiteId,
|
||||
"uploadFileId": fmt.Sprint(createUpload.UploadFileId),
|
||||
"ResumePolicy": "1",
|
||||
})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver Cloud189) uploadPerson(file *model.FileStream, parentFile *model.File, account *model.Account) error {
|
||||
tempFile, err := ioutil.TempFile(conf.Conf.TempDir, "file-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = tempFile.Close()
|
||||
_ = os.Remove(tempFile.Name())
|
||||
}()
|
||||
|
||||
fileMd5 := md5.New()
|
||||
if _, err = io.Copy(io.MultiWriter(fileMd5, tempFile), file); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
client := GetState(account)
|
||||
var createUpload CreateUploadFileResult
|
||||
_, err = client.Request(http.MethodPost, API_URL+"/createUploadFile.action", nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(clientSuffix())
|
||||
r.SetFormData(clientSuffix()).SetFormData(map[string]string{
|
||||
"parentFolderId": parentFile.Id,
|
||||
"baseFileId": "",
|
||||
"fileName": file.Name,
|
||||
"size": fmt.Sprint(file.Size),
|
||||
"md5": hex.EncodeToString(fileMd5.Sum(nil)),
|
||||
// "lastWrite": param.LastWrite,
|
||||
// "localPath": strings.ReplaceAll(file.ParentPath, "\\", "/"),
|
||||
"opertype": "1",
|
||||
"flag": "1",
|
||||
"resumePolicy": "1",
|
||||
"isLog": "0",
|
||||
"fileExt": "",
|
||||
})
|
||||
r.SetResult(&createUpload)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if createUpload.FileDataExists != 1 {
|
||||
if createUpload.UploadFileId, err = driver.uploadFileData(file, tempFile, createUpload, account); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
_, err = client.Request(http.MethodPost, createUpload.FileCommitUrl, nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(clientSuffix())
|
||||
r.SetFormData(map[string]string{
|
||||
"uploadFileId": fmt.Sprint(createUpload.UploadFileId),
|
||||
"opertype": "5", //5 覆盖 1 重命名
|
||||
"ResumePolicy": "1",
|
||||
"isLog": "0",
|
||||
})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver Cloud189) uploadFileData(file *model.FileStream, tempFile *os.File, createUpload CreateUploadFileResult, account *model.Account) (int64, error) {
|
||||
uploadFileState, err := driver.getUploadFileState(createUpload.UploadFileId, account)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if uploadFileState.FileDataExists == 1 || uploadFileState.DataSize == int64(file.Size) {
|
||||
return uploadFileState.UploadFileId, nil
|
||||
}
|
||||
|
||||
if _, err = tempFile.Seek(uploadFileState.DataSize, io.SeekStart); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
_, err = GetState(account).Request("PUT", uploadFileState.FileUploadUrl, nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(clientSuffix())
|
||||
r.SetHeaders(map[string]string{
|
||||
"Content-Type": "application/octet-stream",
|
||||
"ResumePolicy": "1",
|
||||
"Edrive-UploadFileRange": fmt.Sprintf("bytes=%d-%d", uploadFileState.DataSize, file.Size),
|
||||
"Expect": "100-continue",
|
||||
})
|
||||
if isFamily(account) {
|
||||
r.SetHeaders(map[string]string{
|
||||
"familyId": account.SiteId,
|
||||
"UploadFileId": fmt.Sprint(uploadFileState.UploadFileId),
|
||||
})
|
||||
} else {
|
||||
r.SetHeader("Edrive-UploadFileId", fmt.Sprint(uploadFileState.UploadFileId))
|
||||
}
|
||||
r.SetBody(tempFile)
|
||||
}, account)
|
||||
return uploadFileState.UploadFileId, err
|
||||
}
|
||||
|
||||
func (driver Cloud189) getUploadFileState(uploadFileId int64, account *model.Account) (*UploadFileStatusResult, error) {
|
||||
fullUrl := API_URL
|
||||
if isFamily(account) {
|
||||
fullUrl += "/family/file/getFamilyFileStatus.action"
|
||||
} else {
|
||||
fullUrl += "/getUploadFileStatus.action"
|
||||
}
|
||||
var uploadFileState UploadFileStatusResult
|
||||
_, err := GetState(account).Request(http.MethodGet, fullUrl, nil, func(r *resty.Request) {
|
||||
r.SetQueryParams(clientSuffix())
|
||||
r.SetQueryParams(map[string]string{
|
||||
"uploadFileId": fmt.Sprint(uploadFileId),
|
||||
"resumePolicy": "1",
|
||||
})
|
||||
if isFamily(account) {
|
||||
r.SetQueryParam("familyId", account.SiteId)
|
||||
}
|
||||
r.SetResult(&uploadFileState)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &uploadFileState, nil
|
||||
}*/
|
||||
|
||||
var _ base.Driver = (*Cloud189)(nil)
|
180
drivers/189pc/type.go
Normal file
180
drivers/189pc/type.go
Normal file
@ -0,0 +1,180 @@
|
||||
package _189
|
||||
|
||||
import "encoding/xml"
|
||||
|
||||
type LoginParam struct {
|
||||
CaptchaToken string
|
||||
Lt string
|
||||
ParamId string
|
||||
ReqId string
|
||||
jRsaKey string
|
||||
|
||||
vCodeID string
|
||||
vCodeRS string
|
||||
}
|
||||
|
||||
// 居然有四种返回方式
|
||||
type Erron struct {
|
||||
ResCode string `json:"res_code"`
|
||||
ResMessage string `json:"res_message"`
|
||||
|
||||
XMLName xml.Name `xml:"error"`
|
||||
Code string `json:"code" xml:"code"`
|
||||
Message string `json:"message" xml:"message"`
|
||||
|
||||
// Code string `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
|
||||
ErrorCode string `json:"errorCode"`
|
||||
ErrorMsg string `json:"errorMsg"`
|
||||
}
|
||||
|
||||
// 刷新session返回
|
||||
type UserSessionResp struct {
|
||||
ResCode int `json:"res_code"`
|
||||
ResMessage string `json:"res_message"`
|
||||
|
||||
LoginName string `json:"loginName"`
|
||||
|
||||
KeepAlive int `json:"keepAlive"`
|
||||
GetFileDiffSpan int `json:"getFileDiffSpan"`
|
||||
GetUserInfoSpan int `json:"getUserInfoSpan"`
|
||||
|
||||
// 个人云
|
||||
SessionKey string `json:"sessionKey"`
|
||||
SessionSecret string `json:"sessionSecret"`
|
||||
// 家庭云
|
||||
FamilySessionKey string `json:"familySessionKey"`
|
||||
FamilySessionSecret string `json:"familySessionSecret"`
|
||||
}
|
||||
|
||||
//登录返回
|
||||
type appSessionResp struct {
|
||||
UserSessionResp
|
||||
|
||||
IsSaveName string `json:"isSaveName"`
|
||||
|
||||
// 会话刷新Token
|
||||
AccessToken string `json:"accessToken"`
|
||||
//Token刷新
|
||||
RefreshToken string `json:"refreshToken"`
|
||||
}
|
||||
|
||||
type FamilyInfoListResp struct {
|
||||
FamilyInfoResp []FamilyInfoResp `json:"familyInfoResp"`
|
||||
}
|
||||
type FamilyInfoResp struct {
|
||||
Count int `json:"count"`
|
||||
CreateTime string `json:"createTime"`
|
||||
FamilyID int `json:"familyId"`
|
||||
RemarkName string `json:"remarkName"`
|
||||
Type int `json:"type"`
|
||||
UseFlag int `json:"useFlag"`
|
||||
UserRole int `json:"userRole"`
|
||||
}
|
||||
|
||||
/*文件部分*/
|
||||
// 文件
|
||||
type Cloud189File struct {
|
||||
CreateDate string `json:"createDate"`
|
||||
FileCata int64 `json:"fileCata"`
|
||||
Icon struct {
|
||||
//iconOption 5
|
||||
SmallUrl string `json:"smallUrl"`
|
||||
LargeUrl string `json:"largeUrl"`
|
||||
|
||||
// iconOption 10
|
||||
Max600 string `json:"max600"`
|
||||
MediumURL string `json:"mediumUrl"`
|
||||
} `json:"icon"`
|
||||
ID int64 `json:"id"`
|
||||
LastOpTime string `json:"lastOpTime"`
|
||||
Md5 string `json:"md5"`
|
||||
MediaType int `json:"mediaType"`
|
||||
Name string `json:"name"`
|
||||
Orientation int64 `json:"orientation"`
|
||||
Rev string `json:"rev"`
|
||||
Size int64 `json:"size"`
|
||||
StarLabel int64 `json:"starLabel"`
|
||||
}
|
||||
|
||||
// 文件夹
|
||||
type Cloud189Folder struct {
|
||||
ID int64 `json:"id"`
|
||||
ParentID int64 `json:"parentId"`
|
||||
Name string `json:"name"`
|
||||
|
||||
FileCata int64 `json:"fileCata"`
|
||||
FileCount int64 `json:"fileCount"`
|
||||
|
||||
LastOpTime string `json:"lastOpTime"`
|
||||
CreateDate string `json:"createDate"`
|
||||
|
||||
FileListSize int64 `json:"fileListSize"`
|
||||
Rev string `json:"rev"`
|
||||
StarLabel int64 `json:"starLabel"`
|
||||
}
|
||||
|
||||
type Cloud189FilesResp struct {
|
||||
//ResCode int `json:"res_code"`
|
||||
//ResMessage string `json:"res_message"`
|
||||
FileListAO struct {
|
||||
Count int `json:"count"`
|
||||
FileList []Cloud189File `json:"fileList"`
|
||||
FolderList []Cloud189Folder `json:"folderList"`
|
||||
} `json:"fileListAO"`
|
||||
}
|
||||
|
||||
// TaskInfo 任务信息
|
||||
type BatchTaskInfo struct {
|
||||
// FileId 文件ID
|
||||
FileId string `json:"fileId"`
|
||||
// FileName 文件名
|
||||
FileName string `json:"fileName"`
|
||||
// IsFolder 是否是文件夹,0-否,1-是
|
||||
IsFolder int `json:"isFolder"`
|
||||
// SrcParentId 文件所在父目录ID
|
||||
//SrcParentId string `json:"srcParentId"`
|
||||
}
|
||||
|
||||
/*
|
||||
type CreateUploadFileResult struct {
|
||||
// UploadFileId 上传文件请求ID
|
||||
UploadFileId int64 `json:"uploadFileId"`
|
||||
// FileUploadUrl 上传文件数据的URL路径
|
||||
FileUploadUrl string `json:"fileUploadUrl"`
|
||||
// FileCommitUrl 上传文件完成后确认路径
|
||||
FileCommitUrl string `json:"fileCommitUrl"`
|
||||
// FileDataExists 文件是否已存在云盘中,0-未存在,1-已存在
|
||||
FileDataExists int `json:"fileDataExists"`
|
||||
}
|
||||
|
||||
type UploadFileStatusResult struct {
|
||||
// 上传文件的ID
|
||||
UploadFileId int64 `json:"uploadFileId"`
|
||||
// 已上传的大小
|
||||
DataSize int64 `json:"dataSize"`
|
||||
FileUploadUrl string `json:"fileUploadUrl"`
|
||||
FileCommitUrl string `json:"fileCommitUrl"`
|
||||
FileDataExists int `json:"fileDataExists"`
|
||||
}
|
||||
*/
|
||||
|
||||
type InitMultiUploadResp struct {
|
||||
//Code string `json:"code"`
|
||||
Data struct {
|
||||
UploadType int `json:"uploadType"`
|
||||
UploadHost string `json:"uploadHost"`
|
||||
UploadFileID string `json:"uploadFileId"`
|
||||
FileDataExists int `json:"fileDataExists"`
|
||||
} `json:"data"`
|
||||
}
|
||||
type UploadUrlsResp struct {
|
||||
Code string `json:"code"`
|
||||
UploadUrls map[string]Part `json:"uploadUrls"`
|
||||
}
|
||||
|
||||
type Part struct {
|
||||
RequestURL string `json:"requestURL"`
|
||||
RequestHeader string `json:"requestHeader"`
|
||||
}
|
177
drivers/189pc/util.go
Normal file
177
drivers/189pc/util.go
Normal file
@ -0,0 +1,177 @@
|
||||
package _189
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/aes"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha1"
|
||||
"crypto/x509"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
rand2 "math/rand"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Xhofe/alist/model"
|
||||
)
|
||||
|
||||
const (
|
||||
APP_ID = "8025431004"
|
||||
CLIENT_TYPE = "10020"
|
||||
VERSION = "6.2"
|
||||
|
||||
WEB_URL = "https://cloud.189.cn"
|
||||
AUTH_URL = "https://open.e.189.cn"
|
||||
API_URL = "https://api.cloud.189.cn"
|
||||
UPLOAD_URL = "https://upload.cloud.189.cn"
|
||||
|
||||
RETURN_URL = "https://m.cloud.189.cn/zhuanti/2020/loginErrorPc/index.html"
|
||||
|
||||
PC = "TELEPC"
|
||||
MAC = "TELEMAC"
|
||||
|
||||
CHANNEL_ID = "web_cloud.189.cn"
|
||||
)
|
||||
|
||||
func clientSuffix() map[string]string {
|
||||
return map[string]string{
|
||||
"clientType": PC,
|
||||
"version": VERSION,
|
||||
"channelId": CHANNEL_ID,
|
||||
"rand": fmt.Sprintf("%d_%d", rand2.Int63n(1e5), rand2.Int63n(1e10)),
|
||||
}
|
||||
}
|
||||
|
||||
// 带params的SignatureOfHmac HMAC签名
|
||||
func signatureOfHmac(sessionSecret, sessionKey, operate, fullUrl, dateOfGmt, param string) string {
|
||||
u, _ := url.Parse(fullUrl)
|
||||
mac := hmac.New(sha1.New, []byte(sessionSecret))
|
||||
data := fmt.Sprintf("SessionKey=%s&Operate=%s&RequestURI=%s&Date=%s", sessionKey, operate, u.Path, dateOfGmt)
|
||||
if param != "" {
|
||||
data += fmt.Sprintf("¶ms=%s", param)
|
||||
}
|
||||
mac.Write([]byte(data))
|
||||
return strings.ToUpper(hex.EncodeToString(mac.Sum(nil)))
|
||||
}
|
||||
|
||||
// 获取http规范的时间
|
||||
func getHttpDateStr() string {
|
||||
return time.Now().UTC().Format(http.TimeFormat)
|
||||
}
|
||||
|
||||
// RAS 加密用户名密码
|
||||
func rsaEncrypt(publicKey, origData string) string {
|
||||
block, _ := pem.Decode([]byte(publicKey))
|
||||
pubInterface, _ := x509.ParsePKIXPublicKey(block.Bytes)
|
||||
data, _ := rsa.EncryptPKCS1v15(rand.Reader, pubInterface.(*rsa.PublicKey), []byte(origData))
|
||||
return base64ToHex(base64.StdEncoding.EncodeToString(data))
|
||||
}
|
||||
|
||||
// aes 加密params
|
||||
func AesECBEncrypt(data, key string) string {
|
||||
block, _ := aes.NewCipher([]byte(key))
|
||||
paddingData := PKCS7Padding([]byte(data), block.BlockSize())
|
||||
decrypted := make([]byte, len(paddingData))
|
||||
size := block.BlockSize()
|
||||
for src, dst := paddingData, decrypted; len(src) > 0; src, dst = src[size:], dst[size:] {
|
||||
block.Encrypt(dst[:size], src[:size])
|
||||
}
|
||||
return strings.ToUpper(hex.EncodeToString(decrypted))
|
||||
}
|
||||
|
||||
func PKCS7Padding(ciphertext []byte, blockSize int) []byte {
|
||||
padding := blockSize - len(ciphertext)%blockSize
|
||||
padtext := bytes.Repeat([]byte{byte(padding)}, padding)
|
||||
return append(ciphertext, padtext...)
|
||||
}
|
||||
|
||||
// 时间戳
|
||||
func timestamp() int64 {
|
||||
return time.Now().UTC().UnixNano() / 1e6
|
||||
}
|
||||
|
||||
func base64ToHex(a string) string {
|
||||
v, _ := base64.StdEncoding.DecodeString(a)
|
||||
return strings.ToUpper(hex.EncodeToString(v))
|
||||
}
|
||||
|
||||
func isFamily(account *model.Account) bool {
|
||||
return account.InternalType == "Family"
|
||||
}
|
||||
|
||||
func toFamilyOrderBy(o string) string {
|
||||
switch o {
|
||||
case "filename":
|
||||
return "1"
|
||||
case "filesize":
|
||||
return "2"
|
||||
case "lastOpTime":
|
||||
return "3"
|
||||
default:
|
||||
return "1"
|
||||
}
|
||||
}
|
||||
|
||||
func ParseHttpHeader(str string) map[string]string {
|
||||
header := make(map[string]string)
|
||||
for _, value := range strings.Split(str, "&") {
|
||||
i := strings.Index(value, "=")
|
||||
header[strings.TrimSpace(value[0:i])] = strings.TrimSpace(value[i+1:])
|
||||
}
|
||||
return header
|
||||
}
|
||||
|
||||
func MustString(str string, err error) string {
|
||||
return str
|
||||
}
|
||||
|
||||
func MustToBytes(b []byte, err error) []byte {
|
||||
return b
|
||||
}
|
||||
|
||||
func BoolToNumber(b bool) int {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func MustParseTime(str string) *time.Time {
|
||||
loc, _ := time.LoadLocation("Local")
|
||||
lastOpTime, _ := time.ParseInLocation("2006-01-02 15:04:05", str, loc)
|
||||
return &lastOpTime
|
||||
}
|
||||
|
||||
type Params map[string]string
|
||||
|
||||
func (p Params) Set(k, v string) {
|
||||
p[k] = v
|
||||
}
|
||||
|
||||
func (p Params) Encode() string {
|
||||
if p == nil {
|
||||
return ""
|
||||
}
|
||||
var buf strings.Builder
|
||||
keys := make([]string, 0, len(p))
|
||||
for k := range p {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
if buf.Len() > 0 {
|
||||
buf.WriteByte('&')
|
||||
}
|
||||
buf.WriteString(k)
|
||||
buf.WriteByte('=')
|
||||
buf.WriteString(p[k])
|
||||
}
|
||||
return buf.String()
|
||||
}
|
@ -3,44 +3,17 @@ package alidrive
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/go-resty/resty/v2"
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
var aliClient = resty.New()
|
||||
|
||||
type AliRespError struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type AliFiles struct {
|
||||
Items []AliFile `json:"items"`
|
||||
NextMarker string `json:"next_marker"`
|
||||
}
|
||||
|
||||
type AliFile struct {
|
||||
DriveId string `json:"drive_id"`
|
||||
CreatedAt *time.Time `json:"created_at"`
|
||||
FileExtension string `json:"file_extension"`
|
||||
FileId string `json:"file_id"`
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Category string `json:"category"`
|
||||
ParentFileId string `json:"parent_file_id"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
Size int64 `json:"size"`
|
||||
Thumbnail string `json:"thumbnail"`
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
func (driver AliDrive) FormatFile(file *AliFile) *model.File {
|
||||
f := &model.File{
|
||||
Id: file.FileId,
|
||||
@ -51,17 +24,7 @@ func (driver AliDrive) FormatFile(file *AliFile) *model.File {
|
||||
Driver: driver.Config().Name,
|
||||
Url: file.Url,
|
||||
}
|
||||
if file.Type == "folder" {
|
||||
f.Type = conf.FOLDER
|
||||
} else {
|
||||
f.Type = utils.GetFileType(file.FileExtension)
|
||||
}
|
||||
if file.Category == "video" {
|
||||
f.Type = conf.VIDEO
|
||||
}
|
||||
if file.Category == "image" {
|
||||
f.Type = conf.IMAGE
|
||||
}
|
||||
f.Type = file.GetType()
|
||||
return f
|
||||
}
|
||||
|
||||
@ -190,7 +153,7 @@ func (driver AliDrive) rename(fileId, name string, account *model.Account) error
|
||||
return fmt.Errorf("%+v", resp)
|
||||
}
|
||||
|
||||
func (driver AliDrive) batch(srcId, dstId string, account *model.Account) error {
|
||||
func (driver AliDrive) batch(srcId, dstId string, url string, account *model.Account) error {
|
||||
var e AliRespError
|
||||
res, err := aliClient.R().SetError(&e).
|
||||
SetHeader("authorization", "Bearer\t"+account.AccessToken).
|
||||
@ -208,6 +171,7 @@ func (driver AliDrive) batch(srcId, dstId string, account *model.Account) error
|
||||
"to_drive_id": account.DriveId,
|
||||
"to_parent_file_id": dstId,
|
||||
},
|
||||
"url": url,
|
||||
},
|
||||
},
|
||||
"resource": "file",
|
||||
@ -222,12 +186,13 @@ func (driver AliDrive) batch(srcId, dstId string, account *model.Account) error
|
||||
return err
|
||||
} else {
|
||||
_ = model.SaveAccount(account)
|
||||
return driver.batch(srcId, dstId, account)
|
||||
return driver.batch(srcId, dstId, url, account)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("%s", e.Message)
|
||||
}
|
||||
if strings.Contains(res.String(), `"status":200`) {
|
||||
status := jsoniter.Get(res.Body(), "responses", 0, "status").ToInt()
|
||||
if status < 400 && status >= 100 {
|
||||
return nil
|
||||
}
|
||||
return errors.New(res.String())
|
||||
|
@ -2,18 +2,25 @@ package alidrive
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha1"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"math"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/robfig/cron/v3"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"io"
|
||||
"math"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type AliDrive struct{}
|
||||
@ -59,6 +66,11 @@ func (driver AliDrive) Items() []base.Item {
|
||||
Required: false,
|
||||
Description: ">0 and <=200",
|
||||
},
|
||||
{
|
||||
Name: "bool_1",
|
||||
Label: "fast upload",
|
||||
Type: base.TypeBool,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -87,15 +99,15 @@ func (driver AliDrive) Save(account *model.Account, old *model.Account) error {
|
||||
log.Debugf("user info: %+v", resp)
|
||||
account.DriveId = resp["default_drive_id"].(string)
|
||||
cronId, err := conf.Cron.AddFunc("@every 2h", func() {
|
||||
name := account.Name
|
||||
log.Debugf("ali account name: %s", name)
|
||||
newAccount, ok := model.GetAccount(name)
|
||||
id := account.ID
|
||||
log.Debugf("ali account id: %d", id)
|
||||
newAccount, err := model.GetAccountById(id)
|
||||
log.Debugf("ali account: %+v", newAccount)
|
||||
if !ok {
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = driver.RefreshToken(&newAccount)
|
||||
_ = model.SaveAccount(&newAccount)
|
||||
err = driver.RefreshToken(newAccount)
|
||||
_ = model.SaveAccount(newAccount)
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
@ -309,7 +321,7 @@ func (driver AliDrive) Move(src string, dst string, account *model.Account) erro
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = driver.batch(srcFile.Id, dstDirFile.Id, account)
|
||||
err = driver.batch(srcFile.Id, dstDirFile.Id, "/file/move", account)
|
||||
return err
|
||||
}
|
||||
|
||||
@ -324,7 +336,17 @@ func (driver AliDrive) Rename(src string, dst string, account *model.Account) er
|
||||
}
|
||||
|
||||
func (driver AliDrive) Copy(src string, dst string, account *model.Account) error {
|
||||
return base.ErrNotSupport
|
||||
dstDir, _ := filepath.Split(dst)
|
||||
srcFile, err := driver.File(src, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dstDirFile, err := driver.File(dstDir, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = driver.batch(srcFile.Id, dstDirFile.Id, "/file/copy", account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver AliDrive) Delete(path string, account *model.Account) error {
|
||||
@ -354,7 +376,7 @@ func (driver AliDrive) Delete(path string, account *model.Account) error {
|
||||
}
|
||||
return fmt.Errorf("%s", e.Message)
|
||||
}
|
||||
if res.StatusCode() == 204 {
|
||||
if res.StatusCode() < 400 {
|
||||
return nil
|
||||
}
|
||||
return errors.New(res.String())
|
||||
@ -366,15 +388,15 @@ type UploadResp struct {
|
||||
PartInfoList []struct {
|
||||
UploadUrl string `json:"upload_url"`
|
||||
} `json:"part_info_list"`
|
||||
|
||||
RapidUpload bool `json:"rapid_upload"`
|
||||
}
|
||||
|
||||
func (driver AliDrive) Upload(file *model.FileStream, account *model.Account) error {
|
||||
if file == nil {
|
||||
return base.ErrEmptyFile
|
||||
}
|
||||
const DEFAULT uint64 = 10485760
|
||||
var count = int64(math.Ceil(float64(file.GetSize()) / float64(DEFAULT)))
|
||||
var finish uint64 = 0
|
||||
|
||||
parentFile, err := driver.File(file.ParentPath, account)
|
||||
if err != nil {
|
||||
return err
|
||||
@ -382,32 +404,51 @@ func (driver AliDrive) Upload(file *model.FileStream, account *model.Account) er
|
||||
if !parentFile.IsDir() {
|
||||
return base.ErrNotFolder
|
||||
}
|
||||
|
||||
const DEFAULT int64 = 10485760
|
||||
var count = int(math.Ceil(float64(file.GetSize()) / float64(DEFAULT)))
|
||||
|
||||
partInfoList := make([]base.Json, 0, count)
|
||||
for i := 1; i <= count; i++ {
|
||||
partInfoList = append(partInfoList, base.Json{"part_number": i})
|
||||
}
|
||||
|
||||
reqBody := base.Json{
|
||||
"check_name_mode": "overwrite",
|
||||
"drive_id": account.DriveId,
|
||||
"name": file.GetFileName(),
|
||||
"parent_file_id": parentFile.Id,
|
||||
"part_info_list": partInfoList,
|
||||
"size": file.GetSize(),
|
||||
"type": "file",
|
||||
}
|
||||
|
||||
if account.Bool1 {
|
||||
buf := bytes.NewBuffer(make([]byte, 0, 1024))
|
||||
io.CopyN(buf, file, 1024)
|
||||
reqBody["pre_hash"] = utils.GetSHA1Encode(buf.String())
|
||||
// 把头部拼接回去
|
||||
file.File = struct {
|
||||
io.Reader
|
||||
io.Closer
|
||||
}{
|
||||
Reader: io.MultiReader(buf, file.File),
|
||||
Closer: file.File,
|
||||
}
|
||||
} else {
|
||||
reqBody["content_hash_name"] = "none"
|
||||
reqBody["proof_version"] = "v1"
|
||||
}
|
||||
|
||||
var resp UploadResp
|
||||
var e AliRespError
|
||||
partInfoList := make([]base.Json, 0)
|
||||
var i int64
|
||||
for i = 0; i < count; i++ {
|
||||
partInfoList = append(partInfoList, base.Json{
|
||||
"part_number": i + 1,
|
||||
})
|
||||
client := aliClient.R().SetResult(&resp).SetError(&e).SetHeader("authorization", "Bearer\t"+account.AccessToken).SetBody(reqBody)
|
||||
|
||||
_, err = client.Post("https://api.aliyundrive.com/adrive/v2/file/createWithFolders")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = aliClient.R().SetResult(&resp).SetError(&e).
|
||||
SetHeader("authorization", "Bearer\t"+account.AccessToken).
|
||||
SetBody(base.Json{
|
||||
"check_name_mode": "auto_rename",
|
||||
// content_hash
|
||||
"content_hash_name": "none",
|
||||
"drive_id": account.DriveId,
|
||||
"name": file.GetFileName(),
|
||||
"parent_file_id": parentFile.Id,
|
||||
"part_info_list": partInfoList,
|
||||
//proof_code
|
||||
"proof_version": "v1",
|
||||
"size": file.GetSize(),
|
||||
"type": "file",
|
||||
}).Post("https://api.aliyundrive.com/adrive/v2/file/createWithFolders") // /v2/file/create_with_proof
|
||||
//log.Debugf("%+v\n%+v", resp, e)
|
||||
if e.Code != "" {
|
||||
if e.Code != "" && e.Code != "PreHashMatched" {
|
||||
if e.Code == "AccessTokenInvalid" {
|
||||
err = driver.RefreshToken(account)
|
||||
if err != nil {
|
||||
@ -419,26 +460,63 @@ func (driver AliDrive) Upload(file *model.FileStream, account *model.Account) er
|
||||
}
|
||||
return fmt.Errorf("%s", e.Message)
|
||||
}
|
||||
var byteSize uint64
|
||||
for i = 0; i < count; i++ {
|
||||
byteSize = file.GetSize() - finish
|
||||
if DEFAULT < byteSize {
|
||||
byteSize = DEFAULT
|
||||
}
|
||||
log.Debugf("%d,%d", byteSize, finish)
|
||||
byteData := make([]byte, byteSize)
|
||||
n, err := io.ReadFull(file, byteData)
|
||||
//n, err := file.Read(byteData)
|
||||
//byteData, err := io.ReadAll(file)
|
||||
//n := len(byteData)
|
||||
log.Debug(err, n)
|
||||
|
||||
if account.Bool1 && e.Code == "PreHashMatched" {
|
||||
tempFile, err := ioutil.TempFile(conf.Conf.TempDir, "file-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
finish += uint64(n)
|
||||
defer func() {
|
||||
_ = tempFile.Close()
|
||||
_ = os.Remove(tempFile.Name())
|
||||
}()
|
||||
|
||||
req, err := http.NewRequest("PUT", resp.PartInfoList[i].UploadUrl, bytes.NewBuffer(byteData))
|
||||
delete(reqBody, "pre_hash")
|
||||
h := sha1.New()
|
||||
if _, err = io.Copy(io.MultiWriter(tempFile, h), file.File); err != nil {
|
||||
return err
|
||||
}
|
||||
reqBody["content_hash"] = hex.EncodeToString(h.Sum(nil))
|
||||
reqBody["content_hash_name"] = "sha1"
|
||||
reqBody["proof_version"] = "v1"
|
||||
|
||||
/*
|
||||
js 隐性转换太坑不知道有没有bug
|
||||
var n = e.access_token,
|
||||
r = new BigNumber('0x'.concat(md5(n).slice(0, 16))),
|
||||
i = new BigNumber(t.file.size),
|
||||
o = i ? r.mod(i) : new gt.BigNumber(0);
|
||||
(t.file.slice(o.toNumber(), Math.min(o.plus(8).toNumber(), t.file.size)))
|
||||
*/
|
||||
buf := make([]byte, 8)
|
||||
r, _ := new(big.Int).SetString(utils.GetMD5Encode(account.AccessToken)[:16], 16)
|
||||
i := new(big.Int).SetUint64(file.Size)
|
||||
o := r.Mod(r, i)
|
||||
n, _ := io.NewSectionReader(tempFile, o.Int64(), 8).Read(buf[:8])
|
||||
reqBody["proof_code"] = base64.StdEncoding.EncodeToString(buf[:n])
|
||||
|
||||
_, err = client.Post("https://api.aliyundrive.com/adrive/v2/file/createWithFolders")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if e.Code != "" && e.Code != "PreHashMatched" {
|
||||
return fmt.Errorf("%s", e.Message)
|
||||
}
|
||||
|
||||
if resp.RapidUpload {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 秒传失败
|
||||
if _, err = tempFile.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
file.File = tempFile
|
||||
}
|
||||
|
||||
for _, partInfo := range resp.PartInfoList {
|
||||
req, err := http.NewRequest("PUT", partInfo.UploadUrl, io.LimitReader(file.File, DEFAULT))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@ -447,6 +525,7 @@ func (driver AliDrive) Upload(file *model.FileStream, account *model.Account) er
|
||||
return err
|
||||
}
|
||||
log.Debugf("%+v", res)
|
||||
res.Body.Close()
|
||||
//res, err := base.BaseClient.R().
|
||||
// SetHeader("Content-Type","").
|
||||
// SetBody(byteData).Put(resp.PartInfoList[i].UploadUrl)
|
||||
@ -463,7 +542,10 @@ func (driver AliDrive) Upload(file *model.FileStream, account *model.Account) er
|
||||
"file_id": resp.FileId,
|
||||
"upload_id": resp.UploadId,
|
||||
}).Post("https://api.aliyundrive.com/v2/file/complete")
|
||||
if e.Code != "" {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if e.Code != "" && e.Code != "PreHashMatched" {
|
||||
//if e.Code == "AccessTokenInvalid" {
|
||||
// err = driver.RefreshToken(account)
|
||||
// if err != nil {
|
||||
|
53
drivers/alidrive/types.go
Normal file
53
drivers/alidrive/types.go
Normal file
@ -0,0 +1,53 @@
|
||||
package alidrive
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"time"
|
||||
)
|
||||
|
||||
type AliRespError struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type AliFiles struct {
|
||||
Items []AliFile `json:"items"`
|
||||
NextMarker string `json:"next_marker"`
|
||||
}
|
||||
|
||||
type AliFile struct {
|
||||
DriveId string `json:"drive_id"`
|
||||
CreatedAt *time.Time `json:"created_at"`
|
||||
FileExtension string `json:"file_extension"`
|
||||
FileId string `json:"file_id"`
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name"`
|
||||
Category string `json:"category"`
|
||||
ParentFileId string `json:"parent_file_id"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
Size int64 `json:"size"`
|
||||
Thumbnail string `json:"thumbnail"`
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
func (f AliFile) GetSize() uint64 {
|
||||
return uint64(f.Size)
|
||||
}
|
||||
|
||||
func (f AliFile) GetName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
func (f AliFile) GetType() int {
|
||||
if f.Type == "folder" {
|
||||
return conf.FOLDER
|
||||
}
|
||||
if f.Category == "video" {
|
||||
return conf.VIDEO
|
||||
}
|
||||
if f.Category == "image" {
|
||||
return conf.IMAGE
|
||||
}
|
||||
return utils.GetFileType(f.FileExtension)
|
||||
}
|
@ -4,6 +4,7 @@ import (
|
||||
_ "github.com/Xhofe/alist/drivers/123"
|
||||
_ "github.com/Xhofe/alist/drivers/139"
|
||||
_ "github.com/Xhofe/alist/drivers/189"
|
||||
_ "github.com/Xhofe/alist/drivers/189pc"
|
||||
_ "github.com/Xhofe/alist/drivers/alidrive"
|
||||
_ "github.com/Xhofe/alist/drivers/alist"
|
||||
_ "github.com/Xhofe/alist/drivers/baidu"
|
||||
@ -17,10 +18,14 @@ import (
|
||||
_ "github.com/Xhofe/alist/drivers/pikpak"
|
||||
_ "github.com/Xhofe/alist/drivers/quark"
|
||||
_ "github.com/Xhofe/alist/drivers/s3"
|
||||
_ "github.com/Xhofe/alist/drivers/sftp"
|
||||
_ "github.com/Xhofe/alist/drivers/shandian"
|
||||
_ "github.com/Xhofe/alist/drivers/teambition"
|
||||
_ "github.com/Xhofe/alist/drivers/uss"
|
||||
_ "github.com/Xhofe/alist/drivers/webdav"
|
||||
_ "github.com/Xhofe/alist/drivers/xunlei"
|
||||
_ "github.com/Xhofe/alist/drivers/yandex"
|
||||
_ "github.com/Xhofe/alist/drivers/baiduphoto"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"strings"
|
||||
)
|
||||
|
@ -48,8 +48,7 @@ func (driver Baidu) refreshToken(account *model.Account) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (driver Baidu) Request(pathname string, method int, headers, query, form map[string]string, data interface{}, resp interface{}, account *model.Account) ([]byte, error) {
|
||||
u := "https://pan.baidu.com/rest/2.0" + pathname
|
||||
func (driver Baidu) Request(fullurl string, method int, headers, query, form map[string]string, data interface{}, resp interface{}, account *model.Account) ([]byte, error) {
|
||||
req := base.RestyClient.R()
|
||||
req.SetQueryParam("access_token", account.AccessToken)
|
||||
if headers != nil {
|
||||
@ -71,15 +70,15 @@ func (driver Baidu) Request(pathname string, method int, headers, query, form ma
|
||||
var err error
|
||||
switch method {
|
||||
case base.Get:
|
||||
res, err = req.Get(u)
|
||||
res, err = req.Get(fullurl)
|
||||
case base.Post:
|
||||
res, err = req.Post(u)
|
||||
res, err = req.Post(fullurl)
|
||||
case base.Patch:
|
||||
res, err = req.Patch(u)
|
||||
res, err = req.Patch(fullurl)
|
||||
case base.Delete:
|
||||
res, err = req.Delete(u)
|
||||
res, err = req.Delete(fullurl)
|
||||
case base.Put:
|
||||
res, err = req.Put(u)
|
||||
res, err = req.Put(fullurl)
|
||||
default:
|
||||
return nil, base.ErrNotSupport
|
||||
}
|
||||
@ -94,7 +93,7 @@ func (driver Baidu) Request(pathname string, method int, headers, query, form ma
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return driver.Request(pathname, method, headers, query, form, data, resp, account)
|
||||
return driver.Request(fullurl, method, headers, query, form, data, resp, account)
|
||||
}
|
||||
return nil, fmt.Errorf("errno: %d, refer to https://pan.baidu.com/union/doc/", errno)
|
||||
}
|
||||
@ -102,11 +101,11 @@ func (driver Baidu) Request(pathname string, method int, headers, query, form ma
|
||||
}
|
||||
|
||||
func (driver Baidu) Get(pathname string, params map[string]string, resp interface{}, account *model.Account) ([]byte, error) {
|
||||
return driver.Request(pathname, base.Get, nil, params, nil, nil, resp, account)
|
||||
return driver.Request("https://pan.baidu.com/rest/2.0"+pathname, base.Get, nil, params, nil, nil, resp, account)
|
||||
}
|
||||
|
||||
func (driver Baidu) Post(pathname string, params map[string]string, data interface{}, resp interface{}, account *model.Account) ([]byte, error) {
|
||||
return driver.Request(pathname, base.Post, nil, params, nil, data, resp, account)
|
||||
return driver.Request("https://pan.baidu.com/rest/2.0"+pathname, base.Post, nil, params, nil, data, resp, account)
|
||||
}
|
||||
|
||||
func (driver Baidu) manage(opera string, filelist interface{}, account *model.Account) ([]byte, error) {
|
||||
|
@ -58,6 +58,14 @@ func (driver Baidu) Items() []base.Item {
|
||||
Default: "asc",
|
||||
Required: false,
|
||||
},
|
||||
{
|
||||
Name: "internal_type",
|
||||
Label: "download api",
|
||||
Type: base.TypeSelect,
|
||||
Required: true,
|
||||
Values: "official,crack",
|
||||
Default: "official",
|
||||
},
|
||||
{
|
||||
Name: "client_id",
|
||||
Label: "client id",
|
||||
@ -76,6 +84,9 @@ func (driver Baidu) Items() []base.Item {
|
||||
}
|
||||
|
||||
func (driver Baidu) Save(account *model.Account, old *model.Account) error {
|
||||
if account == nil {
|
||||
return nil
|
||||
}
|
||||
return driver.RefreshToken(account)
|
||||
}
|
||||
|
||||
@ -122,6 +133,13 @@ func (driver Baidu) Files(path string, account *model.Account) ([]model.File, er
|
||||
}
|
||||
|
||||
func (driver Baidu) Link(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
if account.InternalType == "crack" {
|
||||
return driver.LinkCrack(args, account)
|
||||
}
|
||||
return driver.LinkOfficial(args, account)
|
||||
}
|
||||
|
||||
func (driver Baidu) LinkOfficial(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
file, err := driver.File(args.Path, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@ -154,6 +172,32 @@ func (driver Baidu) Link(args base.Args, account *model.Account) (*base.Link, er
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (driver Baidu) LinkCrack(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
file, err := driver.File(args.Path, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if file.IsDir() {
|
||||
return nil, base.ErrNotFile
|
||||
}
|
||||
var resp DownloadResp2
|
||||
param := map[string]string{
|
||||
"target": fmt.Sprintf("[\"%s\"]", utils.Join(account.RootFolder, args.Path)),
|
||||
"dlink": "1",
|
||||
"web": "5",
|
||||
"origin": "dlna",
|
||||
}
|
||||
_, err = driver.Request("https://pan.baidu.com/api/filemetas", base.Get, nil, param, nil, nil, &resp, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &base.Link{
|
||||
Url: resp.Info[0].Dlink,
|
||||
Headers: []base.Header{
|
||||
{Name: "User-Agent", Value: "pan.baidu.com"},
|
||||
}}, nil
|
||||
}
|
||||
|
||||
func (driver Baidu) Path(path string, account *model.Account) (*model.File, []model.File, error) {
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
|
@ -74,6 +74,65 @@ type DownloadResp struct {
|
||||
RequestId string `json:"request_id"`
|
||||
}
|
||||
|
||||
type DownloadResp2 struct {
|
||||
Errno int `json:"errno"`
|
||||
Info []struct {
|
||||
//ExtentTinyint4 int `json:"extent_tinyint4"`
|
||||
//ExtentTinyint1 int `json:"extent_tinyint1"`
|
||||
//Bitmap string `json:"bitmap"`
|
||||
//Category int `json:"category"`
|
||||
//Isdir int `json:"isdir"`
|
||||
//Videotag int `json:"videotag"`
|
||||
Dlink string `json:"dlink"`
|
||||
//OperID int64 `json:"oper_id"`
|
||||
//PathMd5 int `json:"path_md5"`
|
||||
//Wpfile int `json:"wpfile"`
|
||||
//LocalMtime int `json:"local_mtime"`
|
||||
/*Thumbs struct {
|
||||
Icon string `json:"icon"`
|
||||
URL3 string `json:"url3"`
|
||||
URL2 string `json:"url2"`
|
||||
URL1 string `json:"url1"`
|
||||
} `json:"thumbs"`*/
|
||||
//PlaySource int `json:"play_source"`
|
||||
//Share int `json:"share"`
|
||||
//FileKey string `json:"file_key"`
|
||||
//Errno int `json:"errno"`
|
||||
//LocalCtime int `json:"local_ctime"`
|
||||
//Rotate int `json:"rotate"`
|
||||
//Metadata time.Time `json:"metadata"`
|
||||
//Height int `json:"height"`
|
||||
//SampleRate int `json:"sample_rate"`
|
||||
//Width int `json:"width"`
|
||||
//OwnerType int `json:"owner_type"`
|
||||
//Privacy int `json:"privacy"`
|
||||
//ExtentInt3 int64 `json:"extent_int3"`
|
||||
//RealCategory string `json:"real_category"`
|
||||
//SrcLocation string `json:"src_location"`
|
||||
//MetaInfo string `json:"meta_info"`
|
||||
//ID string `json:"id"`
|
||||
//Duration int `json:"duration"`
|
||||
//FileSize string `json:"file_size"`
|
||||
//Channels int `json:"channels"`
|
||||
//UseSegment int `json:"use_segment"`
|
||||
//ServerCtime int `json:"server_ctime"`
|
||||
//Resolution string `json:"resolution"`
|
||||
//OwnerID int `json:"owner_id"`
|
||||
//ExtraInfo string `json:"extra_info"`
|
||||
//Size int `json:"size"`
|
||||
//FsID int64 `json:"fs_id"`
|
||||
//ExtentTinyint3 int `json:"extent_tinyint3"`
|
||||
//Md5 string `json:"md5"`
|
||||
//Path string `json:"path"`
|
||||
//FrameRate int `json:"frame_rate"`
|
||||
//ExtentTinyint2 int `json:"extent_tinyint2"`
|
||||
//ServerFilename string `json:"server_filename"`
|
||||
//ServerMtime int `json:"server_mtime"`
|
||||
//TkbindID int `json:"tkbind_id"`
|
||||
} `json:"info"`
|
||||
RequestID int64 `json:"request_id"`
|
||||
}
|
||||
|
||||
type PrecreateResp struct {
|
||||
Path string `json:"path"`
|
||||
Uploadid string `json:"uploadid"`
|
||||
|
259
drivers/baiduphoto/baidu.go
Normal file
259
drivers/baiduphoto/baidu.go
Normal file
@ -0,0 +1,259 @@
|
||||
package baiduphoto
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/go-resty/resty/v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
func (driver Baidu) RefreshToken(account *model.Account) error {
|
||||
err := driver.refreshToken(account)
|
||||
if err != nil && err == base.ErrEmptyToken {
|
||||
err = driver.refreshToken(account)
|
||||
}
|
||||
if err != nil {
|
||||
account.Status = err.Error()
|
||||
}
|
||||
_ = model.SaveAccount(account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver Baidu) refreshToken(account *model.Account) error {
|
||||
u := "https://openapi.baidu.com/oauth/2.0/token"
|
||||
var resp base.TokenResp
|
||||
var e TokenErrResp
|
||||
_, err := base.RestyClient.R().
|
||||
SetResult(&resp).
|
||||
SetError(&e).
|
||||
SetQueryParams(map[string]string{
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": account.RefreshToken,
|
||||
"client_id": account.ClientId,
|
||||
"client_secret": account.ClientSecret,
|
||||
}).Get(u)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if e.ErrorMsg != "" {
|
||||
return &e
|
||||
}
|
||||
if resp.RefreshToken == "" {
|
||||
return base.ErrEmptyToken
|
||||
}
|
||||
account.Status = "work"
|
||||
account.AccessToken, account.RefreshToken = resp.AccessToken, resp.RefreshToken
|
||||
return nil
|
||||
}
|
||||
|
||||
func (driver Baidu) Request(method string, url string, callback func(*resty.Request), account *model.Account) (*resty.Response, error) {
|
||||
req := base.RestyClient.R()
|
||||
req.SetQueryParam("access_token", account.AccessToken)
|
||||
if callback != nil {
|
||||
callback(req)
|
||||
}
|
||||
|
||||
res, err := req.Execute(method, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Debug(res.String())
|
||||
|
||||
var erron Erron
|
||||
if err = utils.Json.Unmarshal(res.Body(), &erron); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch erron.Errno {
|
||||
case 0:
|
||||
return res, nil
|
||||
case -6:
|
||||
if err = driver.RefreshToken(account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("errno: %d, refer to https://photo.baidu.com/union/doc", erron.Errno)
|
||||
}
|
||||
return driver.Request(method, url, callback, account)
|
||||
}
|
||||
|
||||
// 获取所有根文件
|
||||
func (driver Baidu) GetAllFile(account *model.Account) (files []File, err error) {
|
||||
var cursor string
|
||||
|
||||
for {
|
||||
var resp FileListResp
|
||||
_, err = driver.Request(http.MethodGet, FILE_API_URL_V1+"/list", func(r *resty.Request) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"need_thumbnail": "1",
|
||||
"need_filter_hidden": "0",
|
||||
"cursor": cursor,
|
||||
})
|
||||
r.SetResult(&resp)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
cursor = resp.Cursor
|
||||
files = append(files, resp.List...)
|
||||
|
||||
if !resp.HasNextPage() {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取所有相册
|
||||
func (driver Baidu) GetAllAlbum(account *model.Account) (albums []Album, err error) {
|
||||
var cursor string
|
||||
for {
|
||||
var resp AlbumListResp
|
||||
_, err = driver.Request(http.MethodGet, ALBUM_API_URL+"/list", func(r *resty.Request) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"need_amount": "1",
|
||||
"limit": "100",
|
||||
"cursor": cursor,
|
||||
})
|
||||
r.SetResult(&resp)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if albums == nil {
|
||||
albums = make([]Album, 0, resp.TotalCount)
|
||||
}
|
||||
|
||||
cursor = resp.Cursor
|
||||
albums = append(albums, resp.List...)
|
||||
|
||||
if !resp.HasNextPage() {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取相册中所有文件
|
||||
func (driver Baidu) GetAllAlbumFile(albumID string, account *model.Account) (files []AlbumFile, err error) {
|
||||
var cursor string
|
||||
for {
|
||||
var resp AlbumFileListResp
|
||||
_, err = driver.Request(http.MethodGet, ALBUM_API_URL+"/listfile", func(r *resty.Request) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"album_id": splitID(albumID)[0],
|
||||
"need_amount": "1",
|
||||
"limit": "1000",
|
||||
"cursor": cursor,
|
||||
})
|
||||
r.SetResult(&resp)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if files == nil {
|
||||
files = make([]AlbumFile, 0, resp.TotalCount)
|
||||
}
|
||||
|
||||
cursor = resp.Cursor
|
||||
files = append(files, resp.List...)
|
||||
|
||||
if !resp.HasNextPage() {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 创建相册
|
||||
func (driver Baidu) CreateAlbum(name string, account *model.Account) error {
|
||||
if !checkName(name) {
|
||||
return ErrNotSupportName
|
||||
}
|
||||
_, err := driver.Request(http.MethodPost, ALBUM_API_URL+"/create", func(r *resty.Request) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"title": name,
|
||||
"tid": getTid(),
|
||||
"source": "0",
|
||||
})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
// 相册改名
|
||||
func (driver Baidu) SetAlbumName(albumID string, name string, account *model.Account) error {
|
||||
if !checkName(name) {
|
||||
return ErrNotSupportName
|
||||
}
|
||||
|
||||
e := splitID(albumID)
|
||||
_, err := driver.Request(http.MethodPost, ALBUM_API_URL+"/settitle", func(r *resty.Request) {
|
||||
r.SetFormData(map[string]string{
|
||||
"title": name,
|
||||
"album_id": e[0],
|
||||
"tid": e[1],
|
||||
})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
// 删除相册
|
||||
func (driver Baidu) DeleteAlbum(albumID string, account *model.Account) error {
|
||||
e := splitID(albumID)
|
||||
_, err := driver.Request(http.MethodPost, ALBUM_API_URL+"/delete", func(r *resty.Request) {
|
||||
r.SetFormData(map[string]string{
|
||||
"album_id": e[0],
|
||||
"tid": e[1],
|
||||
"delete_origin_image": "0", // 是否删除原图 0 不删除
|
||||
})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
// 删除相册文件
|
||||
func (driver Baidu) DeleteAlbumFile(albumID string, account *model.Account, fileIDs ...string) error {
|
||||
e := splitID(albumID)
|
||||
_, err := driver.Request(http.MethodPost, ALBUM_API_URL+"/delfile", func(r *resty.Request) {
|
||||
r.SetFormData(map[string]string{
|
||||
"album_id": e[0],
|
||||
"tid": e[1],
|
||||
"list": fsidsFormat(fileIDs...),
|
||||
"del_origin": "0", // 是否删除原图 0 不删除 1 删除
|
||||
})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
// 增加相册文件
|
||||
func (driver Baidu) AddAlbumFile(albumID string, account *model.Account, fileIDs ...string) error {
|
||||
e := splitID(albumID)
|
||||
_, err := driver.Request(http.MethodGet, ALBUM_API_URL+"/addfile", func(r *resty.Request) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"album_id": e[0],
|
||||
"tid": e[1],
|
||||
"list": fsidsFormatNotUk(fileIDs...),
|
||||
})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
// 保存相册文件为根文件
|
||||
func (driver Baidu) CopyAlbumFile(albumID string, account *model.Account, fileID string) (*CopyFile, error) {
|
||||
var resp CopyFileResp
|
||||
e := splitID(fileID)
|
||||
_, err := driver.Request(http.MethodPost, ALBUM_API_URL+"/copyfile", func(r *resty.Request) {
|
||||
r.SetFormData(map[string]string{
|
||||
"album_id": splitID(albumID)[0],
|
||||
"tid": e[2],
|
||||
"uk": e[1],
|
||||
"list": fsidsFormatNotUk(fileID),
|
||||
})
|
||||
r.SetResult(&resp)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resp.List[0], err
|
||||
}
|
502
drivers/baiduphoto/driver.go
Normal file
502
drivers/baiduphoto/driver.go
Normal file
@ -0,0 +1,502 @@
|
||||
package baiduphoto
|
||||
|
||||
import (
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"math"
|
||||
"net/http"
|
||||
"os"
|
||||
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
type Baidu struct{}
|
||||
|
||||
func init() {
|
||||
base.RegisterDriver(new(Baidu))
|
||||
}
|
||||
|
||||
func (driver Baidu) Config() base.DriverConfig {
|
||||
return base.DriverConfig{
|
||||
Name: "Baidu.Photo",
|
||||
LocalSort: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (driver Baidu) Items() []base.Item {
|
||||
return []base.Item{
|
||||
{
|
||||
Name: "refresh_token",
|
||||
Label: "refresh token",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "root_folder",
|
||||
Label: "album_id",
|
||||
Type: base.TypeString,
|
||||
},
|
||||
{
|
||||
Name: "internal_type",
|
||||
Label: "download api",
|
||||
Type: base.TypeSelect,
|
||||
Required: true,
|
||||
Values: "file,album",
|
||||
Default: "album",
|
||||
},
|
||||
{
|
||||
Name: "client_id",
|
||||
Label: "client id",
|
||||
Default: "iYCeC9g08h5vuP9UqvPHKKSVrKFXGa1v",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "client_secret",
|
||||
Label: "client secret",
|
||||
Default: "jXiFMOPVPCWlO2M5CwWQzffpNPaGTRBG",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (driver Baidu) Save(account *model.Account, old *model.Account) error {
|
||||
if account == nil {
|
||||
return nil
|
||||
}
|
||||
return driver.RefreshToken(account)
|
||||
}
|
||||
|
||||
func (driver Baidu) File(path string, account *model.Account) (*model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
if path == "/" {
|
||||
return &model.File{
|
||||
Id: account.RootFolder,
|
||||
Name: account.Name,
|
||||
Size: 0,
|
||||
Type: conf.FOLDER,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: account.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
dir, name := utils.Split(path)
|
||||
files, err := driver.Files(dir, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range files {
|
||||
if file.Name == name {
|
||||
return &file, nil
|
||||
}
|
||||
}
|
||||
return nil, base.ErrPathNotFound
|
||||
}
|
||||
|
||||
func (driver Baidu) Files(path string, account *model.Account) ([]model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
var files []model.File
|
||||
cache, err := base.GetCache(path, account)
|
||||
if err == nil {
|
||||
files, _ = cache.([]model.File)
|
||||
return files, nil
|
||||
}
|
||||
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if IsAlbum(file) {
|
||||
albumFiles, err := driver.GetAllAlbumFile(file.Id, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
files = make([]model.File, 0, len(albumFiles))
|
||||
for _, file := range albumFiles {
|
||||
var thumbnail string
|
||||
if len(file.Thumburl) > 0 {
|
||||
thumbnail = file.Thumburl[0]
|
||||
}
|
||||
files = append(files, model.File{
|
||||
Id: joinID(file.Fsid, file.Uk, file.Tid),
|
||||
Name: file.Name(),
|
||||
Size: file.Size,
|
||||
Type: utils.GetFileType(utils.Ext(file.Path)),
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: getTime(file.Mtime),
|
||||
Thumbnail: thumbnail,
|
||||
})
|
||||
}
|
||||
} else if IsRoot(file) {
|
||||
albums, err := driver.GetAllAlbum(account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
files = make([]model.File, 0, len(albums))
|
||||
for _, album := range albums {
|
||||
files = append(files, model.File{
|
||||
Id: joinID(album.AlbumID, album.Tid),
|
||||
Name: album.Title,
|
||||
Size: 0,
|
||||
Type: conf.FOLDER,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: getTime(album.Mtime),
|
||||
})
|
||||
}
|
||||
} else {
|
||||
return nil, base.ErrNotSupport
|
||||
}
|
||||
|
||||
if len(files) > 0 {
|
||||
_ = base.SetCache(path, files, account)
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func (driver Baidu) Link(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
if account.InternalType == "file" {
|
||||
return driver.LinkFile(args, account)
|
||||
}
|
||||
return driver.LinkAlbum(args, account)
|
||||
}
|
||||
|
||||
func (driver Baidu) LinkAlbum(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
file, err := driver.File(args.Path, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !IsAlbumFile(file) {
|
||||
return nil, base.ErrNotSupport
|
||||
}
|
||||
|
||||
album, err := driver.File(utils.Dir(utils.ParsePath(args.Path)), account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
e := splitID(file.Id)
|
||||
res, err := base.NoRedirectClient.R().
|
||||
SetQueryParams(map[string]string{
|
||||
"access_token": account.AccessToken,
|
||||
"album_id": splitID(album.Id)[0],
|
||||
"tid": e[2],
|
||||
"fsid": e[0],
|
||||
"uk": e[1],
|
||||
}).
|
||||
Head(ALBUM_API_URL + "/download")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &base.Link{
|
||||
Headers: []base.Header{
|
||||
{Name: "User-Agent", Value: base.UserAgent},
|
||||
},
|
||||
Url: res.Header().Get("location"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (driver Baidu) LinkFile(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
file, err := driver.File(args.Path, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !IsAlbumFile(file) {
|
||||
return nil, base.ErrNotSupport
|
||||
}
|
||||
|
||||
album, err := driver.File(utils.Dir(utils.ParsePath(args.Path)), account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// 拷贝到根目录
|
||||
cfile, err := driver.CopyAlbumFile(album.Id, account, file.Id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
res, err := driver.Request(http.MethodGet, FILE_API_URL_V2+"/download", func(r *resty.Request) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"fsid": fmt.Sprint(cfile.Fsid),
|
||||
})
|
||||
}, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &base.Link{
|
||||
Headers: []base.Header{
|
||||
{Name: "User-Agent", Value: base.UserAgent},
|
||||
},
|
||||
Url: utils.Json.Get(res.Body(), "dlink").ToString(),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (driver Baidu) Path(path string, account *model.Account) (*model.File, []model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !file.IsDir() {
|
||||
return file, nil, nil
|
||||
}
|
||||
files, err := driver.Files(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, files, nil
|
||||
}
|
||||
|
||||
func (driver Baidu) Preview(path string, account *model.Account) (interface{}, error) {
|
||||
return nil, base.ErrNotSupport
|
||||
}
|
||||
|
||||
func (driver Baidu) Rename(src string, dst string, account *model.Account) error {
|
||||
srcFile, err := driver.File(src, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if IsAlbum(srcFile) {
|
||||
return driver.SetAlbumName(srcFile.Id, utils.Base(dst), account)
|
||||
}
|
||||
return base.ErrNotSupport
|
||||
}
|
||||
|
||||
func (driver Baidu) MakeDir(path string, account *model.Account) error {
|
||||
dir, name := utils.Split(path)
|
||||
parentFile, err := driver.File(dir, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !IsRoot(parentFile) {
|
||||
return base.ErrNotSupport
|
||||
}
|
||||
return driver.CreateAlbum(name, account)
|
||||
}
|
||||
|
||||
func (driver Baidu) Move(src string, dst string, account *model.Account) error {
|
||||
srcFile, err := driver.File(src, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if IsAlbumFile(srcFile) {
|
||||
// 移动相册文件
|
||||
dstAlbum, err := driver.File(utils.Dir(dst), account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !IsAlbum(dstAlbum) {
|
||||
return base.ErrNotSupport
|
||||
}
|
||||
|
||||
srcAlbum, err := driver.File(utils.Dir(src), account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
newFile, err := driver.CopyAlbumFile(srcAlbum.Id, account, srcFile.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = driver.DeleteAlbumFile(srcAlbum.Id, account, srcFile.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = driver.AddAlbumFile(dstAlbum.Id, account, joinID(newFile.Fsid))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return base.ErrNotSupport
|
||||
}
|
||||
|
||||
func (driver Baidu) Copy(src string, dst string, account *model.Account) error {
|
||||
srcFile, err := driver.File(src, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if IsAlbumFile(srcFile) {
|
||||
// 复制相册文件
|
||||
dstAlbum, err := driver.File(utils.Dir(dst), account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !IsAlbum(dstAlbum) {
|
||||
return base.ErrNotSupport
|
||||
}
|
||||
|
||||
srcAlbum, err := driver.File(utils.Dir(src), account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
newFile, err := driver.CopyAlbumFile(srcAlbum.Id, account, srcFile.Id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = driver.AddAlbumFile(dstAlbum.Id, account, joinID(newFile.Fsid))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return base.ErrNotSupport
|
||||
}
|
||||
|
||||
func (driver Baidu) Delete(path string, account *model.Account) error {
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 删除相册
|
||||
if IsAlbum(file) {
|
||||
return driver.DeleteAlbum(file.Id, account)
|
||||
}
|
||||
|
||||
// 生成相册文件
|
||||
if IsAlbumFile(file) {
|
||||
// 删除相册文件
|
||||
album, err := driver.File(utils.Dir(path), account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return driver.DeleteAlbumFile(album.Id, account, file.Id)
|
||||
}
|
||||
return base.ErrNotSupport
|
||||
}
|
||||
|
||||
func (driver Baidu) Upload(file *model.FileStream, account *model.Account) error {
|
||||
if file == nil {
|
||||
return base.ErrEmptyFile
|
||||
}
|
||||
|
||||
parentFile, err := driver.File(file.ParentPath, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if !IsAlbum(parentFile) {
|
||||
return base.ErrNotSupport
|
||||
}
|
||||
|
||||
tempFile, err := ioutil.TempFile(conf.Conf.TempDir, "file-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
tempFile.Close()
|
||||
os.Remove(tempFile.Name())
|
||||
}()
|
||||
|
||||
// 计算需要的数据
|
||||
const DEFAULT = 1 << 22
|
||||
const SliceSize = 1 << 18
|
||||
count := int(math.Ceil(float64(file.Size) / float64(DEFAULT)))
|
||||
|
||||
sliceMD5List := make([]string, 0, count)
|
||||
fileMd5 := md5.New()
|
||||
sliceMd5 := md5.New()
|
||||
for i := 1; i <= count; i++ {
|
||||
if n, err := io.CopyN(io.MultiWriter(fileMd5, sliceMd5, tempFile), file, DEFAULT); err != io.EOF && n == 0 {
|
||||
return err
|
||||
}
|
||||
sliceMD5List = append(sliceMD5List, hex.EncodeToString(sliceMd5.Sum(nil)))
|
||||
sliceMd5.Reset()
|
||||
}
|
||||
|
||||
if _, err = tempFile.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
content_md5 := hex.EncodeToString(fileMd5.Sum(nil))
|
||||
slice_md5 := content_md5
|
||||
if file.GetSize() > SliceSize {
|
||||
sliceData := make([]byte, SliceSize)
|
||||
if _, err = io.ReadFull(tempFile, sliceData); err != nil {
|
||||
return err
|
||||
}
|
||||
sliceMd5.Write(sliceData)
|
||||
slice_md5 = hex.EncodeToString(sliceMd5.Sum(nil))
|
||||
if _, err = tempFile.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// 开始执行上传
|
||||
params := map[string]string{
|
||||
"autoinit": "1",
|
||||
"isdir": "0",
|
||||
"rtype": "1",
|
||||
"ctype": "11",
|
||||
"path": utils.ParsePath(file.Name),
|
||||
"size": fmt.Sprint(file.Size),
|
||||
"slice-md5": slice_md5,
|
||||
"content-md5": content_md5,
|
||||
"block_list": MustString(utils.Json.MarshalToString(sliceMD5List)),
|
||||
}
|
||||
|
||||
// 预上传
|
||||
var precreateResp PrecreateResp
|
||||
_, err = driver.Request(http.MethodPost, FILE_API_URL_V1+"/precreate", func(r *resty.Request) {
|
||||
r.SetFormData(params)
|
||||
r.SetResult(&precreateResp)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch precreateResp.ReturnType {
|
||||
case 1: // 上传文件
|
||||
uploadParams := map[string]string{
|
||||
"method": "upload",
|
||||
"path": params["path"],
|
||||
"uploadid": precreateResp.UploadID,
|
||||
}
|
||||
|
||||
for i := 0; i < count; i++ {
|
||||
uploadParams["partseq"] = fmt.Sprint(i)
|
||||
_, err = driver.Request(http.MethodPost, "https://c3.pcs.baidu.com/rest/2.0/pcs/superfile2", func(r *resty.Request) {
|
||||
r.SetQueryParams(uploadParams)
|
||||
r.SetFileReader("file", file.Name, io.LimitReader(tempFile, DEFAULT))
|
||||
}, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
fallthrough
|
||||
case 2: // 创建文件
|
||||
params["uploadid"] = precreateResp.UploadID
|
||||
_, err = driver.Request(http.MethodPost, FILE_API_URL_V1+"/create", func(r *resty.Request) {
|
||||
r.SetFormData(params)
|
||||
r.SetResult(&precreateResp)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fallthrough
|
||||
case 3: // 增加到相册
|
||||
err = driver.AddAlbumFile(parentFile.Id, account, joinID(precreateResp.Data.FsID))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ base.Driver = (*Baidu)(nil)
|
126
drivers/baiduphoto/types.go
Normal file
126
drivers/baiduphoto/types.go
Normal file
@ -0,0 +1,126 @@
|
||||
package baiduphoto
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/Xhofe/alist/utils"
|
||||
)
|
||||
|
||||
type TokenErrResp struct {
|
||||
ErrorDescription string `json:"error_description"`
|
||||
ErrorMsg string `json:"error"`
|
||||
}
|
||||
|
||||
func (e *TokenErrResp) Error() string {
|
||||
return fmt.Sprint(e.ErrorMsg, " : ", e.ErrorDescription)
|
||||
}
|
||||
|
||||
type Erron struct {
|
||||
Errno int `json:"errno"`
|
||||
RequestID int `json:"request_id"`
|
||||
}
|
||||
|
||||
type Page struct {
|
||||
HasMore int `json:"has_more"`
|
||||
Cursor string `json:"cursor"`
|
||||
}
|
||||
|
||||
func (p Page) HasNextPage() bool {
|
||||
return p.HasMore == 1
|
||||
}
|
||||
|
||||
type (
|
||||
FileListResp struct {
|
||||
Page
|
||||
List []File `json:"list"`
|
||||
}
|
||||
|
||||
File struct {
|
||||
Fsid int64 `json:"fsid"` // 文件ID
|
||||
Path string `json:"path"` // 文件路径
|
||||
Size int64 `json:"size"`
|
||||
Ctime int64 `json:"ctime"` // 创建时间 s
|
||||
Mtime int64 `json:"mtime"` // 修改时间 s
|
||||
Thumburl []string `json:"thumburl"`
|
||||
}
|
||||
)
|
||||
|
||||
func (f File) Name() string {
|
||||
return utils.Base(f.Path)
|
||||
}
|
||||
|
||||
/*相册部分*/
|
||||
type (
|
||||
AlbumListResp struct {
|
||||
Page
|
||||
List []Album `json:"list"`
|
||||
Reset int64 `json:"reset"`
|
||||
TotalCount int64 `json:"total_count"`
|
||||
}
|
||||
|
||||
Album struct {
|
||||
AlbumID string `json:"album_id"`
|
||||
Tid int64 `json:"tid"`
|
||||
Title string `json:"title"`
|
||||
JoinTime int64 `json:"join_time"`
|
||||
CreateTime int64 `json:"create_time"`
|
||||
Mtime int64 `json:"mtime"`
|
||||
}
|
||||
|
||||
AlbumFileListResp struct {
|
||||
Page
|
||||
List []AlbumFile `json:"list"`
|
||||
Reset int64 `json:"reset"`
|
||||
TotalCount int64 `json:"total_count"`
|
||||
}
|
||||
|
||||
AlbumFile struct {
|
||||
File
|
||||
Tid int64 `json:"tid"`
|
||||
Uk int64 `json:"uk"`
|
||||
}
|
||||
)
|
||||
|
||||
type (
|
||||
CopyFileResp struct {
|
||||
List []CopyFile `json:"list"`
|
||||
}
|
||||
CopyFile struct {
|
||||
FromFsid int64 `json:"from_fsid"` // 源ID
|
||||
Fsid int64 `json:"fsid"` // 目标ID
|
||||
Path string `json:"path"`
|
||||
ShootTime int `json:"shoot_time"`
|
||||
}
|
||||
)
|
||||
|
||||
/*上传部分*/
|
||||
type (
|
||||
UploadFile struct {
|
||||
FsID int64 `json:"fs_id"`
|
||||
Size int64 `json:"size"`
|
||||
Md5 string `json:"md5"`
|
||||
ServerFilename string `json:"server_filename"`
|
||||
Path string `json:"path"`
|
||||
Ctime int `json:"ctime"`
|
||||
Mtime int `json:"mtime"`
|
||||
Isdir int `json:"isdir"`
|
||||
Category int `json:"category"`
|
||||
ServerMd5 string `json:"server_md5"`
|
||||
ShootTime int `json:"shoot_time"`
|
||||
}
|
||||
|
||||
CreateFileResp struct {
|
||||
Data UploadFile `json:"data"`
|
||||
}
|
||||
|
||||
PrecreateResp struct {
|
||||
ReturnType int `json:"return_type"` //存在返回2 不存在返回1 已经保存3
|
||||
//存在返回
|
||||
CreateFileResp
|
||||
|
||||
//不存在返回
|
||||
Path string `json:"path"`
|
||||
UploadID string `json:"uploadid"`
|
||||
Blocklist []int64 `json:"block_list"`
|
||||
}
|
||||
)
|
84
drivers/baiduphoto/util.go
Normal file
84
drivers/baiduphoto/util.go
Normal file
@ -0,0 +1,84 @@
|
||||
package baiduphoto
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/rand"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Xhofe/alist/model"
|
||||
)
|
||||
|
||||
const (
|
||||
API_URL = "https://photo.baidu.com/youai"
|
||||
ALBUM_API_URL = API_URL + "/album/v1"
|
||||
FILE_API_URL_V1 = API_URL + "/file/v1"
|
||||
FILE_API_URL_V2 = API_URL + "/file/v2"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotSupportName = errors.New("only chinese and english, numbers and underscores are supported, and the length is no more than 20")
|
||||
)
|
||||
|
||||
//Tid生成
|
||||
func getTid() string {
|
||||
return fmt.Sprintf("3%d%.0f", time.Now().Unix(), math.Floor(9000000*rand.Float64()+1000000))
|
||||
}
|
||||
|
||||
// 检查名称
|
||||
func checkName(name string) bool {
|
||||
return len(name) <= 20 && regexp.MustCompile("[\u4e00-\u9fa5A-Za-z0-9_]").MatchString(name)
|
||||
}
|
||||
|
||||
func getTime(t int64) *time.Time {
|
||||
tm := time.Unix(t, 0)
|
||||
return &tm
|
||||
}
|
||||
|
||||
func fsidsFormat(ids ...string) string {
|
||||
var buf []string
|
||||
for _, id := range ids {
|
||||
e := strings.Split(id, "|")
|
||||
buf = append(buf, fmt.Sprintf("{\"fsid\":%s,\"uk\":%s}", e[0], e[1]))
|
||||
}
|
||||
return fmt.Sprintf("[%s]", strings.Join(buf, ","))
|
||||
}
|
||||
|
||||
func fsidsFormatNotUk(ids ...string) string {
|
||||
var buf []string
|
||||
for _, id := range ids {
|
||||
buf = append(buf, fmt.Sprintf("{\"fsid\":%s}", strings.Split(id, "|")[0]))
|
||||
}
|
||||
return fmt.Sprintf("[%s]", strings.Join(buf, ","))
|
||||
}
|
||||
|
||||
func splitID(id string) []string {
|
||||
return strings.SplitN(id, "|", 3)[:3]
|
||||
}
|
||||
|
||||
func joinID(ids ...interface{}) string {
|
||||
idsStr := make([]string, 0, len(ids))
|
||||
for _, id := range ids {
|
||||
idsStr = append(idsStr, fmt.Sprint(id))
|
||||
}
|
||||
return strings.Join(idsStr, "|")
|
||||
}
|
||||
|
||||
func IsAlbum(file *model.File) bool {
|
||||
return file.Id != "" && file.IsDir()
|
||||
}
|
||||
|
||||
func IsAlbumFile(file *model.File) bool {
|
||||
return file.Id != "" && !file.IsDir()
|
||||
}
|
||||
|
||||
func IsRoot(file *model.File) bool {
|
||||
return file.Id == "" && file.IsDir()
|
||||
}
|
||||
|
||||
func MustString(str string, err error) string {
|
||||
return str
|
||||
}
|
61
drivers/base/base.go
Normal file
61
drivers/base/base.go
Normal file
@ -0,0 +1,61 @@
|
||||
package base
|
||||
|
||||
import "github.com/Xhofe/alist/model"
|
||||
|
||||
type Base struct{}
|
||||
|
||||
func (b Base) Config() DriverConfig {
|
||||
return DriverConfig{}
|
||||
}
|
||||
|
||||
func (b Base) Items() []Item {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (b Base) Save(account *model.Account, old *model.Account) error {
|
||||
return ErrNotImplement
|
||||
}
|
||||
|
||||
func (b Base) File(path string, account *model.Account) (*model.File, error) {
|
||||
return nil, ErrNotImplement
|
||||
}
|
||||
|
||||
func (b Base) Files(path string, account *model.Account) ([]model.File, error) {
|
||||
return nil, ErrNotImplement
|
||||
}
|
||||
|
||||
func (b Base) Link(args Args, account *model.Account) (*Link, error) {
|
||||
return nil, ErrNotImplement
|
||||
}
|
||||
|
||||
func (b Base) Path(path string, account *model.Account) (*model.File, []model.File, error) {
|
||||
return nil, nil, ErrNotImplement
|
||||
}
|
||||
|
||||
func (b Base) Preview(path string, account *model.Account) (interface{}, error) {
|
||||
return nil, ErrNotImplement
|
||||
}
|
||||
|
||||
func (b Base) MakeDir(path string, account *model.Account) error {
|
||||
return ErrNotImplement
|
||||
}
|
||||
|
||||
func (b Base) Move(src string, dst string, account *model.Account) error {
|
||||
return ErrNotImplement
|
||||
}
|
||||
|
||||
func (b Base) Rename(src string, dst string, account *model.Account) error {
|
||||
return ErrNotImplement
|
||||
}
|
||||
|
||||
func (b Base) Copy(src string, dst string, account *model.Account) error {
|
||||
return ErrNotImplement
|
||||
}
|
||||
|
||||
func (b Base) Delete(path string, account *model.Account) error {
|
||||
return ErrNotImplement
|
||||
}
|
||||
|
||||
func (b Base) Upload(file *model.FileStream, account *model.Account) error {
|
||||
return ErrNotImplement
|
||||
}
|
@ -1,20 +1,50 @@
|
||||
package base
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func KeyCache(path string, account *model.Account) string {
|
||||
path = utils.ParsePath(path)
|
||||
return fmt.Sprintf("%s%s", account.Name, path)
|
||||
//path = utils.ParsePath(path)
|
||||
key := utils.ParsePath(utils.Join(account.Name, path))
|
||||
log.Debugln("cache key: ", key)
|
||||
return key
|
||||
}
|
||||
|
||||
func SetCache(path string, obj interface{}, account *model.Account) error {
|
||||
return conf.Cache.Set(conf.Ctx, KeyCache(path, account), obj, nil)
|
||||
func SaveSearchFiles[T model.ISearchFile](key string, obj []T) {
|
||||
if strings.Contains(key, ".balance") {
|
||||
return
|
||||
}
|
||||
err := model.DeleteSearchFilesByPath(key)
|
||||
if err != nil {
|
||||
log.Errorln("failed create search files", err)
|
||||
return
|
||||
}
|
||||
files := make([]model.SearchFile, len(obj))
|
||||
for i := 0; i < len(obj); i++ {
|
||||
files[i] = model.SearchFile{
|
||||
Path: key,
|
||||
Name: obj[i].GetName(),
|
||||
Size: obj[i].GetSize(),
|
||||
Type: obj[i].GetType(),
|
||||
}
|
||||
}
|
||||
err = model.CreateSearchFiles(files)
|
||||
if err != nil {
|
||||
log.Errorln("failed create search files", err)
|
||||
}
|
||||
}
|
||||
|
||||
func SetCache[T model.ISearchFile](path string, obj []T, account *model.Account) error {
|
||||
key := KeyCache(path, account)
|
||||
if conf.GetBool("enable search") {
|
||||
go SaveSearchFiles(key, obj)
|
||||
}
|
||||
return conf.Cache.Set(conf.Ctx, key, obj, nil)
|
||||
}
|
||||
|
||||
func GetCache(path string, account *model.Account) (interface{}, error) {
|
||||
|
@ -19,8 +19,9 @@ type DriverConfig struct {
|
||||
}
|
||||
|
||||
type Args struct {
|
||||
Path string
|
||||
IP string
|
||||
Path string
|
||||
IP string
|
||||
Header http.Header
|
||||
}
|
||||
|
||||
type Driver interface {
|
||||
@ -121,7 +122,7 @@ func GetDrivers() map[string][]Item {
|
||||
{
|
||||
Name: "down_proxy_url",
|
||||
Label: "down_proxy_url",
|
||||
Type: TypeString,
|
||||
Type: TypeText,
|
||||
},
|
||||
{
|
||||
Name: "extract_folder",
|
||||
|
@ -3,6 +3,7 @@ package base
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -21,6 +22,7 @@ const (
|
||||
TypeSelect = "select"
|
||||
TypeBool = "bool"
|
||||
TypeNumber = "number"
|
||||
TypeText = "text"
|
||||
)
|
||||
|
||||
const (
|
||||
@ -48,4 +50,6 @@ type Link struct {
|
||||
Headers []Header `json:"headers"`
|
||||
Data io.ReadCloser
|
||||
FilePath string `json:"path"` // for native
|
||||
Status int
|
||||
Header http.Header
|
||||
}
|
||||
|
@ -227,13 +227,21 @@ func (driver FTP) Copy(src string, dst string, account *model.Account) error {
|
||||
|
||||
func (driver FTP) Delete(path string, account *model.Account) error {
|
||||
path = utils.ParsePath(path)
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
realPath := utils.Join(account.RootFolder, path)
|
||||
conn, err := driver.Login(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
//defer func() { _ = conn.Quit() }()
|
||||
err = conn.Delete(realPath)
|
||||
if file.IsDir() {
|
||||
err = conn.RemoveDirRecur(realPath)
|
||||
} else {
|
||||
err = conn.Delete(realPath)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
|
@ -29,12 +29,14 @@ func (driver GoogleDrive) Items() []base.Item {
|
||||
Label: "client id",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
Default: "202264815644.apps.googleusercontent.com",
|
||||
},
|
||||
{
|
||||
Name: "client_secret",
|
||||
Label: "client secret",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
Default: "X4Z3ca8xfWDb1Voo-F9a7ZxJ",
|
||||
},
|
||||
{
|
||||
Name: "refresh_token",
|
||||
|
@ -2,15 +2,10 @@ package google
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/go-resty/resty/v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type TokenError struct {
|
||||
@ -44,19 +39,6 @@ func (driver GoogleDrive) RefreshToken(account *model.Account) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
type File struct {
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
MimeType string `json:"mimeType"`
|
||||
ModifiedTime *time.Time `json:"modifiedTime"`
|
||||
Size string `json:"size"`
|
||||
ThumbnailLink string `json:"thumbnailLink"`
|
||||
}
|
||||
|
||||
func (driver GoogleDrive) IsDir(mimeType string) bool {
|
||||
return mimeType == "application/vnd.google-apps.folder" || mimeType == "application/vnd.google-apps.shortcut"
|
||||
}
|
||||
|
||||
func (driver GoogleDrive) FormatFile(file *File, account *model.Account) *model.File {
|
||||
f := &model.File{
|
||||
Id: file.Id,
|
||||
@ -65,16 +47,11 @@ func (driver GoogleDrive) FormatFile(file *File, account *model.Account) *model.
|
||||
UpdatedAt: file.ModifiedTime,
|
||||
Url: "",
|
||||
}
|
||||
if driver.IsDir(file.MimeType) {
|
||||
f.Type = conf.FOLDER
|
||||
} else {
|
||||
size, _ := strconv.ParseInt(file.Size, 10, 64)
|
||||
f.Size = size
|
||||
f.Type = utils.GetFileType(filepath.Ext(file.Name))
|
||||
}
|
||||
f.Size = int64(file.GetSize())
|
||||
f.Type = file.GetType()
|
||||
if file.ThumbnailLink != "" {
|
||||
if account.DownProxyUrl != "" {
|
||||
f.Thumbnail = fmt.Sprintf("%s/%s", account.DownProxyUrl, file.ThumbnailLink)
|
||||
if account.APIProxyUrl != "" {
|
||||
f.Thumbnail = fmt.Sprintf("%s/%s", account.APIProxyUrl, file.ThumbnailLink)
|
||||
} else {
|
||||
f.Thumbnail = file.ThumbnailLink
|
||||
}
|
||||
|
38
drivers/google/types.go
Normal file
38
drivers/google/types.go
Normal file
@ -0,0 +1,38 @@
|
||||
package google
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"path"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type File struct {
|
||||
Id string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
MimeType string `json:"mimeType"`
|
||||
ModifiedTime *time.Time `json:"modifiedTime"`
|
||||
Size string `json:"size"`
|
||||
ThumbnailLink string `json:"thumbnailLink"`
|
||||
}
|
||||
|
||||
func (f File) GetSize() uint64 {
|
||||
if f.GetType() == conf.FOLDER {
|
||||
return 0
|
||||
}
|
||||
size, _ := strconv.ParseUint(f.Size, 10, 64)
|
||||
return size
|
||||
}
|
||||
|
||||
func (f File) GetName() string {
|
||||
return f.Name
|
||||
}
|
||||
|
||||
func (f File) GetType() int {
|
||||
mimeType := f.MimeType
|
||||
if mimeType == "application/vnd.google-apps.folder" || mimeType == "application/vnd.google-apps.shortcut" {
|
||||
return conf.FOLDER
|
||||
}
|
||||
return utils.GetFileType(path.Ext(f.Name))
|
||||
}
|
@ -125,13 +125,19 @@ func (driver Lanzou) Link(args base.Args, account *model.Account) (*base.Link, e
|
||||
}
|
||||
log.Debugf("down file: %+v", file)
|
||||
downId := file.Id
|
||||
pwd := ""
|
||||
if account.InternalType == "cookie" {
|
||||
downId, err = driver.GetDownPageId(file.Id, account)
|
||||
downId, pwd, err = driver.GetDownPageId(file.Id, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
url, err := driver.GetLink(downId, account)
|
||||
var url string
|
||||
//if pwd != "" {
|
||||
//url, err = driver.GetLinkWithPassword(downId, pwd, account)
|
||||
//} else {
|
||||
url, err = driver.GetLink(downId, pwd, account)
|
||||
//}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
@ -2,28 +2,15 @@ package lanzou
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type LanZouFile struct {
|
||||
Name string `json:"name"`
|
||||
NameAll string `json:"name_all"`
|
||||
Id string `json:"id"`
|
||||
FolId string `json:"fol_id"`
|
||||
Size string `json:"size"`
|
||||
Time string `json:"time"`
|
||||
Folder bool
|
||||
}
|
||||
|
||||
func (driver *Lanzou) FormatFile(file *LanZouFile) *model.File {
|
||||
now := time.Now()
|
||||
f := &model.File{
|
||||
@ -35,12 +22,11 @@ func (driver *Lanzou) FormatFile(file *LanZouFile) *model.File {
|
||||
UpdatedAt: &now,
|
||||
}
|
||||
if file.Folder {
|
||||
f.Type = conf.FOLDER
|
||||
f.Id = file.FolId
|
||||
} else {
|
||||
f.Name = file.NameAll
|
||||
f.Type = utils.GetFileType(filepath.Ext(file.NameAll))
|
||||
}
|
||||
f.Type = file.GetType()
|
||||
return f
|
||||
}
|
||||
|
||||
@ -118,7 +104,10 @@ func (driver *Lanzou) GetFilesByUrl(account *model.Account) ([]LanZouFile, error
|
||||
uid := regexp.MustCompile(`'uid':'(.+?)',`).FindStringSubmatch(res.String())[1]
|
||||
rep := regexp.MustCompile(`'rep':'(.+?)',`).FindStringSubmatch(res.String())[1]
|
||||
up := regexp.MustCompile(`'up':(.+?),`).FindStringSubmatch(res.String())[1]
|
||||
ls := regexp.MustCompile(`'ls':(.+?),`).FindStringSubmatch(res.String())[1]
|
||||
ls := ""
|
||||
if account.Password != "" {
|
||||
ls = regexp.MustCompile(`'ls':(.+?),`).FindStringSubmatch(res.String())[1]
|
||||
}
|
||||
tName := regexp.MustCompile(`'t':(.+?),`).FindStringSubmatch(res.String())[1]
|
||||
kName := regexp.MustCompile(`'k':(.+?),`).FindStringSubmatch(res.String())[1]
|
||||
t := regexp.MustCompile(`var ` + tName + ` = '(.+?)';`).FindStringSubmatch(res.String())[1]
|
||||
@ -150,6 +139,7 @@ func (driver *Lanzou) GetFilesByUrl(account *model.Account) ([]LanZouFile, error
|
||||
break
|
||||
}
|
||||
pg++
|
||||
time.Sleep(time.Second)
|
||||
files = append(files, resp.Text...)
|
||||
}
|
||||
return files, nil
|
||||
@ -161,29 +151,21 @@ func (driver *Lanzou) GetFilesByUrl(account *model.Account) ([]LanZouFile, error
|
||||
//}
|
||||
|
||||
// GetDownPageId 获取下载页面的ID
|
||||
func (driver *Lanzou) GetDownPageId(fileId string, account *model.Account) (string, error) {
|
||||
var resp LanZouFilesResp
|
||||
func (driver *Lanzou) GetDownPageId(fileId string, account *model.Account) (string, string, error) {
|
||||
var resp DownPageResp
|
||||
res, err := base.RestyClient.R().SetResult(&resp).SetHeader("Cookie", account.AccessToken).
|
||||
SetFormData(map[string]string{
|
||||
"task": "22",
|
||||
"file_id": fileId,
|
||||
}).Post("https://pc.woozooo.com/doupload.php")
|
||||
if err != nil {
|
||||
return "", err
|
||||
return "", "", err
|
||||
}
|
||||
log.Debug(res.String())
|
||||
if resp.Zt != 1 {
|
||||
return "", fmt.Errorf("%v", resp.Info)
|
||||
return "", "", fmt.Errorf("%v", resp.Info)
|
||||
}
|
||||
info, ok := resp.Info.(map[string]interface{})
|
||||
if !ok {
|
||||
return "", fmt.Errorf("%v", resp.Info)
|
||||
}
|
||||
fid, ok := info["f_id"].(string)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("%v", info["f_id"])
|
||||
}
|
||||
return fid, nil
|
||||
return resp.Info.FId, resp.Info.Pwd, nil
|
||||
}
|
||||
|
||||
type LanzouLinkResp struct {
|
||||
@ -192,19 +174,20 @@ type LanzouLinkResp struct {
|
||||
Zt int `json:"zt"`
|
||||
}
|
||||
|
||||
func (driver *Lanzou) GetLink(downId string, account *model.Account) (string, error) {
|
||||
func (driver *Lanzou) GetLink(downId string, pwd string, account *model.Account) (string, error) {
|
||||
shareUrl := account.SiteUrl
|
||||
u, err := url.Parse(shareUrl)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
log.Debugln(fmt.Sprintf("https://%s/%s", u.Host, downId))
|
||||
res, err := base.RestyClient.R().Get(fmt.Sprintf("https://%s/%s", u.Host, downId))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
iframe := regexp.MustCompile(`<iframe class="ifr2" name=".{2,20}" src="(.+?)"`).FindStringSubmatch(res.String())
|
||||
if len(iframe) == 0 {
|
||||
return "", fmt.Errorf("get down empty page")
|
||||
return driver.GetLinkWithPassword(downId, pwd, res.String(), account)
|
||||
}
|
||||
iframeUrl := fmt.Sprintf("https://%s%s", u.Host, iframe[1])
|
||||
res, err = base.RestyClient.R().Get(iframeUrl)
|
||||
@ -220,8 +203,12 @@ func (driver *Lanzou) GetLink(downId string, account *model.Account) (string, er
|
||||
//sign := regexp.MustCompile(`var ispostdowns = '(.+?)';`).FindStringSubmatch(res.String())[1]
|
||||
sign := regexp.MustCompile(`'sign':'(.+?)',`).FindStringSubmatch(res.String())[1]
|
||||
//websign := regexp.MustCompile(`'websign':'(.+?)'`).FindStringSubmatch(res.String())[1]
|
||||
//websign := regexp.MustCompile(`var websign = '(.+?)'`).FindStringSubmatch(res.String())[1]
|
||||
websign := ""
|
||||
websignR := regexp.MustCompile(`var websign = '(.+?)'`).FindStringSubmatch(res.String())
|
||||
if len(websignR) > 1 {
|
||||
websign = websignR[1]
|
||||
}
|
||||
//websign := ""
|
||||
//websignkey := regexp.MustCompile(`'websignkey':'(.+?)'`).FindStringSubmatch(res.String())[1]
|
||||
websignkey := regexp.MustCompile(`var websignkey = '(.+?)';`).FindStringSubmatch(res.String())[1]
|
||||
var resp LanzouLinkResp
|
||||
@ -245,7 +232,38 @@ func (driver *Lanzou) GetLink(downId string, account *model.Account) (string, er
|
||||
if resp.Zt == 1 {
|
||||
return resp.Dom + "/file/" + resp.Url, nil
|
||||
}
|
||||
return "", fmt.Errorf("can't get link")
|
||||
return "", fmt.Errorf("failed get link")
|
||||
}
|
||||
|
||||
func (driver *Lanzou) GetLinkWithPassword(downId string, pwd string, html string, account *model.Account) (string, error) {
|
||||
shareUrl := account.SiteUrl
|
||||
u, err := url.Parse(shareUrl)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if html == "" {
|
||||
log.Debugln(fmt.Sprintf("https://%s/%s", u.Host, downId))
|
||||
res, err := base.RestyClient.R().Get(fmt.Sprintf("https://%s/%s", u.Host, downId))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
html = res.String()
|
||||
}
|
||||
|
||||
data := regexp.MustCompile(`data : '(.+?)'\+pwd,`).FindStringSubmatch(html)[1] + pwd
|
||||
var resp LanzouLinkResp
|
||||
_, err = base.RestyClient.R().SetResult(&resp).SetHeaders(map[string]string{
|
||||
"Referer": fmt.Sprintf("https://%s/%s", u.Host, downId),
|
||||
"Origin": "https://" + u.Host,
|
||||
"content-type": "application/x-www-form-urlencoded",
|
||||
}).SetBody(data).Post(fmt.Sprintf("https://%s/ajaxm.php", u.Host))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if resp.Zt == 1 {
|
||||
return resp.Dom + "/file/" + resp.Url, nil
|
||||
}
|
||||
return "", fmt.Errorf("failed get link with password")
|
||||
}
|
||||
|
||||
func init() {
|
||||
|
47
drivers/lanzou/types.go
Normal file
47
drivers/lanzou/types.go
Normal file
@ -0,0 +1,47 @@
|
||||
package lanzou
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"path"
|
||||
)
|
||||
|
||||
type LanZouFile struct {
|
||||
Name string `json:"name"`
|
||||
NameAll string `json:"name_all"`
|
||||
Id string `json:"id"`
|
||||
FolId string `json:"fol_id"`
|
||||
Size string `json:"size"`
|
||||
Time string `json:"time"`
|
||||
Folder bool
|
||||
}
|
||||
|
||||
func (f LanZouFile) GetSize() uint64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (f LanZouFile) GetName() string {
|
||||
if f.Folder {
|
||||
return f.Name
|
||||
}
|
||||
return f.NameAll
|
||||
}
|
||||
|
||||
func (f LanZouFile) GetType() int {
|
||||
if f.Folder {
|
||||
return conf.FOLDER
|
||||
}
|
||||
return utils.GetFileType(path.Ext(f.NameAll))
|
||||
}
|
||||
|
||||
type DownPageResp struct {
|
||||
Zt int `json:"zt"`
|
||||
Info struct {
|
||||
Pwd string `json:"pwd"`
|
||||
Onof string `json:"onof"`
|
||||
FId string `json:"f_id"`
|
||||
Taoc string `json:"taoc"`
|
||||
IsNewd string `json:"is_newd"`
|
||||
} `json:"info"`
|
||||
Text interface{} `json:"text"`
|
||||
}
|
@ -158,10 +158,6 @@ func (driver MediaTrack) Preview(path string, account *model.Account) (interface
|
||||
}
|
||||
|
||||
func (driver MediaTrack) MakeDir(path string, account *model.Account) error {
|
||||
_, err := driver.File(path, account)
|
||||
if err != base.ErrPathNotFound {
|
||||
return nil
|
||||
}
|
||||
parentFile, err := driver.File(utils.Dir(path), account)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -71,7 +71,6 @@ func (driver Native) File(path string, account *model.Account) (*model.File, err
|
||||
time := f.ModTime()
|
||||
file := &model.File{
|
||||
Name: f.Name(),
|
||||
Size: f.Size(),
|
||||
UpdatedAt: &time,
|
||||
Driver: driver.Config().Name,
|
||||
}
|
||||
@ -79,6 +78,7 @@ func (driver Native) File(path string, account *model.Account) (*model.File, err
|
||||
file.Type = conf.FOLDER
|
||||
} else {
|
||||
file.Type = utils.GetFileType(filepath.Ext(f.Name()))
|
||||
file.Size = f.Size()
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
@ -103,7 +103,6 @@ func (driver Native) Files(path string, account *model.Account) ([]model.File, e
|
||||
time := f.ModTime()
|
||||
file := model.File{
|
||||
Name: f.Name(),
|
||||
Size: f.Size(),
|
||||
Type: 0,
|
||||
UpdatedAt: &time,
|
||||
Driver: driver.Config().Name,
|
||||
@ -112,9 +111,14 @@ func (driver Native) Files(path string, account *model.Account) ([]model.File, e
|
||||
file.Type = conf.FOLDER
|
||||
} else {
|
||||
file.Type = utils.GetFileType(filepath.Ext(f.Name()))
|
||||
file.Size = f.Size()
|
||||
}
|
||||
files = append(files, file)
|
||||
}
|
||||
_, err = base.GetCache(path, account)
|
||||
if len(files) != 0 && err != nil {
|
||||
_ = base.SetCache(path, files, account)
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
|
@ -53,6 +53,7 @@ func (driver Onedrive) Items() []base.Item {
|
||||
Label: "redirect uri",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
Default: "https://tool.nn.ci/onedrive/callback",
|
||||
},
|
||||
{
|
||||
Name: "refresh_token",
|
||||
@ -175,7 +176,7 @@ func (driver Onedrive) Link(args base.Args, account *model.Account) (*base.Link,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if file.File.MimeType == "" {
|
||||
if file.File == nil {
|
||||
return nil, base.ErrNotFile
|
||||
}
|
||||
link := base.Link{
|
||||
|
@ -120,7 +120,7 @@ type OneFile struct {
|
||||
Size int64 `json:"size"`
|
||||
LastModifiedDateTime *time.Time `json:"lastModifiedDateTime"`
|
||||
Url string `json:"@microsoft.graph.downloadUrl"`
|
||||
File struct {
|
||||
File *struct {
|
||||
MimeType string `json:"mimeType"`
|
||||
} `json:"file"`
|
||||
Thumbnails []struct {
|
||||
@ -157,7 +157,7 @@ func (driver Onedrive) FormatFile(file *OneFile) *model.File {
|
||||
if len(file.Thumbnails) > 0 {
|
||||
f.Thumbnail = file.Thumbnails[0].Medium.Url
|
||||
}
|
||||
if file.File.MimeType == "" {
|
||||
if file.File == nil {
|
||||
f.Type = conf.FOLDER
|
||||
} else {
|
||||
f.Type = utils.GetFileType(filepath.Ext(file.Name))
|
||||
@ -307,8 +307,10 @@ func (driver Onedrive) UploadBig(file *model.FileStream, account *model.Account)
|
||||
res, err := base.HttpClient.Do(req)
|
||||
if res.StatusCode != 201 && res.StatusCode != 202 {
|
||||
data, _ := ioutil.ReadAll(res.Body)
|
||||
res.Body.Close()
|
||||
return errors.New(string(data))
|
||||
}
|
||||
res.Body.Close()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
@ -8,6 +8,10 @@ import (
|
||||
"runtime/debug"
|
||||
)
|
||||
|
||||
func Save(driver base.Driver, account, old *model.Account) error {
|
||||
return driver.Save(account, old)
|
||||
}
|
||||
|
||||
func Path(driver base.Driver, account *model.Account, path string) (*model.File, []model.File, error) {
|
||||
return driver.Path(path, account)
|
||||
}
|
||||
@ -29,7 +33,11 @@ func File(driver base.Driver, account *model.Account, path string) (*model.File,
|
||||
|
||||
func MakeDir(driver base.Driver, account *model.Account, path string, clearCache bool) error {
|
||||
log.Debugf("mkdir: %s", path)
|
||||
err := driver.MakeDir(path, account)
|
||||
_, err := Files(driver, account, path)
|
||||
if err != base.ErrPathNotFound {
|
||||
return nil
|
||||
}
|
||||
err = driver.MakeDir(path, account)
|
||||
if err == nil && clearCache {
|
||||
_ = base.DeleteCache(utils.Dir(path), account)
|
||||
}
|
||||
|
@ -119,9 +119,14 @@ func (driver PikPak) Link(args base.Args, account *model.Account) (*base.Link, e
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &base.Link{
|
||||
link := base.Link{
|
||||
Url: resp.WebContentLink,
|
||||
}, nil
|
||||
}
|
||||
if len(resp.Medias) > 0 && resp.Medias[0].Link.Url != "" {
|
||||
log.Debugln("use media link")
|
||||
link.Url = resp.Medias[0].Link.Url
|
||||
}
|
||||
return &link, nil
|
||||
}
|
||||
|
||||
func (driver PikPak) Path(path string, account *model.Account) (*model.File, []model.File, error) {
|
||||
|
@ -144,6 +144,37 @@ type File struct {
|
||||
Size string `json:"size"`
|
||||
ThumbnailLink string `json:"thumbnail_link"`
|
||||
WebContentLink string `json:"web_content_link"`
|
||||
Medias []Media `json:"medias"`
|
||||
}
|
||||
|
||||
type Media struct {
|
||||
MediaId string `json:"media_id"`
|
||||
MediaName string `json:"media_name"`
|
||||
Video struct {
|
||||
Height int `json:"height"`
|
||||
Width int `json:"width"`
|
||||
Duration int `json:"duration"`
|
||||
BitRate int `json:"bit_rate"`
|
||||
FrameRate int `json:"frame_rate"`
|
||||
VideoCodec string `json:"video_codec"`
|
||||
AudioCodec string `json:"audio_codec"`
|
||||
VideoType string `json:"video_type"`
|
||||
} `json:"video"`
|
||||
Link struct {
|
||||
Url string `json:"url"`
|
||||
Token string `json:"token"`
|
||||
Expire time.Time `json:"expire"`
|
||||
} `json:"link"`
|
||||
NeedMoreQuota bool `json:"need_more_quota"`
|
||||
VipTypes []interface{} `json:"vip_types"`
|
||||
RedirectLink string `json:"redirect_link"`
|
||||
IconLink string `json:"icon_link"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
Priority int `json:"priority"`
|
||||
IsOrigin bool `json:"is_origin"`
|
||||
ResolutionName string `json:"resolution_name"`
|
||||
IsVisible bool `json:"is_visible"`
|
||||
Category string `json:"category"`
|
||||
}
|
||||
|
||||
func (driver PikPak) FormatFile(file *File) *model.File {
|
||||
|
@ -64,6 +64,12 @@ func (driver Quark) Save(account *model.Account, old *model.Account) error {
|
||||
return nil
|
||||
}
|
||||
_, err := driver.Get("/config", nil, nil, account)
|
||||
if err == nil {
|
||||
account.Status = "work"
|
||||
} else {
|
||||
account.Status = err.Error()
|
||||
}
|
||||
_ = model.SaveAccount(account)
|
||||
return err
|
||||
}
|
||||
|
||||
@ -132,6 +138,7 @@ func (driver Quark) Link(args base.Args, account *model.Account) (*base.Link, er
|
||||
Url: resp.Data[0].DownloadUrl,
|
||||
Headers: []base.Header{
|
||||
{Name: "Cookie", Value: account.AccessToken},
|
||||
{Name: "Referer", Value: "https://pan.quark.cn"},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
@ -8,6 +8,7 @@ import (
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/Xhofe/alist/utils/cookie"
|
||||
"github.com/go-resty/resty/v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"net/http"
|
||||
@ -62,7 +63,12 @@ func (driver Quark) Request(pathname string, method int, headers, query, form ma
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Debugf("%s response: %s", pathname, res.String())
|
||||
__puus := cookie.GetCookie(res.Cookies(), "__puus")
|
||||
if __puus != nil {
|
||||
account.AccessToken = cookie.SetStr(account.AccessToken, "__puus", __puus.Value)
|
||||
_ = model.SaveAccount(account)
|
||||
}
|
||||
//log.Debugf("%s response: %s", pathname, res.String())
|
||||
if e.Status >= 400 || e.Code != 0 {
|
||||
return nil, errors.New(e.Message)
|
||||
}
|
||||
@ -97,7 +103,7 @@ func (driver Quark) GetFiles(parent string, account *model.Account) ([]model.Fil
|
||||
for _, f := range resp.Data.List {
|
||||
files = append(files, *driver.formatFile(&f))
|
||||
}
|
||||
if page*size >= resp.Metadata.Count {
|
||||
if page*size >= resp.Metadata.Total {
|
||||
break
|
||||
}
|
||||
page++
|
||||
|
@ -51,37 +51,37 @@ type SortResp struct {
|
||||
type DownResp struct {
|
||||
Resp
|
||||
Data []struct {
|
||||
Fid string `json:"fid"`
|
||||
FileName string `json:"file_name"`
|
||||
PdirFid string `json:"pdir_fid"`
|
||||
Category int `json:"category"`
|
||||
FileType int `json:"file_type"`
|
||||
Size int `json:"size"`
|
||||
FormatType string `json:"format_type"`
|
||||
Status int `json:"status"`
|
||||
Tags string `json:"tags"`
|
||||
LCreatedAt int64 `json:"l_created_at"`
|
||||
LUpdatedAt int64 `json:"l_updated_at"`
|
||||
NameSpace int `json:"name_space"`
|
||||
Thumbnail string `json:"thumbnail"`
|
||||
DownloadUrl string `json:"download_url"`
|
||||
Md5 string `json:"md5"`
|
||||
RiskType int `json:"risk_type"`
|
||||
RangeSize int `json:"range_size"`
|
||||
BackupSign int `json:"backup_sign"`
|
||||
ObjCategory string `json:"obj_category"`
|
||||
Duration int `json:"duration"`
|
||||
FileSource string `json:"file_source"`
|
||||
File bool `json:"file"`
|
||||
CreatedAt int64 `json:"created_at"`
|
||||
UpdatedAt int64 `json:"updated_at"`
|
||||
PrivateExtra struct {
|
||||
} `json:"_private_extra"`
|
||||
//Fid string `json:"fid"`
|
||||
//FileName string `json:"file_name"`
|
||||
//PdirFid string `json:"pdir_fid"`
|
||||
//Category int `json:"category"`
|
||||
//FileType int `json:"file_type"`
|
||||
//Size int `json:"size"`
|
||||
//FormatType string `json:"format_type"`
|
||||
//Status int `json:"status"`
|
||||
//Tags string `json:"tags"`
|
||||
//LCreatedAt int64 `json:"l_created_at"`
|
||||
//LUpdatedAt int64 `json:"l_updated_at"`
|
||||
//NameSpace int `json:"name_space"`
|
||||
//Thumbnail string `json:"thumbnail"`
|
||||
DownloadUrl string `json:"download_url"`
|
||||
//Md5 string `json:"md5"`
|
||||
//RiskType int `json:"risk_type"`
|
||||
//RangeSize int `json:"range_size"`
|
||||
//BackupSign int `json:"backup_sign"`
|
||||
//ObjCategory string `json:"obj_category"`
|
||||
//Duration int `json:"duration"`
|
||||
//FileSource string `json:"file_source"`
|
||||
//File bool `json:"file"`
|
||||
//CreatedAt int64 `json:"created_at"`
|
||||
//UpdatedAt int64 `json:"updated_at"`
|
||||
//PrivateExtra struct {
|
||||
//} `json:"_private_extra"`
|
||||
} `json:"data"`
|
||||
Metadata struct {
|
||||
Acc2 string `json:"acc2"`
|
||||
Acc1 string `json:"acc1"`
|
||||
} `json:"metadata"`
|
||||
//Metadata struct {
|
||||
// Acc2 string `json:"acc2"`
|
||||
// Acc1 string `json:"acc1"`
|
||||
//} `json:"metadata"`
|
||||
}
|
||||
|
||||
type UpPreResp struct {
|
||||
|
@ -1,6 +1,7 @@
|
||||
package s3
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
@ -9,6 +10,7 @@ import (
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/aws/aws-sdk-go/service/s3/s3manager"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"io/ioutil"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"time"
|
||||
@ -78,6 +80,7 @@ func (driver S3) Items() []base.Item {
|
||||
Label: "placeholder filename",
|
||||
Type: base.TypeString,
|
||||
Description: "default empty string",
|
||||
Default: defaultPlaceholderName,
|
||||
},
|
||||
{
|
||||
Name: "bool_1",
|
||||
@ -213,8 +216,19 @@ func (driver S3) Preview(path string, account *model.Account) (interface{}, erro
|
||||
}
|
||||
|
||||
func (driver S3) MakeDir(path string, account *model.Account) error {
|
||||
// not support, default as success
|
||||
return nil
|
||||
// not support, generate a placeholder file
|
||||
_, err := driver.File(path, account)
|
||||
// exist
|
||||
if err != base.ErrPathNotFound {
|
||||
return nil
|
||||
}
|
||||
return driver.Upload(&model.FileStream{
|
||||
File: ioutil.NopCloser(bytes.NewReader([]byte{})),
|
||||
Size: 0,
|
||||
ParentPath: path,
|
||||
Name: getPlaceholderName(account.Zone),
|
||||
MIMEType: "application/octet-stream",
|
||||
}, account)
|
||||
}
|
||||
|
||||
func (driver S3) Move(src string, dst string, account *model.Account) error {
|
||||
@ -277,6 +291,7 @@ func (driver S3) Upload(file *model.FileStream, account *model.Account) error {
|
||||
}
|
||||
uploader := s3manager.NewUploader(s)
|
||||
key := driver.GetKey(utils.Join(file.ParentPath, file.GetFileName()), account, false)
|
||||
log.Debugln("key:", key)
|
||||
input := &s3manager.UploadInput{
|
||||
Bucket: &account.Bucket,
|
||||
Key: &key,
|
||||
|
@ -88,7 +88,7 @@ func (driver S3) List(prefix string, account *model.Account) ([]model.File, erro
|
||||
}
|
||||
for _, object := range listObjectsResult.Contents {
|
||||
name := utils.Base(*object.Key)
|
||||
if name == account.Zone {
|
||||
if name == getPlaceholderName(account.Zone) {
|
||||
continue
|
||||
}
|
||||
file := model.File{
|
||||
@ -152,7 +152,7 @@ func (driver S3) ListV2(prefix string, account *model.Account) ([]model.File, er
|
||||
}
|
||||
for _, object := range listObjectsResult.Contents {
|
||||
name := utils.Base(*object.Key)
|
||||
if name == account.Zone {
|
||||
if name == getPlaceholderName(account.Zone) {
|
||||
continue
|
||||
}
|
||||
file := model.File{
|
||||
|
10
drivers/s3/util.go
Normal file
10
drivers/s3/util.go
Normal file
@ -0,0 +1,10 @@
|
||||
package s3
|
||||
|
||||
var defaultPlaceholderName = ".placeholder"
|
||||
|
||||
func getPlaceholderName(placeholder string) string {
|
||||
if placeholder == "" {
|
||||
return defaultPlaceholderName
|
||||
}
|
||||
return placeholder
|
||||
}
|
220
drivers/sftp/driver.go
Normal file
220
drivers/sftp/driver.go
Normal file
@ -0,0 +1,220 @@
|
||||
package template
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"io"
|
||||
"path"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type SFTP struct {
|
||||
}
|
||||
|
||||
func (driver SFTP) Config() base.DriverConfig {
|
||||
return base.DriverConfig{
|
||||
Name: "SFTP",
|
||||
OnlyProxy: true,
|
||||
OnlyLocal: true,
|
||||
LocalSort: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (driver SFTP) Items() []base.Item {
|
||||
// TODO fill need info
|
||||
return []base.Item{
|
||||
{
|
||||
Name: "site_url",
|
||||
Label: "ip/host",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "limit",
|
||||
Label: "port",
|
||||
Type: base.TypeNumber,
|
||||
Required: true,
|
||||
Default: "22",
|
||||
},
|
||||
{
|
||||
Name: "username",
|
||||
Label: "username",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "password",
|
||||
Label: "password",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "root_folder",
|
||||
Label: "root folder path",
|
||||
Type: base.TypeString,
|
||||
Default: "/",
|
||||
Required: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (driver SFTP) Save(account *model.Account, old *model.Account) error {
|
||||
if old != nil {
|
||||
clientsMap.Lock()
|
||||
defer clientsMap.Unlock()
|
||||
delete(clientsMap.clients, old.Name)
|
||||
}
|
||||
if account == nil {
|
||||
return nil
|
||||
}
|
||||
_, err := GetClient(account)
|
||||
if err != nil {
|
||||
account.Status = err.Error()
|
||||
} else {
|
||||
account.Status = "work"
|
||||
}
|
||||
_ = model.SaveAccount(account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver SFTP) File(path string, account *model.Account) (*model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
if path == "/" {
|
||||
return &model.File{
|
||||
Id: account.RootFolder,
|
||||
Name: account.Name,
|
||||
Size: 0,
|
||||
Type: conf.FOLDER,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: account.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
dir, name := filepath.Split(path)
|
||||
files, err := driver.Files(dir, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range files {
|
||||
if file.Name == name {
|
||||
return &file, nil
|
||||
}
|
||||
}
|
||||
return nil, base.ErrPathNotFound
|
||||
}
|
||||
|
||||
func (driver SFTP) Files(path string, account *model.Account) ([]model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
remotePath := utils.Join(account.RootFolder, path)
|
||||
cache, err := base.GetCache(path, account)
|
||||
if err == nil {
|
||||
files, _ := cache.([]model.File)
|
||||
return files, nil
|
||||
}
|
||||
client, err := GetClient(account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
files := make([]model.File, 0)
|
||||
rawFiles, err := client.Files(remotePath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for i := 0; i < len(rawFiles); i++ {
|
||||
files = append(files, driver.formatFile(rawFiles[i]))
|
||||
}
|
||||
if len(files) > 0 {
|
||||
_ = base.SetCache(path, files, account)
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func (driver SFTP) Link(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
client, err := GetClient(account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
remoteFileName := utils.Join(account.RootFolder, args.Path)
|
||||
remoteFile, err := client.Open(remoteFileName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &base.Link{
|
||||
Data: remoteFile,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (driver SFTP) Path(path string, account *model.Account) (*model.File, []model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !file.IsDir() {
|
||||
return file, nil, nil
|
||||
}
|
||||
files, err := driver.Files(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, files, nil
|
||||
}
|
||||
|
||||
func (driver SFTP) Preview(path string, account *model.Account) (interface{}, error) {
|
||||
//TODO preview interface if driver support
|
||||
return nil, base.ErrNotImplement
|
||||
}
|
||||
|
||||
func (driver SFTP) MakeDir(path string, account *model.Account) error {
|
||||
client, err := GetClient(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.MkdirAll(utils.Join(account.RootFolder, path))
|
||||
}
|
||||
|
||||
func (driver SFTP) Move(src string, dst string, account *model.Account) error {
|
||||
return driver.Rename(src, dst, account)
|
||||
}
|
||||
|
||||
func (driver SFTP) Rename(src string, dst string, account *model.Account) error {
|
||||
client, err := GetClient(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Rename(utils.Join(account.RootFolder, src), utils.Join(account.RootFolder, dst))
|
||||
}
|
||||
|
||||
func (driver SFTP) Copy(src string, dst string, account *model.Account) error {
|
||||
return base.ErrNotSupport
|
||||
}
|
||||
|
||||
func (driver SFTP) Delete(path string, account *model.Account) error {
|
||||
client, err := GetClient(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.remove(utils.Join(account.RootFolder, path))
|
||||
}
|
||||
|
||||
func (driver SFTP) Upload(file *model.FileStream, account *model.Account) error {
|
||||
if file == nil {
|
||||
return base.ErrEmptyFile
|
||||
}
|
||||
client, err := GetClient(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dstFile, err := client.Create(path.Join(account.RootFolder, file.ParentPath, file.Name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() {
|
||||
_ = dstFile.Close()
|
||||
}()
|
||||
_, err = io.Copy(dstFile, file)
|
||||
return err
|
||||
}
|
||||
|
||||
var _ base.Driver = (*SFTP)(nil)
|
110
drivers/sftp/sftp.go
Normal file
110
drivers/sftp/sftp.go
Normal file
@ -0,0 +1,110 @@
|
||||
package template
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/pkg/sftp"
|
||||
"golang.org/x/crypto/ssh"
|
||||
"os"
|
||||
"path"
|
||||
"sync"
|
||||
)
|
||||
|
||||
var clientsMap = struct {
|
||||
sync.Mutex
|
||||
clients map[string]*Client
|
||||
}{clients: make(map[string]*Client)}
|
||||
|
||||
func GetClient(account *model.Account) (*Client, error) {
|
||||
clientsMap.Lock()
|
||||
defer clientsMap.Unlock()
|
||||
if v, ok := clientsMap.clients[account.Name]; ok {
|
||||
return v, nil
|
||||
}
|
||||
conn, err := ssh.Dial("tcp", fmt.Sprintf("%s:%d", account.SiteUrl, account.Limit), &ssh.ClientConfig{
|
||||
User: account.Username,
|
||||
Auth: []ssh.AuthMethod{ssh.Password(account.Password)},
|
||||
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client, err := sftp.NewClient(conn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c := &Client{client}
|
||||
clientsMap.clients[account.Name] = c
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
*sftp.Client
|
||||
}
|
||||
|
||||
func (client *Client) Files(remotePath string) ([]os.FileInfo, error) {
|
||||
return client.ReadDir(remotePath)
|
||||
}
|
||||
|
||||
func (client *Client) remove(remotePath string) error {
|
||||
f, err := client.Stat(remotePath)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
if f.IsDir() {
|
||||
return client.removeDirectory(remotePath)
|
||||
} else {
|
||||
return client.removeFile(remotePath)
|
||||
}
|
||||
}
|
||||
|
||||
func (client *Client) removeDirectory(remotePath string) error {
|
||||
//打不开,说明要么文件路径错误了,要么是第一次部署
|
||||
remoteFiles, err := client.ReadDir(remotePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, backupDir := range remoteFiles {
|
||||
remoteFilePath := path.Join(remotePath, backupDir.Name())
|
||||
if backupDir.IsDir() {
|
||||
err := client.removeDirectory(remoteFilePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
err := client.Remove(path.Join(remoteFilePath))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return client.RemoveDirectory(remotePath)
|
||||
}
|
||||
|
||||
func (client *Client) removeFile(remotePath string) error {
|
||||
return client.Remove(utils.Join(remotePath))
|
||||
}
|
||||
|
||||
func (driver SFTP) formatFile(f os.FileInfo) model.File {
|
||||
t := f.ModTime()
|
||||
file := model.File{
|
||||
//Id: f.Id,
|
||||
Name: f.Name(),
|
||||
Size: f.Size(),
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: &t,
|
||||
}
|
||||
if f.IsDir() {
|
||||
file.Type = conf.FOLDER
|
||||
} else {
|
||||
file.Type = utils.GetFileType(path.Ext(f.Name()))
|
||||
}
|
||||
return file
|
||||
}
|
||||
|
||||
func init() {
|
||||
base.RegisterDriver(&SFTP{})
|
||||
}
|
18
drivers/sftp/types.go
Normal file
18
drivers/sftp/types.go
Normal file
@ -0,0 +1,18 @@
|
||||
package template
|
||||
|
||||
import "time"
|
||||
|
||||
// write all struct here
|
||||
|
||||
type Resp struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type File struct {
|
||||
Id string `json:"id"`
|
||||
FileName string `json:"file_name"`
|
||||
Size int64 `json:"size"`
|
||||
File bool `json:"file"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
}
|
3
drivers/sftp/util.go
Normal file
3
drivers/sftp/util.go
Normal file
@ -0,0 +1,3 @@
|
||||
package template
|
||||
|
||||
// write util func here, such as cal sign
|
@ -98,7 +98,7 @@ func (driver Teambition) GetFiles(parentId string, account *model.Account) ([]mo
|
||||
Size: 0,
|
||||
Type: conf.FOLDER,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: &collection.Updated,
|
||||
UpdatedAt: collection.Updated,
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -126,7 +126,7 @@ func (driver Teambition) GetFiles(parentId string, account *model.Account) ([]mo
|
||||
Size: work.FileSize,
|
||||
Type: utils.GetFileType(path.Ext(work.FileName)),
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: &work.Updated,
|
||||
UpdatedAt: work.Updated,
|
||||
Thumbnail: work.Thumbnail,
|
||||
Url: work.DownloadURL,
|
||||
})
|
||||
|
@ -3,22 +3,22 @@ package teambition
|
||||
import "time"
|
||||
|
||||
type Collection struct {
|
||||
ID string `json:"_id"`
|
||||
Title string `json:"title"`
|
||||
Updated time.Time `json:"updated"`
|
||||
ID string `json:"_id"`
|
||||
Title string `json:"title"`
|
||||
Updated *time.Time `json:"updated"`
|
||||
}
|
||||
|
||||
type Work struct {
|
||||
ID string `json:"_id"`
|
||||
FileName string `json:"fileName"`
|
||||
FileSize int64 `json:"fileSize"`
|
||||
FileKey string `json:"fileKey"`
|
||||
FileCategory string `json:"fileCategory"`
|
||||
DownloadURL string `json:"downloadUrl"`
|
||||
ThumbnailURL string `json:"thumbnailUrl"`
|
||||
Thumbnail string `json:"thumbnail"`
|
||||
Updated time.Time `json:"updated"`
|
||||
PreviewURL string `json:"previewUrl"`
|
||||
ID string `json:"_id"`
|
||||
FileName string `json:"fileName"`
|
||||
FileSize int64 `json:"fileSize"`
|
||||
FileKey string `json:"fileKey"`
|
||||
FileCategory string `json:"fileCategory"`
|
||||
DownloadURL string `json:"downloadUrl"`
|
||||
ThumbnailURL string `json:"thumbnailUrl"`
|
||||
Thumbnail string `json:"thumbnail"`
|
||||
Updated *time.Time `json:"updated"`
|
||||
PreviewURL string `json:"previewUrl"`
|
||||
}
|
||||
|
||||
type FileUpload struct {
|
||||
|
151
drivers/template/driver.go
Normal file
151
drivers/template/driver.go
Normal file
@ -0,0 +1,151 @@
|
||||
package template
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
type Template struct {
|
||||
base.Base
|
||||
}
|
||||
|
||||
func (driver Template) Config() base.DriverConfig {
|
||||
return base.DriverConfig{
|
||||
Name: "Template",
|
||||
OnlyProxy: false,
|
||||
OnlyLocal: false,
|
||||
ApiProxy: false,
|
||||
NoNeedSetLink: false,
|
||||
NoCors: false,
|
||||
LocalSort: false,
|
||||
}
|
||||
}
|
||||
|
||||
func (driver Template) Items() []base.Item {
|
||||
// TODO fill need info
|
||||
return []base.Item{
|
||||
{
|
||||
Name: "refresh_token",
|
||||
Label: "refresh token",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "root_folder",
|
||||
Label: "root folder path",
|
||||
Type: base.TypeString,
|
||||
Default: "/",
|
||||
Required: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (driver Template) Save(account *model.Account, old *model.Account) error {
|
||||
// TODO test available or init
|
||||
return nil
|
||||
}
|
||||
|
||||
func (driver Template) File(path string, account *model.Account) (*model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
if path == "/" {
|
||||
return &model.File{
|
||||
Id: account.RootFolder,
|
||||
Name: account.Name,
|
||||
Size: 0,
|
||||
Type: conf.FOLDER,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: account.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
dir, name := filepath.Split(path)
|
||||
files, err := driver.Files(dir, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range files {
|
||||
if file.Name == name {
|
||||
return &file, nil
|
||||
}
|
||||
}
|
||||
return nil, base.ErrPathNotFound
|
||||
}
|
||||
|
||||
func (driver Template) Files(path string, account *model.Account) ([]model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
cache, err := base.GetCache(path, account)
|
||||
if err == nil {
|
||||
files, _ := cache.([]model.File)
|
||||
return files, nil
|
||||
}
|
||||
var files []model.File
|
||||
// TODO get files
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(files) > 0 {
|
||||
_ = base.SetCache(path, files, account)
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func (driver Template) Link(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
// TODO get file link
|
||||
return nil, base.ErrNotImplement
|
||||
}
|
||||
|
||||
func (driver Template) Path(path string, account *model.Account) (*model.File, []model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !file.IsDir() {
|
||||
return file, nil, nil
|
||||
}
|
||||
files, err := driver.Files(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, files, nil
|
||||
}
|
||||
|
||||
// Optional function
|
||||
//func (driver Template) Preview(path string, account *model.Account) (interface{}, error) {
|
||||
// //TODO preview interface if driver support
|
||||
// return nil, base.ErrNotImplement
|
||||
//}
|
||||
//
|
||||
//func (driver Template) MakeDir(path string, account *model.Account) error {
|
||||
// //TODO make dir
|
||||
// return base.ErrNotImplement
|
||||
//}
|
||||
//
|
||||
//func (driver Template) Move(src string, dst string, account *model.Account) error {
|
||||
// //TODO move file/dir
|
||||
// return base.ErrNotImplement
|
||||
//}
|
||||
//
|
||||
//func (driver Template) Rename(src string, dst string, account *model.Account) error {
|
||||
// //TODO rename file/dir
|
||||
// return base.ErrNotImplement
|
||||
//}
|
||||
//
|
||||
//func (driver Template) Copy(src string, dst string, account *model.Account) error {
|
||||
// //TODO copy file/dir
|
||||
// return base.ErrNotImplement
|
||||
//}
|
||||
//
|
||||
//func (driver Template) Delete(path string, account *model.Account) error {
|
||||
// //TODO delete file/dir
|
||||
// return base.ErrNotImplement
|
||||
//}
|
||||
//
|
||||
//func (driver Template) Upload(file *model.FileStream, account *model.Account) error {
|
||||
// //TODO upload file
|
||||
// return base.ErrNotImplement
|
||||
//}
|
||||
|
||||
var _ base.Driver = (*Template)(nil)
|
90
drivers/template/template.go
Normal file
90
drivers/template/template.go
Normal file
@ -0,0 +1,90 @@
|
||||
package template
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/go-resty/resty/v2"
|
||||
"path"
|
||||
)
|
||||
|
||||
func LoginOrRefreshToken(account *model.Account) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func Request(u string, method int, headers, query, form map[string]string, data interface{}, resp interface{}, account *model.Account) ([]byte, error) {
|
||||
req := base.RestyClient.R()
|
||||
req.SetHeaders(map[string]string{
|
||||
"Authorization": "Bearer" + account.AccessToken,
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
})
|
||||
if headers != nil {
|
||||
req.SetHeaders(headers)
|
||||
}
|
||||
if query != nil {
|
||||
req.SetQueryParams(query)
|
||||
}
|
||||
if form != nil {
|
||||
req.SetFormData(form)
|
||||
}
|
||||
if data != nil {
|
||||
req.SetBody(data)
|
||||
}
|
||||
if resp != nil {
|
||||
req.SetResult(resp)
|
||||
}
|
||||
var e Resp
|
||||
var err error
|
||||
var res *resty.Response
|
||||
req.SetError(&e)
|
||||
switch method {
|
||||
case base.Get:
|
||||
res, err = req.Get(u)
|
||||
case base.Post:
|
||||
res, err = req.Post(u)
|
||||
case base.Delete:
|
||||
res, err = req.Delete(u)
|
||||
case base.Patch:
|
||||
res, err = req.Patch(u)
|
||||
case base.Put:
|
||||
res, err = req.Put(u)
|
||||
default:
|
||||
return nil, base.ErrNotSupport
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if e.Code >= 400 {
|
||||
if e.Code == 401 {
|
||||
err = LoginOrRefreshToken(account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return Request(u, method, headers, query, form, data, resp, account)
|
||||
}
|
||||
return nil, errors.New(e.Message)
|
||||
}
|
||||
return res.Body(), nil
|
||||
}
|
||||
|
||||
func (driver Template) formatFile(f *File) *model.File {
|
||||
file := model.File{
|
||||
Id: f.Id,
|
||||
Name: f.FileName,
|
||||
Size: f.Size,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: f.UpdatedAt,
|
||||
}
|
||||
if f.File {
|
||||
file.Type = utils.GetFileType(path.Ext(f.FileName))
|
||||
} else {
|
||||
file.Type = conf.FOLDER
|
||||
}
|
||||
return &file
|
||||
}
|
||||
|
||||
func init() {
|
||||
base.RegisterDriver(&Template{})
|
||||
}
|
18
drivers/template/types.go
Normal file
18
drivers/template/types.go
Normal file
@ -0,0 +1,18 @@
|
||||
package template
|
||||
|
||||
import "time"
|
||||
|
||||
// write all struct here
|
||||
|
||||
type Resp struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
type File struct {
|
||||
Id string `json:"id"`
|
||||
FileName string `json:"file_name"`
|
||||
Size int64 `json:"size"`
|
||||
File bool `json:"file"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
}
|
3
drivers/template/util.go
Normal file
3
drivers/template/util.go
Normal file
@ -0,0 +1,3 @@
|
||||
package template
|
||||
|
||||
// write util func here, such as cal sign
|
237
drivers/uss/driver.go
Normal file
237
drivers/uss/driver.go
Normal file
@ -0,0 +1,237 @@
|
||||
package uss
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"github.com/upyun/go-sdk/v3/upyun"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type USS struct {
|
||||
}
|
||||
|
||||
func (driver USS) Config() base.DriverConfig {
|
||||
return base.DriverConfig{
|
||||
Name: "USS",
|
||||
LocalSort: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (driver USS) Items() []base.Item {
|
||||
return []base.Item{
|
||||
{
|
||||
Name: "bucket",
|
||||
Label: "Bucket",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "endpoint",
|
||||
Label: "Endpoint",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "access_key",
|
||||
Label: "Operator Name",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "access_secret",
|
||||
Label: "Operator Password",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "root_folder",
|
||||
Label: "root folder path",
|
||||
Type: base.TypeString,
|
||||
Required: false,
|
||||
},
|
||||
{
|
||||
Name: "custom_host",
|
||||
Label: "Custom Host",
|
||||
Type: base.TypeString,
|
||||
},
|
||||
{
|
||||
Name: "limit",
|
||||
Label: "Sign url expire time(hours)",
|
||||
Type: base.TypeNumber,
|
||||
Default: "4",
|
||||
Description: "default 4 hours",
|
||||
},
|
||||
//{
|
||||
// Name: "zone",
|
||||
// Label: "placeholder filename",
|
||||
// Type: base.TypeString,
|
||||
// Description: "default empty string",
|
||||
//},
|
||||
}
|
||||
}
|
||||
|
||||
func (driver USS) Save(account *model.Account, old *model.Account) error {
|
||||
if account == nil {
|
||||
return nil
|
||||
}
|
||||
if account.Limit == 0 {
|
||||
account.Limit = 4
|
||||
}
|
||||
client, err := driver.NewUpYun(account)
|
||||
if err != nil {
|
||||
account.Status = err.Error()
|
||||
} else {
|
||||
clientsMap[account.Name] = client
|
||||
account.Status = "work"
|
||||
}
|
||||
_ = model.SaveAccount(account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver USS) File(path string, account *model.Account) (*model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
if path == "/" {
|
||||
return &model.File{
|
||||
Id: account.RootFolder,
|
||||
Name: account.Name,
|
||||
Size: 0,
|
||||
Type: conf.FOLDER,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: account.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
dir, name := filepath.Split(path)
|
||||
files, err := driver.Files(dir, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range files {
|
||||
if file.Name == name {
|
||||
return &file, nil
|
||||
}
|
||||
}
|
||||
return nil, base.ErrPathNotFound
|
||||
}
|
||||
|
||||
func (driver USS) Files(path string, account *model.Account) ([]model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
var files []model.File
|
||||
cache, err := base.GetCache(path, account)
|
||||
if err == nil {
|
||||
files, _ = cache.([]model.File)
|
||||
} else {
|
||||
files, err = driver.List(path, account)
|
||||
if err == nil && len(files) > 0 {
|
||||
_ = base.SetCache(path, files, account)
|
||||
}
|
||||
}
|
||||
return files, err
|
||||
}
|
||||
|
||||
func (driver USS) Link(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
key := driver.GetKey(args.Path, account, false)
|
||||
host := account.CustomHost
|
||||
if host == "" {
|
||||
host = account.Endpoint
|
||||
}
|
||||
if strings.Contains(host, "://") {
|
||||
host = "https://" + host
|
||||
}
|
||||
u := fmt.Sprintf("%s/%s", host, key)
|
||||
downExp := time.Hour * time.Duration(account.Limit)
|
||||
expireAt := time.Now().Add(downExp).Unix()
|
||||
upd := url.QueryEscape(utils.Base(args.Path))
|
||||
signStr := strings.Join([]string{account.AccessSecret, fmt.Sprint(expireAt), fmt.Sprintf("/%s", key)}, "&")
|
||||
upt := utils.GetMD5Encode(signStr)[12:20] + fmt.Sprint(expireAt)
|
||||
link := fmt.Sprintf("%s?_upd=%s&_upt=%s", u, upd, upt)
|
||||
return &base.Link{Url: link}, nil
|
||||
}
|
||||
|
||||
func (driver USS) Path(path string, account *model.Account) (*model.File, []model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
log.Debugf("s3 path: %s", path)
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !file.IsDir() {
|
||||
return file, nil, nil
|
||||
}
|
||||
files, err := driver.Files(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, files, nil
|
||||
}
|
||||
|
||||
func (driver USS) Preview(path string, account *model.Account) (interface{}, error) {
|
||||
return nil, base.ErrNotSupport
|
||||
}
|
||||
|
||||
func (driver USS) MakeDir(path string, account *model.Account) error {
|
||||
client, err := driver.GetClient(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Mkdir(driver.GetKey(path, account, true))
|
||||
}
|
||||
|
||||
func (driver USS) Move(src string, dst string, account *model.Account) error {
|
||||
client, err := driver.GetClient(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Move(&upyun.MoveObjectConfig{
|
||||
SrcPath: driver.GetKey(src, account, false),
|
||||
DestPath: driver.GetKey(dst, account, false),
|
||||
})
|
||||
}
|
||||
|
||||
func (driver USS) Rename(src string, dst string, account *model.Account) error {
|
||||
return driver.Move(src, dst, account)
|
||||
}
|
||||
|
||||
func (driver USS) Copy(src string, dst string, account *model.Account) error {
|
||||
client, err := driver.GetClient(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Copy(&upyun.CopyObjectConfig{
|
||||
SrcPath: driver.GetKey(src, account, false),
|
||||
DestPath: driver.GetKey(dst, account, false),
|
||||
})
|
||||
}
|
||||
|
||||
func (driver USS) Delete(path string, account *model.Account) error {
|
||||
client, err := driver.GetClient(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Delete(&upyun.DeleteObjectConfig{
|
||||
Path: driver.GetKey(path, account, false),
|
||||
Async: false,
|
||||
})
|
||||
}
|
||||
|
||||
func (driver USS) Upload(file *model.FileStream, account *model.Account) error {
|
||||
if file == nil {
|
||||
return base.ErrEmptyFile
|
||||
}
|
||||
client, err := driver.GetClient(account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.Put(&upyun.PutObjectConfig{
|
||||
Path: driver.GetKey(utils.Join(file.ParentPath, file.GetFileName()), account, false),
|
||||
Reader: file,
|
||||
})
|
||||
}
|
||||
|
||||
var _ base.Driver = (*USS)(nil)
|
82
drivers/uss/uss.go
Normal file
82
drivers/uss/uss.go
Normal file
@ -0,0 +1,82 @@
|
||||
package uss
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/upyun/go-sdk/v3/upyun"
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var clientsMap map[string]*upyun.UpYun
|
||||
|
||||
func (driver USS) NewUpYun(account *model.Account) (*upyun.UpYun, error) {
|
||||
return upyun.NewUpYun(&upyun.UpYunConfig{
|
||||
Bucket: account.Bucket,
|
||||
Operator: account.AccessKey,
|
||||
Password: account.AccessToken,
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (driver USS) GetClient(account *model.Account) (*upyun.UpYun, error) {
|
||||
client, ok := clientsMap[account.Name]
|
||||
if ok {
|
||||
return client, nil
|
||||
}
|
||||
return nil, errors.New("can't get client")
|
||||
}
|
||||
|
||||
func (driver USS) List(prefix string, account *model.Account) ([]model.File, error) {
|
||||
prefix = driver.GetKey(prefix, account, true)
|
||||
client, err := driver.GetClient(account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
objsChan := make(chan *upyun.FileInfo, 10)
|
||||
defer close(objsChan)
|
||||
go func() {
|
||||
err = client.List(&upyun.GetObjectsConfig{
|
||||
Path: prefix,
|
||||
ObjectsChan: objsChan,
|
||||
MaxListObjects: 0,
|
||||
MaxListLevel: 1,
|
||||
})
|
||||
}()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res := make([]model.File, 0)
|
||||
for obj := range objsChan {
|
||||
t := obj.Time
|
||||
f := model.File{
|
||||
Name: obj.Name,
|
||||
Size: obj.Size,
|
||||
UpdatedAt: &t,
|
||||
Driver: driver.Config().Name,
|
||||
}
|
||||
if obj.IsDir {
|
||||
f.Type = conf.FOLDER
|
||||
} else {
|
||||
f.Type = utils.GetFileType(path.Ext(obj.Name))
|
||||
}
|
||||
res = append(res, f)
|
||||
}
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (driver USS) GetKey(path string, account *model.Account, dir bool) string {
|
||||
path = utils.Join(account.RootFolder, path)
|
||||
path = strings.TrimPrefix(path, "/")
|
||||
if dir {
|
||||
path += "/"
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func init() {
|
||||
clientsMap = make(map[string]*upyun.UpYun)
|
||||
base.RegisterDriver(&USS{})
|
||||
}
|
@ -3,8 +3,10 @@ package webdav
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/drivers/webdav/odrvcookie"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
@ -40,6 +42,15 @@ func (driver WebDav) Items() []base.Item {
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "internal_type",
|
||||
Label: "vendor",
|
||||
Type: base.TypeSelect,
|
||||
Required: true,
|
||||
Default: "other",
|
||||
Values: "sharepoint,other",
|
||||
Description: "webdav vendor",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@ -47,9 +58,17 @@ func (driver WebDav) Save(account *model.Account, old *model.Account) error {
|
||||
if account == nil {
|
||||
return nil
|
||||
}
|
||||
account.Status = "work"
|
||||
var err error
|
||||
if isSharePoint(account) {
|
||||
_, err = odrvcookie.GetCookie(account.Username, account.Password, account.SiteUrl)
|
||||
}
|
||||
if err != nil {
|
||||
account.Status = err.Error()
|
||||
} else {
|
||||
account.Status = "work"
|
||||
}
|
||||
_ = model.SaveAccount(account)
|
||||
return nil
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver WebDav) File(path string, account *model.Account) (*model.File, error) {
|
||||
@ -114,11 +133,27 @@ func (driver WebDav) Files(path string, account *model.Account) ([]model.File, e
|
||||
func (driver WebDav) Link(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
path := args.Path
|
||||
c := driver.NewClient(account)
|
||||
reader, err := c.ReadStream(driver.WebDavPath(path))
|
||||
callback := func(r *http.Request) {
|
||||
if args.Header.Get("Range") != "" {
|
||||
r.Header.Set("Range", args.Header.Get("Range"))
|
||||
}
|
||||
if args.Header.Get("If-Range") != "" {
|
||||
r.Header.Set("If-Range", args.Header.Get("If-Range"))
|
||||
}
|
||||
}
|
||||
reader, header, err := c.ReadStream(driver.WebDavPath(path), callback)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &base.Link{Data: reader}, nil
|
||||
link := &base.Link{Data: reader}
|
||||
if header.Get("Content-Range") != "" {
|
||||
link.Status = 206
|
||||
link.Header = http.Header{
|
||||
"Content-Range": header.Values("Content-Range"),
|
||||
"Content-Length": header.Values("Content-Length"),
|
||||
}
|
||||
}
|
||||
return link, nil
|
||||
}
|
||||
|
||||
func (driver WebDav) Path(path string, account *model.Account) (*model.File, []model.File, error) {
|
||||
@ -178,7 +213,11 @@ func (driver WebDav) Upload(file *model.FileStream, account *model.Account) erro
|
||||
}
|
||||
c := driver.NewClient(account)
|
||||
path := utils.Join(file.ParentPath, file.Name)
|
||||
err := c.WriteStream(driver.WebDavPath(path), file, 0644)
|
||||
callback := func(r *http.Request) {
|
||||
r.Header.Set("Content-Type", file.GetMIMEType())
|
||||
r.ContentLength = int64(file.GetSize())
|
||||
}
|
||||
err := c.WriteStream(driver.WebDavPath(path), file, 0644, callback)
|
||||
return err
|
||||
}
|
||||
|
||||
|
47
drivers/webdav/odrvcookie/cookie.go
Normal file
47
drivers/webdav/odrvcookie/cookie.go
Normal file
@ -0,0 +1,47 @@
|
||||
package odrvcookie
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/utils/cookie"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type SpCookie struct {
|
||||
Cookie string
|
||||
expire time.Time
|
||||
}
|
||||
|
||||
func (sp SpCookie) IsExpire() bool {
|
||||
return time.Now().After(sp.expire)
|
||||
}
|
||||
|
||||
var cookiesMap = struct {
|
||||
sync.Mutex
|
||||
m map[string]*SpCookie
|
||||
}{m: make(map[string]*SpCookie)}
|
||||
|
||||
func GetCookie(username, password, siteUrl string) (string, error) {
|
||||
cookiesMap.Lock()
|
||||
defer cookiesMap.Unlock()
|
||||
spCookie, ok := cookiesMap.m[username]
|
||||
if ok {
|
||||
if !spCookie.IsExpire() {
|
||||
log.Debugln("sp use old cookie.")
|
||||
return spCookie.Cookie, nil
|
||||
}
|
||||
}
|
||||
log.Debugln("fetch new cookie")
|
||||
ca := New(username, password, siteUrl)
|
||||
tokenConf, err := ca.Cookies()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
spCookie = &SpCookie{
|
||||
Cookie: cookie.ToString([]*http.Cookie{&tokenConf.RtFa, &tokenConf.FedAuth}),
|
||||
expire: time.Now().Add(time.Hour * 12),
|
||||
}
|
||||
cookiesMap.m[username] = spCookie
|
||||
return spCookie.Cookie, nil
|
||||
}
|
206
drivers/webdav/odrvcookie/fetch.go
Normal file
206
drivers/webdav/odrvcookie/fetch.go
Normal file
@ -0,0 +1,206 @@
|
||||
// Package odrvcookie can fetch authentication cookies for a sharepoint webdav endpoint
|
||||
package odrvcookie
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"net/http/cookiejar"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/publicsuffix"
|
||||
)
|
||||
|
||||
// CookieAuth hold the authentication information
|
||||
// These are username and password as well as the authentication endpoint
|
||||
type CookieAuth struct {
|
||||
user string
|
||||
pass string
|
||||
endpoint string
|
||||
}
|
||||
|
||||
// CookieResponse contains the requested cookies
|
||||
type CookieResponse struct {
|
||||
RtFa http.Cookie
|
||||
FedAuth http.Cookie
|
||||
}
|
||||
|
||||
// SuccessResponse hold a response from the sharepoint webdav
|
||||
type SuccessResponse struct {
|
||||
XMLName xml.Name `xml:"Envelope"`
|
||||
Succ SuccessResponseBody `xml:"Body"`
|
||||
}
|
||||
|
||||
// SuccessResponseBody is the body of a success response, it holds the token
|
||||
type SuccessResponseBody struct {
|
||||
XMLName xml.Name
|
||||
Type string `xml:"RequestSecurityTokenResponse>TokenType"`
|
||||
Created time.Time `xml:"RequestSecurityTokenResponse>Lifetime>Created"`
|
||||
Expires time.Time `xml:"RequestSecurityTokenResponse>Lifetime>Expires"`
|
||||
Token string `xml:"RequestSecurityTokenResponse>RequestedSecurityToken>BinarySecurityToken"`
|
||||
}
|
||||
|
||||
// reqString is a template that gets populated with the user data in order to retrieve a "BinarySecurityToken"
|
||||
const reqString = `<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope"
|
||||
xmlns:a="http://www.w3.org/2005/08/addressing"
|
||||
xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
|
||||
<s:Header>
|
||||
<a:Action s:mustUnderstand="1">http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue</a:Action>
|
||||
<a:ReplyTo>
|
||||
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
|
||||
</a:ReplyTo>
|
||||
<a:To s:mustUnderstand="1">{{ .LoginUrl }}</a:To>
|
||||
<o:Security s:mustUnderstand="1"
|
||||
xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
|
||||
<o:UsernameToken>
|
||||
<o:Username>{{ .Username }}</o:Username>
|
||||
<o:Password>{{ .Password }}</o:Password>
|
||||
</o:UsernameToken>
|
||||
</o:Security>
|
||||
</s:Header>
|
||||
<s:Body>
|
||||
<t:RequestSecurityToken xmlns:t="http://schemas.xmlsoap.org/ws/2005/02/trust">
|
||||
<wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
|
||||
<a:EndpointReference>
|
||||
<a:Address>{{ .Address }}</a:Address>
|
||||
</a:EndpointReference>
|
||||
</wsp:AppliesTo>
|
||||
<t:KeyType>http://schemas.xmlsoap.org/ws/2005/05/identity/NoProofKey</t:KeyType>
|
||||
<t:RequestType>http://schemas.xmlsoap.org/ws/2005/02/trust/Issue</t:RequestType>
|
||||
<t:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</t:TokenType>
|
||||
</t:RequestSecurityToken>
|
||||
</s:Body>
|
||||
</s:Envelope>`
|
||||
|
||||
// New creates a new CookieAuth struct
|
||||
func New(pUser, pPass, pEndpoint string) CookieAuth {
|
||||
retStruct := CookieAuth{
|
||||
user: pUser,
|
||||
pass: pPass,
|
||||
endpoint: pEndpoint,
|
||||
}
|
||||
|
||||
return retStruct
|
||||
}
|
||||
|
||||
// Cookies creates a CookieResponse. It fetches the auth token and then
|
||||
// retrieves the Cookies
|
||||
func (ca *CookieAuth) Cookies() (CookieResponse, error) {
|
||||
spToken, err := ca.getSPToken()
|
||||
if err != nil {
|
||||
return CookieResponse{}, err
|
||||
}
|
||||
return ca.getSPCookie(spToken)
|
||||
}
|
||||
|
||||
func (ca *CookieAuth) getSPCookie(conf *SuccessResponse) (CookieResponse, error) {
|
||||
spRoot, err := url.Parse(ca.endpoint)
|
||||
if err != nil {
|
||||
return CookieResponse{}, err
|
||||
}
|
||||
|
||||
u, err := url.Parse("https://" + spRoot.Host + "/_forms/default.aspx?wa=wsignin1.0")
|
||||
if err != nil {
|
||||
return CookieResponse{}, err
|
||||
}
|
||||
|
||||
// To authenticate with davfs or anything else we need two cookies (rtFa and FedAuth)
|
||||
// In order to get them we use the token we got earlier and a cookieJar
|
||||
jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
|
||||
if err != nil {
|
||||
return CookieResponse{}, err
|
||||
}
|
||||
|
||||
client := &http.Client{
|
||||
Jar: jar,
|
||||
}
|
||||
|
||||
// Send the previously aquired Token as a Post parameter
|
||||
if _, err = client.Post(u.String(), "text/xml", strings.NewReader(conf.Succ.Token)); err != nil {
|
||||
return CookieResponse{}, err
|
||||
}
|
||||
|
||||
cookieResponse := CookieResponse{}
|
||||
for _, cookie := range jar.Cookies(u) {
|
||||
if (cookie.Name == "rtFa") || (cookie.Name == "FedAuth") {
|
||||
switch cookie.Name {
|
||||
case "rtFa":
|
||||
cookieResponse.RtFa = *cookie
|
||||
case "FedAuth":
|
||||
cookieResponse.FedAuth = *cookie
|
||||
}
|
||||
}
|
||||
}
|
||||
return cookieResponse, err
|
||||
}
|
||||
|
||||
var loginUrlsMap = map[string]string{
|
||||
"com": "https://login.microsoftonline.com",
|
||||
"cn": "https://login.chinacloudapi.cn",
|
||||
"us": "https://login.microsoftonline.us",
|
||||
"de": "https://login.microsoftonline.de",
|
||||
}
|
||||
|
||||
func getLoginUrl(endpoint string) (string, error) {
|
||||
spRoot, err := url.Parse(endpoint)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
domains := strings.Split(spRoot.Host, ".")
|
||||
tld := domains[len(domains)-1]
|
||||
loginUrl, ok := loginUrlsMap[tld]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("tld %s is not supported", tld)
|
||||
}
|
||||
return loginUrl + "/extSTS.srf", nil
|
||||
}
|
||||
|
||||
func (ca *CookieAuth) getSPToken() (*SuccessResponse, error) {
|
||||
loginUrl, err := getLoginUrl(ca.endpoint)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
reqData := map[string]string{
|
||||
"Username": ca.user,
|
||||
"Password": ca.pass,
|
||||
"Address": ca.endpoint,
|
||||
"LoginUrl": loginUrl,
|
||||
}
|
||||
|
||||
t := template.Must(template.New("authXML").Parse(reqString))
|
||||
|
||||
buf := &bytes.Buffer{}
|
||||
if err := t.Execute(buf, reqData); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Execute the first request which gives us an auth token for the sharepoint service
|
||||
// With this token we can authenticate on the login page and save the returned cookies
|
||||
req, err := http.NewRequest("POST", loginUrl, buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client := &http.Client{}
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
respBuf := bytes.Buffer{}
|
||||
respBuf.ReadFrom(resp.Body)
|
||||
s := respBuf.Bytes()
|
||||
|
||||
var conf SuccessResponse
|
||||
err = xml.Unmarshal(s, &conf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &conf, err
|
||||
}
|
7
drivers/webdav/util.go
Normal file
7
drivers/webdav/util.go
Normal file
@ -0,0 +1,7 @@
|
||||
package webdav
|
||||
|
||||
import "github.com/Xhofe/alist/model"
|
||||
|
||||
func isSharePoint(account *model.Account) bool {
|
||||
return account.InternalType == "sharepoint"
|
||||
}
|
@ -2,14 +2,26 @@ package webdav
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/drivers/webdav/odrvcookie"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/pkg/gowebdav"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/studio-b12/gowebdav"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (driver WebDav) NewClient(account *model.Account) *gowebdav.Client {
|
||||
return gowebdav.NewClient(account.SiteUrl, account.Username, account.Password)
|
||||
c := gowebdav.NewClient(account.SiteUrl, account.Username, account.Password)
|
||||
if isSharePoint(account) {
|
||||
cookie, err := odrvcookie.GetCookie(account.Username, account.Password, account.SiteUrl)
|
||||
if err == nil {
|
||||
c.SetInterceptor(func(method string, rq *http.Request) {
|
||||
rq.Header.Del("Authorization")
|
||||
rq.Header.Set("Cookie", cookie)
|
||||
})
|
||||
}
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
func (driver WebDav) WebDavPath(path string) string {
|
||||
|
419
drivers/xunlei/driver.go
Normal file
419
drivers/xunlei/driver.go
Normal file
@ -0,0 +1,419 @@
|
||||
package xunlei
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/s3/s3manager"
|
||||
"github.com/go-resty/resty/v2"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type XunLeiCloud struct{}
|
||||
|
||||
func init() {
|
||||
base.RegisterDriver(new(XunLeiCloud))
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Config() base.DriverConfig {
|
||||
return base.DriverConfig{
|
||||
Name: "XunLeiCloud",
|
||||
LocalSort: true,
|
||||
}
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Items() []base.Item {
|
||||
return []base.Item{
|
||||
{
|
||||
Name: "username",
|
||||
Label: "username",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
Description: "account username/phone number",
|
||||
},
|
||||
{
|
||||
Name: "password",
|
||||
Label: "password",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
Description: "account password",
|
||||
},
|
||||
{
|
||||
Name: "captcha_token",
|
||||
Label: "verified captcha token",
|
||||
Type: base.TypeString,
|
||||
},
|
||||
{
|
||||
Name: "root_folder",
|
||||
Label: "root folder file_id",
|
||||
Type: base.TypeString,
|
||||
},
|
||||
{
|
||||
Name: "client_version",
|
||||
Label: "client version",
|
||||
Default: "7.43.0.7998",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "client_id",
|
||||
Label: "client id",
|
||||
Default: "Xp6vsxz_7IYVw2BB",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "client_secret",
|
||||
Label: "client secret",
|
||||
Default: "Xp6vsy4tN9toTVdMSpomVdXpRmES",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "algorithms",
|
||||
Label: "algorithms",
|
||||
Default: "hrVPGbeqYPs+CIscj05VpAtjalzY5yjpvlMS8bEo,DrI0uTP,HHK0VXyMgY0xk2K0o,BBaXsExvL3GadmIacjWv7ISUJp3ifAwqbJumu,5toJ7ejB+bh1,5LsZTFAFjgvFvIl1URBgOAJ,QcJ5Ry+,hYgZVz8r7REROaCYfd9,zw6gXgkk/8TtGrmx6EGfekPESLnbZfDFwqR,gtSwLnMBa8h12nF3DU6+LwEQPHxd,fMG8TvtAYbCkxuEbIm0Xi/Lb7Z",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "package_name",
|
||||
Label: "package name",
|
||||
Default: "com.xunlei.downloadprovider",
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
{
|
||||
Name: "user_agent",
|
||||
Label: "user agent",
|
||||
Default: "ANDROID-com.xunlei.downloadprovider/7.43.0.7998 netWorkType/WIFI appid/40 deviceName/Samsung_Sm-g9810 deviceModel/SM-G9810 OSVersion/7.1.2 protocolVersion/301 platformVersion/10 sdkVersion/220200 Oauth2Client/0.9 (Linux 4_0_9+) (JAVA 0)",
|
||||
Type: base.TypeString,
|
||||
Required: false,
|
||||
},
|
||||
{
|
||||
Name: "device_id",
|
||||
Label: "device id",
|
||||
Default: utils.GetMD5Encode(uuid.NewString()),
|
||||
Type: base.TypeString,
|
||||
Required: true,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Save(account *model.Account, old *model.Account) error {
|
||||
if account == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
client := GetClient(account)
|
||||
// 指定验证通过的captchaToken
|
||||
if account.CaptchaToken != "" {
|
||||
client.UpdateCaptchaToken(strings.TrimSpace(account.CaptchaToken))
|
||||
account.CaptchaToken = ""
|
||||
}
|
||||
|
||||
if client.token == "" {
|
||||
return client.Login(account)
|
||||
}
|
||||
|
||||
account.Status = "work"
|
||||
model.SaveAccount(account)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) File(path string, account *model.Account) (*model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
if path == "/" {
|
||||
return &model.File{
|
||||
Id: account.RootFolder,
|
||||
Name: account.Name,
|
||||
Size: 0,
|
||||
Type: conf.FOLDER,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: account.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
dir, name := filepath.Split(path)
|
||||
files, err := driver.Files(dir, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range files {
|
||||
if file.Name == name {
|
||||
return &file, nil
|
||||
}
|
||||
}
|
||||
return nil, base.ErrPathNotFound
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Files(path string, account *model.Account) ([]model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
cache, err := base.GetCache(path, account)
|
||||
if err == nil {
|
||||
files, _ := cache.([]model.File)
|
||||
return files, nil
|
||||
}
|
||||
|
||||
parentFile, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
time.Sleep(time.Millisecond * 300)
|
||||
files := make([]model.File, 0)
|
||||
var pageToken string
|
||||
for {
|
||||
var fileList FileList
|
||||
_, err = GetClient(account).Request("GET", FILE_API_URL, func(r *resty.Request) {
|
||||
r.SetQueryParams(map[string]string{
|
||||
"parent_id": parentFile.Id,
|
||||
"page_token": pageToken,
|
||||
"with_audit": "true",
|
||||
"limit": "100",
|
||||
"filters": `{"phase": {"eq": "PHASE_TYPE_COMPLETE"}, "trashed":{"eq":false}}`,
|
||||
})
|
||||
r.SetResult(&fileList)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, file := range fileList.Files {
|
||||
if file.Kind == FOLDER || (file.Kind == FILE && file.Audit.Status == "STATUS_OK") {
|
||||
files = append(files, *driver.formatFile(&file))
|
||||
}
|
||||
}
|
||||
if fileList.NextPageToken == "" {
|
||||
break
|
||||
}
|
||||
pageToken = fileList.NextPageToken
|
||||
}
|
||||
if len(files) > 0 {
|
||||
_ = base.SetCache(path, files, account)
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) formatFile(file *Files) *model.File {
|
||||
size, _ := strconv.ParseInt(file.Size, 10, 64)
|
||||
tp := conf.FOLDER
|
||||
if file.Kind == FILE {
|
||||
tp = utils.GetFileType(file.FileExtension)
|
||||
}
|
||||
return &model.File{
|
||||
Id: file.ID,
|
||||
Name: file.Name,
|
||||
Size: size,
|
||||
Type: tp,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: file.CreatedTime,
|
||||
Thumbnail: file.ThumbnailLink,
|
||||
}
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Link(args base.Args, account *model.Account) (*base.Link, error) {
|
||||
file, err := driver.File(utils.ParsePath(args.Path), account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if file.Type == conf.FOLDER {
|
||||
return nil, base.ErrNotFile
|
||||
}
|
||||
var lFile Files
|
||||
clinet := GetClient(account)
|
||||
_, err = clinet.Request("GET", FILE_API_URL+"/{fileID}", func(r *resty.Request) {
|
||||
r.SetPathParam("fileID", file.Id)
|
||||
r.SetQueryParam("with_audit", "true")
|
||||
r.SetResult(&lFile)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &base.Link{
|
||||
Headers: []base.Header{
|
||||
{Name: "User-Agent", Value: clinet.userAgent},
|
||||
},
|
||||
Url: lFile.WebContentLink,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Path(path string, account *model.Account) (*model.File, []model.File, error) {
|
||||
path = utils.ParsePath(path)
|
||||
file, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !file.IsDir() {
|
||||
return file, nil, nil
|
||||
}
|
||||
files, err := driver.Files(path, account)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return nil, files, nil
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Preview(path string, account *model.Account) (interface{}, error) {
|
||||
return nil, base.ErrNotSupport
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Rename(src string, dst string, account *model.Account) error {
|
||||
srcFile, err := driver.File(src, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = GetClient(account).Request("PATCH", FILE_API_URL+"/{fileID}", func(r *resty.Request) {
|
||||
r.SetPathParam("fileID", srcFile.Id)
|
||||
r.SetBody(&base.Json{"name": filepath.Base(dst)})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) MakeDir(path string, account *model.Account) error {
|
||||
dir, name := filepath.Split(path)
|
||||
parentFile, err := driver.File(dir, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !parentFile.IsDir() {
|
||||
return base.ErrNotFolder
|
||||
}
|
||||
_, err = GetClient(account).Request("POST", FILE_API_URL, func(r *resty.Request) {
|
||||
r.SetBody(&base.Json{
|
||||
"kind": FOLDER,
|
||||
"name": name,
|
||||
"parent_id": parentFile.Id,
|
||||
})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Move(src string, dst string, account *model.Account) error {
|
||||
srcFile, err := driver.File(src, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dstDirFile, err := driver.File(filepath.Dir(dst), account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
_, err = GetClient(account).Request("POST", FILE_API_URL+":batchMove", func(r *resty.Request) {
|
||||
r.SetBody(&base.Json{
|
||||
"to": base.Json{"parent_id": dstDirFile.Id},
|
||||
"ids": []string{srcFile.Id},
|
||||
})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Copy(src string, dst string, account *model.Account) error {
|
||||
srcFile, err := driver.File(src, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
dstDirFile, err := driver.File(filepath.Dir(dst), account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = GetClient(account).Request("POST", FILE_API_URL+":batchCopy", func(r *resty.Request) {
|
||||
r.SetBody(&base.Json{
|
||||
"to": base.Json{"parent_id": dstDirFile.Id},
|
||||
"ids": []string{srcFile.Id},
|
||||
})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Delete(path string, account *model.Account) error {
|
||||
srcFile, err := driver.File(path, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = GetClient(account).Request("PATCH", FILE_API_URL+"/{fileID}/trash", func(r *resty.Request) {
|
||||
r.SetPathParam("fileID", srcFile.Id)
|
||||
r.SetBody(&base.Json{})
|
||||
}, account)
|
||||
return err
|
||||
}
|
||||
|
||||
func (driver XunLeiCloud) Upload(file *model.FileStream, account *model.Account) error {
|
||||
if file == nil {
|
||||
return base.ErrEmptyFile
|
||||
}
|
||||
|
||||
parentFile, err := driver.File(file.ParentPath, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
/*
|
||||
tempFile, err := ioutil.TempFile(conf.Conf.TempDir, "file-*")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = tempFile.Close()
|
||||
_ = os.Remove(tempFile.Name())
|
||||
}()
|
||||
|
||||
gcid, err := getGcid(io.TeeReader(file, tempFile), int64(file.Size))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if _, err = tempFile.Seek(0, io.SeekStart); err != nil {
|
||||
return err
|
||||
}
|
||||
*/
|
||||
|
||||
var resp UploadTaskResponse
|
||||
_, err = GetClient(account).Request("POST", FILE_API_URL, func(r *resty.Request) {
|
||||
r.SetBody(&base.Json{
|
||||
"kind": FILE,
|
||||
"parent_id": parentFile.Id,
|
||||
"name": file.Name,
|
||||
"size": file.Size,
|
||||
"hash": "1CF254FBC456E1B012CD45C546636AA62CF8350E",
|
||||
"upload_type": UPLOAD_TYPE_RESUMABLE,
|
||||
})
|
||||
r.SetResult(&resp)
|
||||
}, account)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
param := resp.Resumable.Params
|
||||
if resp.UploadType == UPLOAD_TYPE_RESUMABLE {
|
||||
param.Endpoint = strings.TrimLeft(param.Endpoint, param.Bucket+".")
|
||||
s, err := session.NewSession(&aws.Config{
|
||||
Credentials: credentials.NewStaticCredentials(param.AccessKeyID, param.AccessKeySecret, param.SecurityToken),
|
||||
Region: aws.String("xunlei"),
|
||||
Endpoint: aws.String(param.Endpoint),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = s3manager.NewUploader(s).Upload(&s3manager.UploadInput{
|
||||
Bucket: aws.String(param.Bucket),
|
||||
Key: aws.String(param.Key),
|
||||
Expires: aws.Time(param.Expiration),
|
||||
Body: file,
|
||||
})
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
var _ base.Driver = (*XunLeiCloud)(nil)
|
179
drivers/xunlei/types.go
Normal file
179
drivers/xunlei/types.go
Normal file
@ -0,0 +1,179 @@
|
||||
package xunlei
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Erron struct {
|
||||
ErrorCode int64 `json:"error_code"`
|
||||
ErrorMsg string `json:"error"`
|
||||
ErrorDescription string `json:"error_description"`
|
||||
// ErrorDetails interface{} `json:"error_details"`
|
||||
}
|
||||
|
||||
func (e *Erron) HasError() bool {
|
||||
return e.ErrorCode != 0 || e.ErrorMsg != "" || e.ErrorDescription != ""
|
||||
}
|
||||
|
||||
func (e *Erron) Error() string {
|
||||
return fmt.Sprintf("ErrorCode: %d ,Error: %s ,ErrorDescription: %s ", e.ErrorCode, e.ErrorMsg, e.ErrorDescription)
|
||||
}
|
||||
|
||||
/*
|
||||
* 验证码Token
|
||||
**/
|
||||
type CaptchaTokenRequest struct {
|
||||
Action string `json:"action"`
|
||||
CaptchaToken string `json:"captcha_token"`
|
||||
ClientID string `json:"client_id"`
|
||||
DeviceID string `json:"device_id"`
|
||||
Meta map[string]string `json:"meta"`
|
||||
RedirectUri string `json:"redirect_uri"`
|
||||
}
|
||||
|
||||
type CaptchaTokenResponse struct {
|
||||
CaptchaToken string `json:"captcha_token"`
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
Url string `json:"url"`
|
||||
}
|
||||
|
||||
/*
|
||||
* 登录
|
||||
**/
|
||||
type TokenResponse struct {
|
||||
TokenType string `json:"token_type"`
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
ExpiresIn int64 `json:"expires_in"`
|
||||
|
||||
Sub string `json:"sub"`
|
||||
UserID string `json:"user_id"`
|
||||
}
|
||||
|
||||
func (t *TokenResponse) Token() string {
|
||||
return fmt.Sprint(t.TokenType, " ", t.AccessToken)
|
||||
}
|
||||
|
||||
type SignInRequest struct {
|
||||
CaptchaToken string `json:"captcha_token"`
|
||||
|
||||
ClientID string `json:"client_id"`
|
||||
ClientSecret string `json:"client_secret"`
|
||||
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
/*
|
||||
* 文件
|
||||
**/
|
||||
type FileList struct {
|
||||
Kind string `json:"kind"`
|
||||
NextPageToken string `json:"next_page_token"`
|
||||
Files []Files `json:"files"`
|
||||
Version string `json:"version"`
|
||||
VersionOutdated bool `json:"version_outdated"`
|
||||
}
|
||||
|
||||
type Files struct {
|
||||
Kind string `json:"kind"`
|
||||
ID string `json:"id"`
|
||||
ParentID string `json:"parent_id"`
|
||||
Name string `json:"name"`
|
||||
UserID string `json:"user_id"`
|
||||
Size string `json:"size"`
|
||||
Revision string `json:"revision"`
|
||||
FileExtension string `json:"file_extension"`
|
||||
MimeType string `json:"mime_type"`
|
||||
Starred bool `json:"starred"`
|
||||
WebContentLink string `json:"web_content_link"`
|
||||
CreatedTime *time.Time `json:"created_time"`
|
||||
ModifiedTime *time.Time `json:"modified_time"`
|
||||
IconLink string `json:"icon_link"`
|
||||
ThumbnailLink string `json:"thumbnail_link"`
|
||||
Md5Checksum string `json:"md5_checksum"`
|
||||
Hash string `json:"hash"`
|
||||
//Links struct{} `json:"links"`
|
||||
Phase string `json:"phase"`
|
||||
Audit struct {
|
||||
Status string `json:"status"`
|
||||
Message string `json:"message"`
|
||||
Title string `json:"title"`
|
||||
} `json:"audit"`
|
||||
/* Medias []struct {
|
||||
Category string `json:"category"`
|
||||
IconLink string `json:"icon_link"`
|
||||
IsDefault bool `json:"is_default"`
|
||||
IsOrigin bool `json:"is_origin"`
|
||||
IsVisible bool `json:"is_visible"`
|
||||
//Link interface{} `json:"link"`
|
||||
MediaID string `json:"media_id"`
|
||||
MediaName string `json:"media_name"`
|
||||
NeedMoreQuota bool `json:"need_more_quota"`
|
||||
Priority int `json:"priority"`
|
||||
RedirectLink string `json:"redirect_link"`
|
||||
ResolutionName string `json:"resolution_name"`
|
||||
Video struct {
|
||||
AudioCodec string `json:"audio_codec"`
|
||||
BitRate int `json:"bit_rate"`
|
||||
Duration int `json:"duration"`
|
||||
FrameRate int `json:"frame_rate"`
|
||||
Height int `json:"height"`
|
||||
VideoCodec string `json:"video_codec"`
|
||||
VideoType string `json:"video_type"`
|
||||
Width int `json:"width"`
|
||||
} `json:"video"`
|
||||
VipTypes []string `json:"vip_types"`
|
||||
} `json:"medias"` */
|
||||
Trashed bool `json:"trashed"`
|
||||
DeleteTime string `json:"delete_time"`
|
||||
OriginalURL string `json:"original_url"`
|
||||
//Params struct{} `json:"params"`
|
||||
OriginalFileIndex int `json:"original_file_index"`
|
||||
Space string `json:"space"`
|
||||
//Apps []interface{} `json:"apps"`
|
||||
Writable bool `json:"writable"`
|
||||
FolderType string `json:"folder_type"`
|
||||
//Collection interface{} `json:"collection"`
|
||||
}
|
||||
|
||||
/*
|
||||
* 上传
|
||||
**/
|
||||
type UploadTaskResponse struct {
|
||||
UploadType string `json:"upload_type"`
|
||||
|
||||
/*//UPLOAD_TYPE_FORM
|
||||
Form struct {
|
||||
//Headers struct{} `json:"headers"`
|
||||
Kind string `json:"kind"`
|
||||
Method string `json:"method"`
|
||||
MultiParts struct {
|
||||
OSSAccessKeyID string `json:"OSSAccessKeyId"`
|
||||
Signature string `json:"Signature"`
|
||||
Callback string `json:"callback"`
|
||||
Key string `json:"key"`
|
||||
Policy string `json:"policy"`
|
||||
XUserData string `json:"x:user_data"`
|
||||
} `json:"multi_parts"`
|
||||
URL string `json:"url"`
|
||||
} `json:"form"`*/
|
||||
|
||||
//UPLOAD_TYPE_RESUMABLE
|
||||
Resumable struct {
|
||||
Kind string `json:"kind"`
|
||||
Params struct {
|
||||
AccessKeyID string `json:"access_key_id"`
|
||||
AccessKeySecret string `json:"access_key_secret"`
|
||||
Bucket string `json:"bucket"`
|
||||
Endpoint string `json:"endpoint"`
|
||||
Expiration time.Time `json:"expiration"`
|
||||
Key string `json:"key"`
|
||||
SecurityToken string `json:"security_token"`
|
||||
} `json:"params"`
|
||||
Provider string `json:"provider"`
|
||||
} `json:"resumable"`
|
||||
|
||||
File Files `json:"file"`
|
||||
}
|
63
drivers/xunlei/util.go
Normal file
63
drivers/xunlei/util.go
Normal file
@ -0,0 +1,63 @@
|
||||
package xunlei
|
||||
|
||||
import (
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"io"
|
||||
"net/url"
|
||||
)
|
||||
|
||||
const (
|
||||
API_URL = "https://api-pan.xunlei.com/drive/v1"
|
||||
FILE_API_URL = API_URL + "/files"
|
||||
XLUSER_API_URL = "https://xluser-ssl.xunlei.com/v1"
|
||||
)
|
||||
|
||||
const (
|
||||
FOLDER = "drive#folder"
|
||||
FILE = "drive#file"
|
||||
RESUMABLE = "drive#resumable"
|
||||
)
|
||||
|
||||
const (
|
||||
UPLOAD_TYPE_UNKNOWN = "UPLOAD_TYPE_UNKNOWN"
|
||||
//UPLOAD_TYPE_FORM = "UPLOAD_TYPE_FORM"
|
||||
UPLOAD_TYPE_RESUMABLE = "UPLOAD_TYPE_RESUMABLE"
|
||||
UPLOAD_TYPE_URL = "UPLOAD_TYPE_URL"
|
||||
)
|
||||
|
||||
func getAction(method string, u string) string {
|
||||
c, _ := url.Parse(u)
|
||||
return method + ":" + c.Path
|
||||
}
|
||||
|
||||
// 计算文件Gcid
|
||||
func getGcid(r io.Reader, size int64) (string, error) {
|
||||
calcBlockSize := func(j int64) int64 {
|
||||
if j >= 0 && j <= 0x8000000 {
|
||||
return 0x40000
|
||||
}
|
||||
if j <= 0x8000000 || j > 0x10000000 {
|
||||
if j <= 0x10000000 || j > 0x20000000 {
|
||||
return 0x200000
|
||||
}
|
||||
return 0x100000
|
||||
}
|
||||
return 0x80000
|
||||
}
|
||||
|
||||
hash1 := sha1.New()
|
||||
hash2 := sha1.New()
|
||||
readSize := calcBlockSize(size)
|
||||
for {
|
||||
hash2.Reset()
|
||||
if n, err := io.CopyN(hash2, r, readSize); err != nil && n == 0 {
|
||||
if err != io.EOF {
|
||||
return "", err
|
||||
}
|
||||
break
|
||||
}
|
||||
hash1.Write(hash2.Sum(nil))
|
||||
}
|
||||
return hex.EncodeToString(hash1.Sum(nil)), nil
|
||||
}
|
282
drivers/xunlei/xunlei.go
Normal file
282
drivers/xunlei/xunlei.go
Normal file
@ -0,0 +1,282 @@
|
||||
package xunlei
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Xhofe/alist/drivers/base"
|
||||
"github.com/Xhofe/alist/model"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
"github.com/go-resty/resty/v2"
|
||||
log "github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
// 缓存登录状态
|
||||
var userClients sync.Map
|
||||
|
||||
func GetClient(account *model.Account) *Client {
|
||||
if v, ok := userClients.Load(account.Username); ok {
|
||||
return v.(*Client)
|
||||
}
|
||||
|
||||
client := &Client{
|
||||
Client: base.RestyClient,
|
||||
|
||||
clientID: account.ClientId,
|
||||
clientSecret: account.ClientSecret,
|
||||
clientVersion: account.ClientVersion,
|
||||
packageName: account.PackageName,
|
||||
algorithms: strings.Split(account.Algorithms, ","),
|
||||
userAgent: account.UserAgent,
|
||||
deviceID: account.DeviceId,
|
||||
}
|
||||
userClients.Store(account.Username, client)
|
||||
return client
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
*resty.Client
|
||||
sync.Mutex
|
||||
|
||||
clientID string
|
||||
clientSecret string
|
||||
clientVersion string
|
||||
packageName string
|
||||
algorithms []string
|
||||
userAgent string
|
||||
deviceID string
|
||||
|
||||
captchaToken string
|
||||
|
||||
token string
|
||||
refreshToken string
|
||||
userID string
|
||||
}
|
||||
|
||||
// 请求验证码token
|
||||
func (c *Client) requestCaptchaToken(action string, meta map[string]string) error {
|
||||
param := CaptchaTokenRequest{
|
||||
Action: action,
|
||||
CaptchaToken: c.captchaToken,
|
||||
ClientID: c.clientID,
|
||||
DeviceID: c.deviceID,
|
||||
Meta: meta,
|
||||
RedirectUri: "xlaccsdk01://xunlei.com/callback?state=harbor",
|
||||
}
|
||||
|
||||
var e Erron
|
||||
var resp CaptchaTokenResponse
|
||||
_, err := c.Client.R().
|
||||
SetBody(¶m).
|
||||
SetError(&e).
|
||||
SetResult(&resp).
|
||||
SetHeader("X-Device-Id", c.deviceID).
|
||||
SetQueryParam("client_id", c.clientID).
|
||||
Post(XLUSER_API_URL + "/shield/captcha/init")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if e.HasError() {
|
||||
return &e
|
||||
}
|
||||
|
||||
if resp.Url != "" {
|
||||
return fmt.Errorf("need verify:%s", resp.Url)
|
||||
}
|
||||
|
||||
if resp.CaptchaToken == "" {
|
||||
return fmt.Errorf("empty captchaToken")
|
||||
}
|
||||
c.captchaToken = resp.CaptchaToken
|
||||
return nil
|
||||
}
|
||||
|
||||
// 验证码签名
|
||||
func (c *Client) captchaSign(time string) string {
|
||||
str := fmt.Sprint(c.clientID, c.clientVersion, c.packageName, c.deviceID, time)
|
||||
for _, algorithm := range c.algorithms {
|
||||
str = utils.GetMD5Encode(str + algorithm)
|
||||
}
|
||||
return "1." + str
|
||||
}
|
||||
|
||||
// 登录
|
||||
func (c *Client) Login(account *model.Account) (err error) {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
defer func() {
|
||||
if err != nil {
|
||||
account.Status = err.Error()
|
||||
} else {
|
||||
account.Status = "work"
|
||||
}
|
||||
model.SaveAccount(account)
|
||||
}()
|
||||
|
||||
meta := make(map[string]string)
|
||||
if strings.Contains(account.Username, "@") {
|
||||
meta["email"] = account.Username
|
||||
} else if len(account.Username) >= 11 {
|
||||
if !strings.Contains(account.Username, "+") {
|
||||
account.Username = "+86 " + account.Username
|
||||
}
|
||||
meta["phone_number"] = account.Username
|
||||
} else {
|
||||
meta["username"] = account.Username
|
||||
}
|
||||
|
||||
url := XLUSER_API_URL + "/auth/signin"
|
||||
err = c.requestCaptchaToken(getAction(http.MethodPost, url), meta)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
var e Erron
|
||||
var resp TokenResponse
|
||||
_, err = c.Client.R().
|
||||
SetResult(&resp).
|
||||
SetError(&e).
|
||||
SetBody(&SignInRequest{
|
||||
CaptchaToken: c.captchaToken,
|
||||
ClientID: c.clientID,
|
||||
ClientSecret: c.clientSecret,
|
||||
Username: account.Username,
|
||||
Password: account.Password,
|
||||
}).
|
||||
SetHeader("X-Device-Id", c.deviceID).
|
||||
SetQueryParam("client_id", c.clientID).
|
||||
Post(url)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if e.HasError() {
|
||||
return &e
|
||||
}
|
||||
|
||||
if resp.RefreshToken == "" {
|
||||
return base.ErrEmptyToken
|
||||
}
|
||||
|
||||
c.token = resp.Token()
|
||||
c.refreshToken = resp.RefreshToken
|
||||
c.userID = resp.UserID
|
||||
return nil
|
||||
}
|
||||
|
||||
// 刷新验证码token
|
||||
func (c *Client) RefreshCaptchaToken(action string) error {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
timestamp := fmt.Sprint(time.Now().UnixMilli())
|
||||
param := map[string]string{
|
||||
"client_version": c.clientVersion,
|
||||
"package_name": c.packageName,
|
||||
"user_id": c.userID,
|
||||
"captcha_sign": c.captchaSign(timestamp),
|
||||
"timestamp": timestamp,
|
||||
}
|
||||
return c.requestCaptchaToken(action, param)
|
||||
}
|
||||
|
||||
// 刷新token
|
||||
func (c *Client) RefreshToken() error {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
var e Erron
|
||||
var resp TokenResponse
|
||||
_, err := c.Client.R().
|
||||
SetError(&e).
|
||||
SetResult(&resp).
|
||||
SetBody(&base.Json{
|
||||
"grant_type": "refresh_token",
|
||||
"refresh_token": c.refreshToken,
|
||||
"client_id": c.clientID,
|
||||
"client_secret": c.clientSecret,
|
||||
}).
|
||||
SetHeader("X-Device-Id", c.deviceID).
|
||||
SetQueryParam("client_id", c.clientID).
|
||||
Post(XLUSER_API_URL + "/auth/token")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if e.HasError() {
|
||||
return &e
|
||||
}
|
||||
|
||||
if resp.RefreshToken == "" {
|
||||
return base.ErrEmptyToken
|
||||
}
|
||||
|
||||
c.token = resp.TokenType + " " + resp.AccessToken
|
||||
c.refreshToken = resp.RefreshToken
|
||||
c.userID = resp.UserID
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) Request(method string, url string, callback func(*resty.Request), account *model.Account) (*resty.Response, error) {
|
||||
c.Lock()
|
||||
req := c.Client.R().
|
||||
SetHeaders(map[string]string{
|
||||
"X-Device-Id": c.deviceID,
|
||||
"Authorization": c.token,
|
||||
"X-Captcha-Token": c.captchaToken,
|
||||
"User-Agent": c.userAgent,
|
||||
"client_id": c.clientID,
|
||||
}).
|
||||
SetQueryParam("client_id", c.clientID)
|
||||
if callback != nil {
|
||||
callback(req)
|
||||
}
|
||||
c.Unlock()
|
||||
|
||||
res, err := req.Execute(method, url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
log.Debug(res.String())
|
||||
|
||||
var e Erron
|
||||
if err = utils.Json.Unmarshal(res.Body(), &e); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 处理错误
|
||||
switch e.ErrorCode {
|
||||
case 0:
|
||||
return res, nil
|
||||
case 4122, 4121, 10: // token过期
|
||||
if err = c.RefreshToken(); err == nil {
|
||||
break
|
||||
}
|
||||
fallthrough
|
||||
case 16: // 登录失效
|
||||
if err = c.Login(account); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case 9: // 验证码token过期
|
||||
if err = c.RefreshCaptchaToken(getAction(method, url)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
return nil, &e
|
||||
}
|
||||
return c.Request(method, url, callback, account)
|
||||
}
|
||||
|
||||
func (c *Client) UpdateCaptchaToken(captchaToken string) bool {
|
||||
c.Lock()
|
||||
defer c.Unlock()
|
||||
|
||||
if captchaToken != "" {
|
||||
c.captchaToken = captchaToken
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
@ -213,7 +213,8 @@ func (driver Yandex) Upload(file *model.FileStream, account *model.Account) erro
|
||||
}
|
||||
req.Header.Set("Content-Length", strconv.FormatUint(file.Size, 10))
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
_, err = base.HttpClient.Do(req)
|
||||
res, err := base.HttpClient.Do(req)
|
||||
res.Body.Close()
|
||||
//res, err := base.RestyClient.R().
|
||||
// SetHeader("Content-Length", strconv.FormatUint(file.Size, 10)).
|
||||
// SetBody(file).Put(resp.Href)
|
||||
|
@ -26,7 +26,7 @@ type File struct {
|
||||
//} `json:"exif"`
|
||||
//Created time.Time `json:"created"`
|
||||
//ResourceId string `json:"resource_id"`
|
||||
Modified time.Time `json:"modified"`
|
||||
Modified *time.Time `json:"modified"`
|
||||
//MimeType string `json:"mime_type"`
|
||||
File string `json:"file"`
|
||||
//MediaType string `json:"media_type"`
|
||||
|
@ -131,7 +131,7 @@ func (driver Yandex) GetFiles(rawPath string, account *model.Account) ([]model.F
|
||||
Name: file.Name,
|
||||
Size: file.Size,
|
||||
Driver: driver.Config().Name,
|
||||
UpdatedAt: &file.Modified,
|
||||
UpdatedAt: file.Modified,
|
||||
Thumbnail: file.Preview,
|
||||
Url: file.File,
|
||||
}
|
||||
|
37
go.mod
37
go.mod
@ -1,24 +1,34 @@
|
||||
module github.com/Xhofe/alist
|
||||
|
||||
go 1.17
|
||||
go 1.18
|
||||
|
||||
require (
|
||||
github.com/aws/aws-sdk-go v1.27.0
|
||||
github.com/caarlos0/env/v6 v6.9.1
|
||||
github.com/eko/gocache/v2 v2.1.0
|
||||
github.com/gin-contrib/cors v1.3.1
|
||||
github.com/gin-gonic/gin v1.7.4
|
||||
github.com/go-resty/resty/v2 v2.6.0
|
||||
github.com/google/uuid v1.3.0
|
||||
github.com/jlaffaye/ftp v0.0.0-20211117213618-11820403398b
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/patrickmn/go-cache v2.1.0+incompatible
|
||||
github.com/pkg/sftp v1.13.4
|
||||
github.com/robfig/cron/v3 v3.0.0
|
||||
github.com/sirupsen/logrus v1.8.1
|
||||
github.com/studio-b12/gowebdav v0.0.0-20211109083228-3f8721cd4b6f
|
||||
github.com/upyun/go-sdk/v3 v3.0.2
|
||||
golang.org/x/text v0.3.7
|
||||
gorm.io/driver/mysql v1.2.3
|
||||
gorm.io/driver/postgres v1.2.3
|
||||
gorm.io/driver/sqlite v1.2.6
|
||||
gorm.io/gorm v1.22.5
|
||||
gorm.io/driver/mysql v1.3.2
|
||||
gorm.io/driver/postgres v1.3.1
|
||||
gorm.io/driver/sqlite v1.3.1
|
||||
gorm.io/gorm v1.23.1
|
||||
)
|
||||
|
||||
require github.com/kr/fs v0.1.0 // indirect
|
||||
|
||||
require (
|
||||
github.com/fatih/color v1.13.0
|
||||
github.com/mattn/go-colorable v0.1.9 // indirect
|
||||
)
|
||||
|
||||
require (
|
||||
@ -35,21 +45,20 @@ require (
|
||||
github.com/go-redis/redis/v8 v8.9.0 // indirect
|
||||
github.com/go-sql-driver/mysql v1.6.0 // indirect
|
||||
github.com/golang/protobuf v1.5.2 // indirect
|
||||
github.com/google/uuid v1.3.0 // indirect
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 // indirect
|
||||
github.com/jackc/pgconn v1.10.1 // indirect
|
||||
github.com/jackc/pgconn v1.11.0 // indirect
|
||||
github.com/jackc/pgio v1.0.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgproto3/v2 v2.2.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20200714003250-2b9c44734f2b // indirect
|
||||
github.com/jackc/pgtype v1.9.1 // indirect
|
||||
github.com/jackc/pgx/v4 v4.14.1 // indirect
|
||||
github.com/jackc/pgtype v1.10.0 // indirect
|
||||
github.com/jackc/pgx/v4 v4.15.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.4 // indirect
|
||||
github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af // indirect
|
||||
github.com/leodido/go-urn v1.2.1 // indirect
|
||||
github.com/mattn/go-isatty v0.0.14 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.10 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.11 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
@ -63,9 +72,9 @@ require (
|
||||
go.opentelemetry.io/otel v0.20.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v0.20.0 // indirect
|
||||
go.opentelemetry.io/otel/trace v0.20.0 // indirect
|
||||
golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce // indirect
|
||||
golang.org/x/net v0.0.0-20211209124913-491a49abca63 // indirect
|
||||
golang.org/x/sys v0.0.0-20211023085530-d6a326fbbf70 // indirect
|
||||
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29
|
||||
golang.org/x/net v0.0.0-20211209124913-491a49abca63
|
||||
golang.org/x/sys v0.0.0-20220330033206-e17cdc41300f // indirect
|
||||
google.golang.org/protobuf v1.27.1 // indirect
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.0.0 // indirect
|
||||
gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect
|
||||
|
90
go.sum
90
go.sum
@ -39,8 +39,9 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r
|
||||
github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b h1:L/QXpzIa3pOvUGt1D1lA5KjYhPBAN/3iWdP7xeFS9F0=
|
||||
github.com/bradfitz/gomemcache v0.0.0-20190913173617-a41fca850d0b/go.mod h1:H0wQNHz2YrLsuXOZozoeDmnHXkNCRmMW0gwFWDfEZDA=
|
||||
github.com/caarlos0/env/v6 v6.9.1 h1:zOkkjM0F6ltnQ5eBX6IPI41UP/KDGEK7rRPwGCNos8k=
|
||||
github.com/caarlos0/env/v6 v6.9.1/go.mod h1:hvp/ryKXKipEkcuYjs9mI4bBCg+UI0Yhgm5Zu0ddvwc=
|
||||
github.com/casbin/casbin/v2 v2.1.2/go.mod h1:YcPU1XXisHhLzuxH9coDNf2FbKpjGlbCg3n9yuLkIJQ=
|
||||
github.com/cenkalti/backoff v2.2.1+incompatible h1:tNowT99t7UNflLxfYYSlKYsBpXdEet03Pg2g16Swow4=
|
||||
github.com/cenkalti/backoff v2.2.1+incompatible/go.mod h1:90ReRw6GdpyfrHakVjL/QHaoyV4aDUVVkXQJJJ3NXXM=
|
||||
github.com/cenkalti/backoff/v4 v4.1.0 h1:c8LkOFQTzuO0WBM/ae5HdGQuZPfPxp7lqBRwQRm4fSc=
|
||||
github.com/cenkalti/backoff/v4 v4.1.0/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw=
|
||||
@ -90,6 +91,8 @@ github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.m
|
||||
github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c=
|
||||
github.com/evanphx/json-patch v4.2.0+incompatible/go.mod h1:50XU6AFN0ol/bzJsmQLiYLvXMP4fmwYFNcr97nuDLSk=
|
||||
github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4=
|
||||
github.com/fatih/color v1.13.0 h1:8LOYc1KYPPmyKMuN8QV2DNRWNbLo6LZ0iLs8+mlH53w=
|
||||
github.com/fatih/color v1.13.0/go.mod h1:kLAiJbzzSOZDVNGyDpeOxJ47H46qBXwg5ILebYFFOfk=
|
||||
github.com/fortytw2/leaktest v1.3.0 h1:u8491cBMTQ8ft8aeV+adlcytMZylmA5nnwwkRZjI8vw=
|
||||
github.com/fortytw2/leaktest v1.3.0/go.mod h1:jDsjWgpAGjm2CA7WthBh/CdZYEPF31XHquHwclZch5g=
|
||||
github.com/franela/goblin v0.0.0-20200105215937-c9ffbefa60db/go.mod h1:7dvUGVsVBjqR7JHJk0brhHOZYGmfBYOrK0ZhYMEtBr4=
|
||||
@ -218,7 +221,6 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO
|
||||
github.com/hudl/fargo v1.3.0/go.mod h1:y3CKSmjA+wD2gak7sUSXTAoopbhU08POFhmITJgmKTg=
|
||||
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
|
||||
github.com/influxdata/influxdb1-client v0.0.0-20191209144304-8bf82d3c094d/go.mod h1:qj24IKcXYK6Iy9ceXlo3Tc+vtHo9lIhSX5JddghvEPo=
|
||||
github.com/jackc/chunkreader v1.0.0 h1:4s39bBR8ByfqH+DKm8rQA3E1LHZWB9XWcrz8fqaZbe0=
|
||||
github.com/jackc/chunkreader v1.0.0/go.mod h1:RT6O25fNZIuasFJRyZ4R/Y2BbhasbmZXF9QQ7T3kePo=
|
||||
github.com/jackc/chunkreader/v2 v2.0.0/go.mod h1:odVSm741yZoC3dpHEUXIqA9tQRhFrgOHwnPIn9lDKlk=
|
||||
github.com/jackc/chunkreader/v2 v2.0.1 h1:i+RDz65UE+mmpjTfyz0MoVTnzeYxroil2G82ki7MGG8=
|
||||
@ -229,10 +231,9 @@ github.com/jackc/pgconn v0.0.0-20190831204454-2fabfa3c18b7/go.mod h1:ZJKsE/KZfsU
|
||||
github.com/jackc/pgconn v1.8.0/go.mod h1:1C2Pb36bGIP9QHGBYCjnyhqu7Rv3sGshaQUvmfGIB/o=
|
||||
github.com/jackc/pgconn v1.9.0/go.mod h1:YctiPyvzfU11JFxoXokUOOKQXQmDMoJL9vJzHH8/2JY=
|
||||
github.com/jackc/pgconn v1.9.1-0.20210724152538-d89c8390a530/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI=
|
||||
github.com/jackc/pgconn v1.10.0 h1:4EYhlDVEMsJ30nNj0mmgwIUXoq7e9sMJrVC2ED6QlCU=
|
||||
github.com/jackc/pgconn v1.10.0/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI=
|
||||
github.com/jackc/pgconn v1.10.1 h1:DzdIHIjG1AxGwoEEqS+mGsURyjt4enSmqzACXvVzOT8=
|
||||
github.com/jackc/pgconn v1.10.1/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI=
|
||||
github.com/jackc/pgconn v1.11.0 h1:HiHArx4yFbwl91X3qqIHtUFoiIfLNJXCQRsnzkiwwaQ=
|
||||
github.com/jackc/pgconn v1.11.0/go.mod h1:4z2w8XhRbP1hYxkpTuBjTS3ne3J48K83+u0zoyvg2pI=
|
||||
github.com/jackc/pgio v1.0.0 h1:g12B9UwVnzGhueNavwioyEEpAmqMe1E/BN9ES+8ovkE=
|
||||
github.com/jackc/pgio v1.0.0/go.mod h1:oP+2QK2wFfUWgr+gxjoBH9KGBb31Eio69xUb0w5bYf8=
|
||||
github.com/jackc/pgmock v0.0.0-20190831213851-13a1b77aafa2/go.mod h1:fGZlG77KXmcq05nJLRkk0+p82V8B8Dw8KN2/V9c/OAE=
|
||||
@ -241,14 +242,12 @@ github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65 h1:DadwsjnMwFjfWc9y5W
|
||||
github.com/jackc/pgmock v0.0.0-20210724152146-4ad1a8207f65/go.mod h1:5R2h2EEX+qri8jOWMbJCtaPWkrrNc7OHwsp2TCqp7ak=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgproto3 v1.1.0 h1:FYYE4yRw+AgI8wXIinMlNjBbp/UitDJwfj5LqqewP1A=
|
||||
github.com/jackc/pgproto3 v1.1.0/go.mod h1:eR5FA3leWg7p9aeAqi37XOTgTIbkABlvcPB3E5rlc78=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190420180111-c116219b62db/go.mod h1:bhq50y+xrl9n5mRYyCBFKkpRVTLYJVWeCc+mEAI3yXA=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-alpha1.0.20190609003834-432c2951c711/go.mod h1:uH0AWtUmuShn0bcesswc4aBTWGvw0cAxIJp+6OB//Wg=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-rc3/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM=
|
||||
github.com/jackc/pgproto3/v2 v2.0.0-rc3.0.20190831210041-4c03ce451f29/go.mod h1:ryONWYqW6dqSg1Lw6vXNMXoBJhpzvWKnT95C46ckYeM=
|
||||
github.com/jackc/pgproto3/v2 v2.0.6/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA=
|
||||
github.com/jackc/pgproto3/v2 v2.1.1 h1:7PQ/4gLoqnl87ZxL7xjO0DR5gYuviDCZxQJsUlFW1eI=
|
||||
github.com/jackc/pgproto3/v2 v2.1.1/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA=
|
||||
github.com/jackc/pgproto3/v2 v2.2.0 h1:r7JypeP2D3onoQTCxWdTpCtJ4D+qpKr0TxvoyMhZ5ns=
|
||||
github.com/jackc/pgproto3/v2 v2.2.0/go.mod h1:WfJCnwN3HIg9Ish/j3sgWXnAfK8A9Y0bwXYU5xKaEdA=
|
||||
@ -258,29 +257,23 @@ github.com/jackc/pgtype v0.0.0-20190421001408-4ed0de4755e0/go.mod h1:hdSHsc1V01C
|
||||
github.com/jackc/pgtype v0.0.0-20190824184912-ab885b375b90/go.mod h1:KcahbBH1nCMSo2DXpzsoWOAfFkdEtEJpPbVLq8eE+mc=
|
||||
github.com/jackc/pgtype v0.0.0-20190828014616-a8802b16cc59/go.mod h1:MWlu30kVJrUS8lot6TQqcg7mtthZ9T0EoIBFiJcmcyw=
|
||||
github.com/jackc/pgtype v1.8.1-0.20210724151600-32e20a603178/go.mod h1:C516IlIV9NKqfsMCXTdChteoXmwgUceqaLfjg2e3NlM=
|
||||
github.com/jackc/pgtype v1.8.1 h1:9k0IXtdJXHJbyAWQgbWr1lU+MEhPXZz6RIXxfR5oxXs=
|
||||
github.com/jackc/pgtype v1.8.1/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4=
|
||||
github.com/jackc/pgtype v1.9.0/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4=
|
||||
github.com/jackc/pgtype v1.9.1 h1:MJc2s0MFS8C3ok1wQTdQxWuXQcB6+HwAm5x1CzW7mf0=
|
||||
github.com/jackc/pgtype v1.9.1/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4=
|
||||
github.com/jackc/pgtype v1.10.0 h1:ILnBWrRMSXGczYvmkYD6PsYyVFUNLTnIUJHHDLmqk38=
|
||||
github.com/jackc/pgtype v1.10.0/go.mod h1:LUMuVrfsFfdKGLw+AFFVv6KtHOFMwRgDDzBt76IqCA4=
|
||||
github.com/jackc/pgx/v4 v4.0.0-20190420224344-cc3461e65d96/go.mod h1:mdxmSJJuR08CZQyj1PVQBHy9XOp5p8/SHH6a0psbY9Y=
|
||||
github.com/jackc/pgx/v4 v4.0.0-20190421002000-1b8f0016e912/go.mod h1:no/Y67Jkk/9WuGR0JG/JseM9irFbnEPbuWV2EELPNuM=
|
||||
github.com/jackc/pgx/v4 v4.0.0-pre1.0.20190824185557-6972a5742186/go.mod h1:X+GQnOEnf1dqHGpw7JmHqHc1NxDoalibchSk9/RWuDc=
|
||||
github.com/jackc/pgx/v4 v4.12.1-0.20210724153913-640aa07df17c/go.mod h1:1QD0+tgSXP7iUjYm9C1NxKhny7lq6ee99u/z+IHFcgs=
|
||||
github.com/jackc/pgx/v4 v4.13.0 h1:JCjhT5vmhMAf/YwBHLvrBn4OGdIQBiFG6ym8Zmdx570=
|
||||
github.com/jackc/pgx/v4 v4.13.0/go.mod h1:9P4X524sErlaxj0XSGZk7s+LD0eOyu1ZDUrrpznYDF0=
|
||||
github.com/jackc/pgx/v4 v4.14.0/go.mod h1:jT3ibf/A0ZVCp89rtCIN0zCJxcE74ypROmHEZYsG/j8=
|
||||
github.com/jackc/pgx/v4 v4.14.1 h1:71oo1KAGI6mXhLiTMn6iDFcp3e7+zon/capWjl2OEFU=
|
||||
github.com/jackc/pgx/v4 v4.14.1/go.mod h1:RgDuE4Z34o7XE92RpLsvFiOEfrAUT0Xt2KxvX73W06M=
|
||||
github.com/jackc/pgx/v4 v4.15.0 h1:B7dTkXsdILD3MF987WGGCcg+tvLW6bZJdEcqVFeU//w=
|
||||
github.com/jackc/pgx/v4 v4.15.0/go.mod h1:D/zyOyXiaM1TmVWnOM18p0xdDtdakRBa0RsVGI3U3bw=
|
||||
github.com/jackc/puddle v0.0.0-20190413234325-e4ced69a3a2b/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jackc/puddle v0.0.0-20190608224051-11cab39313c9/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jackc/puddle v1.1.3/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jackc/puddle v1.2.0/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jackc/puddle v1.2.1/go.mod h1:m4B5Dj62Y0fbyuIc15OsIqK0+JU8nkqQjsgx7dvjSWk=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.2 h1:eVKgfIdy9b6zbWBMgFpfDPoAMifwSZagU9HmEU6zgiI=
|
||||
github.com/jinzhu/now v1.1.2/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jinzhu/now v1.1.3/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jinzhu/now v1.1.4 h1:tHnRBy1i5F2Dh8BAFxqFzxKqqvezXrL2OW1TnX+Mlas=
|
||||
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/jlaffaye/ftp v0.0.0-20211117213618-11820403398b h1:Ur6QAxsHCK99Quj9PaWafoV4unb0DO/HWiKExD+TN5g=
|
||||
@ -307,6 +300,8 @@ github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+o
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
|
||||
github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8=
|
||||
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
|
||||
github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515/go.mod h1:+0opPa2QZZtGFBFZlji/RkVcI2GknAs/DXo4wKdlNEc=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
|
||||
@ -333,6 +328,8 @@ github.com/mailru/easyjson v0.0.0-20160728113105-d5b7844b561a/go.mod h1:C1wdFJiN
|
||||
github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
|
||||
github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
|
||||
github.com/mattn/go-colorable v0.1.6/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-colorable v0.1.9 h1:sqDoxXbdeALODt0DAeJCVp38ps9ZogZEAXjus69YV3U=
|
||||
github.com/mattn/go-colorable v0.1.9/go.mod h1:u6P/XSegPjTcexA+o6vUJrdnUu04hMope9wVRipJSqc=
|
||||
github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
|
||||
github.com/mattn/go-isatty v0.0.4/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
|
||||
github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
|
||||
@ -342,11 +339,9 @@ github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Ky
|
||||
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
|
||||
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
|
||||
github.com/mattn/go-runewidth v0.0.2/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
|
||||
github.com/mattn/go-sqlite3 v1.14.8/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
|
||||
github.com/mattn/go-sqlite3 v1.14.9 h1:10HX2Td0ocZpYEjhilsuo6WWtUqttj2Kb0KtD86/KYA=
|
||||
github.com/mattn/go-sqlite3 v1.14.9/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
|
||||
github.com/mattn/go-sqlite3 v1.14.10 h1:MLn+5bFRlWMGoSRmJour3CL1w/qL96mvipqpwQW/Sfk=
|
||||
github.com/mattn/go-sqlite3 v1.14.10/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
|
||||
github.com/mattn/go-sqlite3 v1.14.11 h1:gt+cp9c0XGqe9S/wAHTL3n/7MqY+siPWgWJgqdsFrzQ=
|
||||
github.com/mattn/go-sqlite3 v1.14.11/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1 h1:4hp9jkHxhMHkqkrB3Ix0jegS5sx/RkqARlsWZ6pIwiU=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
|
||||
@ -420,6 +415,8 @@ github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINE
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
|
||||
github.com/pkg/sftp v1.13.4 h1:Lb0RYJCmgUcBgZosfoi9Y9sbl6+LJgOIgk/2Y4YjMFg=
|
||||
github.com/pkg/sftp v1.13.4/go.mod h1:LzqnAvaD5TWeNBsZpfKxSYn1MbjWwOsCIAFFJbpIsK8=
|
||||
github.com/pmezard/go-difflib v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
@ -465,7 +462,6 @@ github.com/rs/zerolog v1.15.0/go.mod h1:xYTKnLHcpfU2225ny5qZjxnj9NvkumZYjJHlAThC
|
||||
github.com/russross/blackfriday/v2 v2.0.1/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts=
|
||||
github.com/samuel/go-zookeeper v0.0.0-20190923202752-2cc03de413da/go.mod h1:gi+0XIa01GRL2eRQVjQkKGqKF3SF9vZR/HnPullcV2E=
|
||||
github.com/satori/go.uuid v1.2.0/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
|
||||
github.com/sean-/seed v0.0.0-20170313163322-e2103e2c3529/go.mod h1:DxrIzT+xaE7yg65j358z/aeFdxmN0P9QXhEzd20vsDc=
|
||||
github.com/shopspring/decimal v0.0.0-20180709203117-cd690d0c9e24/go.mod h1:M+9NzErvs504Cn4c5DxATwIqPbtswREoFCre64PpcG4=
|
||||
github.com/shopspring/decimal v1.2.0 h1:abSATXmQEYyShuxI4/vyW3tV1MrKAJzCZ/0zLUXYbsQ=
|
||||
@ -504,15 +500,14 @@ github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/studio-b12/gowebdav v0.0.0-20211109083228-3f8721cd4b6f h1:L2NE7BXnSlSLoNYZ0lCwZDjdnYjCNYC71k9ClZUTFTs=
|
||||
github.com/studio-b12/gowebdav v0.0.0-20211109083228-3f8721cd4b6f/go.mod h1:bHA7t77X/QFExdeAnDzK6vKM34kEZAcE1OX4MfiwjkE=
|
||||
github.com/tmc/grpc-websocket-proxy v0.0.0-20170815181823-89b8d40f7ca8/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U=
|
||||
github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw=
|
||||
github.com/ugorji/go v1.2.6 h1:tGiWC9HENWE2tqYycIqFTNorMmFRVhNwCpDOpWqnk8E=
|
||||
github.com/ugorji/go v1.2.6/go.mod h1:anCg0y61KIhDlPZmnH+so+RQbysYVyDko0IMgJv0Nn0=
|
||||
github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY=
|
||||
github.com/ugorji/go/codec v1.2.6 h1:7kbGefxLoDBuYXOms4yD7223OpNMMPNPZxXk5TvFcyQ=
|
||||
github.com/ugorji/go/codec v1.2.6/go.mod h1:V6TCNZ4PHqoHGFZuSG1W8nrCzzdgA2DozYxWFFpvxTw=
|
||||
github.com/upyun/go-sdk/v3 v3.0.2 h1:Ke+iOipK5CT0xzMwsgJsi7faJV7ID4lAs+wrH1RH0dA=
|
||||
github.com/upyun/go-sdk/v3 v3.0.2/go.mod h1:P/SnuuwhrIgAVRd/ZpzDWqCsBAf/oHg7UggbAxyZa0E=
|
||||
github.com/urfave/cli v1.20.0/go.mod h1:70zkFmudgCuE/ngEzBv17Jvp/497gISqfk5gWijbERA=
|
||||
github.com/urfave/cli v1.22.1/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtXRu0=
|
||||
github.com/vmihailenco/msgpack v4.0.4+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk=
|
||||
@ -553,12 +548,12 @@ golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8U
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.0.0-20201203163018-be400aefbc4c/go.mod h1:jdWPYTVW3xRLrWPugEBEK3UY2ZEsg3UU495nc5E+M+I=
|
||||
golang.org/x/crypto v0.0.0-20210421170649-83a5a9bb288b/go.mod h1:T9bdIzuCu7OtxOm1hfPfRQxPLYneinmdGuTeoZ9dtd4=
|
||||
golang.org/x/crypto v0.0.0-20210616213533-5ff15b29337e/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg=
|
||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
||||
golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce h1:Roh6XWxHFKrPgC/EQhVubSAGQ6Ozk6IdxHSzt1mR0EI=
|
||||
golang.org/x/crypto v0.0.0-20220112180741-5e0467b6c7ce/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29 h1:tkVvjkPTB7pnW3jnid7kNyAMPVWllTNOf/qKDze4p9o=
|
||||
golang.org/x/crypto v0.0.0-20220331220935-ae2d96664a29/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
|
||||
golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE=
|
||||
golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU=
|
||||
@ -641,13 +636,14 @@ golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7w
|
||||
golang.org/x/sys v0.0.0-20210124154548-22da62e12c0c/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210309074719-68d13333faf2/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210423185535-09eb48e85fd7/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20211023085530-d6a326fbbf70 h1:SeSEfdIxyvwGJliREIJhRPPXvW6sDlLT+UQ3B0hD0NA=
|
||||
golang.org/x/sys v0.0.0-20211023085530-d6a326fbbf70/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.0.0-20220330033206-e17cdc41300f h1:rlezHXNlxYWvBCzNses9Dlc7nGFaNMJeqLolcmQSSZY=
|
||||
golang.org/x/sys v0.0.0-20220330033206-e17cdc41300f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/term v0.0.0-20201117132131-f5c789dd3221/go.mod h1:Nr5EML6q2oocZ2LXRh80K7BxOlk5/8JxuGnuhpl+muw=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1 h1:v+OssWQX+hTHEmOBgwxdZxK4zHq3yOs8F9J7mk0PY8E=
|
||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
||||
golang.org/x/text v0.0.0-20160726164857-2910a502d2bf/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
@ -657,8 +653,6 @@ golang.org/x/text v0.3.4/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/time v0.0.0-20180412165947-fbb02b2291d2/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/tools v0.0.0-20180221164845-07fd8470d635/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20180828015842-6cd1fcedba52/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
@ -747,26 +741,14 @@ gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
|
||||
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/mysql v1.1.2 h1:OofcyE2lga734MxwcCW9uB4mWNXMr50uaGRVwQL2B0M=
|
||||
gorm.io/driver/mysql v1.1.2/go.mod h1:4P/X9vSc3WTrhTLZ259cpFd6xKNYiSSdSZngkSBGIMM=
|
||||
gorm.io/driver/mysql v1.2.3 h1:cZqzlOfg5Kf1VIdLC1D9hT6Cy9BgxhExLj/2tIgUe7Y=
|
||||
gorm.io/driver/mysql v1.2.3/go.mod h1:qsiz+XcAyMrS6QY+X3M9R6b/lKM1imKmcuK9kac5LTo=
|
||||
gorm.io/driver/postgres v1.1.2 h1:Amy3hCvLqM+/ICzjCnQr8wKFLVJTeOTdlMT7kCP+J1Q=
|
||||
gorm.io/driver/postgres v1.1.2/go.mod h1:/AGV0zvqF3mt9ZtzLzQmXWQ/5vr+1V1TyHZGZVjzmwI=
|
||||
gorm.io/driver/postgres v1.2.3 h1:f4t0TmNMy9gh3TU2PX+EppoA6YsgFnyq8Ojtddb42To=
|
||||
gorm.io/driver/postgres v1.2.3/go.mod h1:pJV6RgYQPG47aM1f0QeOzFH9HxQc8JcmAgjRCgS0wjs=
|
||||
gorm.io/driver/sqlite v1.1.6 h1:p3U8WXkVFTOLPED4JjrZExfndjOtya3db8w9/vEMNyI=
|
||||
gorm.io/driver/sqlite v1.1.6/go.mod h1:W8LmC/6UvVbHKah0+QOC7Ja66EaZXHwUTjgXY8YNWX8=
|
||||
gorm.io/driver/sqlite v1.2.6 h1:SStaH/b+280M7C8vXeZLz/zo9cLQmIGwwj3cSj7p6l4=
|
||||
gorm.io/driver/sqlite v1.2.6/go.mod h1:gyoX0vHiiwi0g49tv+x2E7l8ksauLK0U/gShcdUsjWY=
|
||||
gorm.io/gorm v1.21.12/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
|
||||
gorm.io/gorm v1.21.15/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
|
||||
gorm.io/gorm v1.21.16 h1:YBIQLtP5PLfZQz59qfrq7xbrK7KWQ+JsXXCH/THlMqs=
|
||||
gorm.io/gorm v1.21.16/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
|
||||
gorm.io/gorm v1.22.3/go.mod h1:F+OptMscr0P2F2qU97WT1WimdH9GaQPoDW7AYd5i2Y0=
|
||||
gorm.io/gorm v1.22.4/go.mod h1:1aeVC+pe9ZmvKZban/gW4QPra7PRoTEssyc922qCAkk=
|
||||
gorm.io/gorm v1.22.5 h1:lYREBgc02Be/5lSCTuysZZDb6ffL2qrat6fg9CFbvXU=
|
||||
gorm.io/gorm v1.22.5/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
|
||||
gorm.io/driver/mysql v1.3.2 h1:QJryWiqQ91EvZ0jZL48NOpdlPdMjdip1hQ8bTgo4H7I=
|
||||
gorm.io/driver/mysql v1.3.2/go.mod h1:ChK6AHbHgDCFZyJp0F+BmVGb06PSIoh9uVYKAlRbb2U=
|
||||
gorm.io/driver/postgres v1.3.1 h1:Pyv+gg1Gq1IgsLYytj/S2k7ebII3CzEdpqQkPOdH24g=
|
||||
gorm.io/driver/postgres v1.3.1/go.mod h1:WwvWOuR9unCLpGWCL6Y3JOeBWvbKi6JLhayiVclSZZU=
|
||||
gorm.io/driver/sqlite v1.3.1 h1:bwfE+zTEWklBYoEodIOIBwuWHpnx52Z9zJFW5F33WLk=
|
||||
gorm.io/driver/sqlite v1.3.1/go.mod h1:wJx0hJspfycZ6myN38x1O/AqLtNS6c5o9TndewFbELg=
|
||||
gorm.io/gorm v1.23.1 h1:aj5IlhDzEPsoIyOPtTRVI+SyaN1u6k613sbt4pwbxG0=
|
||||
gorm.io/gorm v1.23.1/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
|
||||
honnef.co/go/tools v0.0.0-20180728063816-88497007e858/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4=
|
||||
|
159
model/account.go
159
model/account.go
@ -2,7 +2,9 @@ package model
|
||||
|
||||
import (
|
||||
"github.com/Xhofe/alist/conf"
|
||||
"github.com/Xhofe/alist/utils"
|
||||
log "github.com/sirupsen/logrus"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@ -48,6 +50,13 @@ type Account struct {
|
||||
CustomHost string `json:"custom_host"`
|
||||
ExtractFolder string `json:"extract_folder"`
|
||||
Bool1 bool `json:"bool_1"`
|
||||
// for xunlei
|
||||
Algorithms string `json:"algorithms"`
|
||||
ClientVersion string `json:"client_version"`
|
||||
PackageName string `json:"package_name"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
CaptchaToken string `json:"captcha_token"`
|
||||
DeviceId string `json:"device_id"`
|
||||
}
|
||||
|
||||
var accountsMap = make(map[string]Account)
|
||||
@ -97,6 +106,7 @@ func RegisterAccount(account Account) {
|
||||
accountsMap[account.Name] = account
|
||||
}
|
||||
|
||||
// GetAccount 根据名称获取账号(不包含负载均衡账号) 用于定时任务更新账号
|
||||
func GetAccount(name string) (Account, bool) {
|
||||
if len(accountsMap) == 1 {
|
||||
for _, v := range accountsMap {
|
||||
@ -107,25 +117,29 @@ func GetAccount(name string) (Account, bool) {
|
||||
return account, ok
|
||||
}
|
||||
|
||||
func GetAccountsByName(name string) []Account {
|
||||
accounts := make([]Account, 0)
|
||||
if AccountsCount() == 1 {
|
||||
account, _ := GetAccount("")
|
||||
accounts = append(accounts, account)
|
||||
return accounts
|
||||
}
|
||||
for _, v := range accountsMap {
|
||||
if v.Name == name || v.Name == name+balance {
|
||||
accounts = append(accounts, v)
|
||||
}
|
||||
}
|
||||
return accounts
|
||||
}
|
||||
// GetAccountsByName 根据名称获取账号(包含负载均衡账号)
|
||||
//func GetAccountsByName(name string) []Account {
|
||||
// accounts := make([]Account, 0)
|
||||
// if AccountsCount() == 1 {
|
||||
// for _, v := range accountsMap {
|
||||
// accounts = append(accounts, v)
|
||||
// }
|
||||
// return accounts
|
||||
// }
|
||||
// for _, v := range accountsMap {
|
||||
// if v.Name == name || strings.HasPrefix(v.Name, name+balance) {
|
||||
// accounts = append(accounts, v)
|
||||
// }
|
||||
// }
|
||||
// return accounts
|
||||
//}
|
||||
|
||||
var balanceMap sync.Map
|
||||
|
||||
// GetBalancedAccount 根据名称获取账号,负载均衡之后的
|
||||
func GetBalancedAccount(name string) (Account, bool) {
|
||||
accounts := GetAccountsByName(name)
|
||||
accounts := GetAccountsByPath(name)
|
||||
log.Debugf("accounts: %+v", accounts)
|
||||
accountNum := len(accounts)
|
||||
switch accountNum {
|
||||
case 0:
|
||||
@ -147,6 +161,7 @@ func GetBalancedAccount(name string) (Account, bool) {
|
||||
}
|
||||
}
|
||||
|
||||
// GetAccountById 根据id获取账号,用于更新账号
|
||||
func GetAccountById(id uint) (*Account, error) {
|
||||
var account Account
|
||||
account.ID = id
|
||||
@ -156,31 +171,117 @@ func GetAccountById(id uint) (*Account, error) {
|
||||
return &account, nil
|
||||
}
|
||||
|
||||
func GetAccountFiles() ([]File, error) {
|
||||
files := make([]File, 0)
|
||||
// GetAccountFiles 获取账号虚拟文件(去除负载均衡)
|
||||
//func GetAccountFiles() ([]File, error) {
|
||||
// files := make([]File, 0)
|
||||
// var accounts []Account
|
||||
// if err := conf.DB.Order(columnName("index")).Find(&accounts).Error; err != nil {
|
||||
// return nil, err
|
||||
// }
|
||||
// for _, v := range accounts {
|
||||
// if strings.Contains(v.Name, balance) {
|
||||
// continue
|
||||
// }
|
||||
// files = append(files, File{
|
||||
// Name: v.Name,
|
||||
// Size: 0,
|
||||
// Driver: v.Type,
|
||||
// Type: conf.FOLDER,
|
||||
// UpdatedAt: v.UpdatedAt,
|
||||
// })
|
||||
// }
|
||||
// return files, nil
|
||||
//}
|
||||
|
||||
// GetAccounts 获取所有账号
|
||||
func GetAccounts() ([]Account, error) {
|
||||
var accounts []Account
|
||||
if err := conf.DB.Order("`index`").Find(&accounts).Error; err != nil {
|
||||
if err := conf.DB.Order(columnName("index")).Find(&accounts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return accounts, nil
|
||||
}
|
||||
|
||||
// GetAccountsByPath 根据路径获取账号,最长匹配,未负载均衡
|
||||
// 如有账号: /a/b,/a/c,/a/d/e,/a/d/e.balance
|
||||
// GetAccountsByPath(/a/d/e/f) => /a/d/e,/a/d/e.balance
|
||||
func GetAccountsByPath(path string) []Account {
|
||||
accounts := make([]Account, 0)
|
||||
curSlashCount := 0
|
||||
for _, v := range accountsMap {
|
||||
name := utils.ParsePath(v.Name)
|
||||
bIndex := strings.LastIndex(name, balance)
|
||||
if bIndex != -1 {
|
||||
name = name[:bIndex]
|
||||
}
|
||||
if name == "/" {
|
||||
name = ""
|
||||
}
|
||||
// 不是这个账号
|
||||
if path != name && !strings.HasPrefix(path, name+"/") {
|
||||
continue
|
||||
}
|
||||
slashCount := strings.Count(name, "/")
|
||||
// 不是最长匹配
|
||||
if slashCount < curSlashCount {
|
||||
continue
|
||||
}
|
||||
if slashCount > curSlashCount {
|
||||
accounts = accounts[:0]
|
||||
curSlashCount = slashCount
|
||||
}
|
||||
accounts = append(accounts, v)
|
||||
}
|
||||
sort.Slice(accounts, func(i, j int) bool {
|
||||
return accounts[i].Name < accounts[j].Name
|
||||
})
|
||||
return accounts
|
||||
}
|
||||
|
||||
// GetAccountFilesByPath 根据路径获取账号虚拟文件
|
||||
// 如有账号: /a/b,/a/c,/a/d/e,/a/b.balance1,/av
|
||||
// GetAccountFilesByPath(/a) => b,c,d
|
||||
func GetAccountFilesByPath(prefix string) []File {
|
||||
files := make([]File, 0)
|
||||
accounts := make([]Account, AccountsCount())
|
||||
i := 0
|
||||
for _, v := range accountsMap {
|
||||
accounts[i] = v
|
||||
i += 1
|
||||
}
|
||||
sort.Slice(accounts, func(i, j int) bool {
|
||||
if accounts[i].Index == accounts[j].Index {
|
||||
return accounts[i].Name < accounts[j].Name
|
||||
}
|
||||
return accounts[i].Index < accounts[j].Index
|
||||
})
|
||||
prefix = utils.ParsePath(prefix)
|
||||
set := make(map[string]interface{})
|
||||
for _, v := range accounts {
|
||||
if strings.HasSuffix(v.Name, balance) {
|
||||
// 负载均衡账号
|
||||
if strings.Contains(v.Name, balance) {
|
||||
continue
|
||||
}
|
||||
full := utils.ParsePath(v.Name)
|
||||
if len(full) <= len(prefix) {
|
||||
continue
|
||||
}
|
||||
// 不是以prefix为前缀
|
||||
if !strings.HasPrefix(full, prefix+"/") && prefix != "/" {
|
||||
continue
|
||||
}
|
||||
name := strings.Split(strings.TrimPrefix(strings.TrimPrefix(full, prefix), "/"), "/")[0]
|
||||
if _, ok := set[name]; ok {
|
||||
continue
|
||||
}
|
||||
files = append(files, File{
|
||||
Name: v.Name,
|
||||
Name: name,
|
||||
Size: 0,
|
||||
Driver: v.Type,
|
||||
Type: conf.FOLDER,
|
||||
UpdatedAt: v.UpdatedAt,
|
||||
})
|
||||
set[name] = nil
|
||||
}
|
||||
return files, nil
|
||||
}
|
||||
|
||||
func GetAccounts() ([]Account, error) {
|
||||
var accounts []Account
|
||||
if err := conf.DB.Order("`index`").Find(&accounts).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return accounts, nil
|
||||
return files
|
||||
}
|
||||
|
@ -56,7 +56,7 @@ func ExtractFolder(files []File, account *Account) {
|
||||
return
|
||||
}
|
||||
front := account.ExtractFolder == "front"
|
||||
sort.Slice(files, func(i, j int) bool {
|
||||
sort.SliceStable(files, func(i, j int) bool {
|
||||
if files[i].IsDir() || files[j].IsDir() {
|
||||
if !files[i].IsDir() {
|
||||
return !front
|
||||
@ -84,3 +84,7 @@ func (f File) ModTime() time.Time {
|
||||
func (f File) IsDir() bool {
|
||||
return f.Type == conf.FOLDER
|
||||
}
|
||||
|
||||
func (f File) GetType() int {
|
||||
return f.Type
|
||||
}
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user